当前位置:网站首页>服务应用 ClockService安卓实现闹钟
服务应用 ClockService安卓实现闹钟
2020-11-09 12:12:00 【osc_35cfk3ig】
ClockService安卓服务应用实现闹钟
创建ClockActivity,可输入一个时间(使用Time文本框),再创建一个ClockService在用于计时,到时间后,以在Activity中发出通知(在下方的TextView中显示“时间到”)。
注意:这里涉及到了Service操作Activity



实验步骤:使用BoundService方式开启服务
1、首先定义布局文件,这里不做过多赘述

3、 定义一个Service服务类,然后在类里面定义一个MyBinder的内部类,用于获取Service对象与Service对象状态。在内部类中必须要实现的方法onBind方法返回MyBinder服务对象。在内部类中定义一个getHandler方法获取Handler对象用于MainActivity和MyService之间的消息传递。

Handler消息传递关键代码如下:


4、 创建MainActivity中的单击事件,

5、服务的绑定需要创建ServiceConnection对象并实现相应的方法,然后在重写的onServiceConnected方法中获取后台Service,代码如下:

- Activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="110dp"
android:layout_marginHorizontal="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="150dp"
android:layout_height="80dp"
android:layout_marginTop="15dp"
android:background="@drawable/shape"
android:gravity="center_horizontal"
android:text="闹钟"
android:textAlignment="center"
android:textSize="50sp"></TextView>
<EditText
android:autofillHints="true"
android:hint="10:10:10"
android:id="@+id/num"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:background="@drawable/shape"
android:gravity="center"
android:inputType="time"
android:textSize="35sp"></EditText>
</LinearLayout>
<Button
android:id="@+id/btnStart"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginHorizontal="20dp"
android:layout_marginTop="15dp"
android:background="@drawable/shape"
android:text="开始"
android:textSize="50sp"></Button>
<TextView
android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_margin="20dp"
android:background="@drawable/shape"
android:gravity="center"
android:text="倒计时"
android:textSize="100sp"></TextView>
</LinearLayout>
- MyService.java代码
package com.example.clock;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.EditText;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return new MyBinder(); //必须实现的方法,用于活动与服务之间的绑定
}
public class MyBinder extends Binder {
MyHandler handler;
public MyService getMyService() {
return MyService.this;
}
public MyHandler getHandler() {
handler=new MyHandler();//初始化一个消息对象
return handler; //返回该消息对象
}
}
public class MyHandler extends Handler {
public String[] nums;
public String str;
public String str1;
public void handleMessage(Message msg) {
str1= String.valueOf(msg.obj); //获取MainActivity中传递的消息
Log.d("渣", str1);
new Thread(new Runnable() {
@Override
public void run() {
//开启一个线程
nums=str1.split(":"); //将获取到的字符串拆分成数组
//将字符串中的时间转换成秒
int time1=Integer.parseInt(nums[2])+60*60*Integer.parseInt(nums[1])+60*Integer.parseInt(nums[1]);
for(int time = time1;time>=0;time--){
//通过for循环对对时间进行循环
if(time==0){
//如果时间倒计时到0,则显示(时间到)字样
MainActivity.textView.setText("时间到!");
}
try {
//将time秒重新转换成时间字符串
int hour = 0;
int minutes = 0;
int sencond = 0;
int temp = time % 3600;
if (time > 3600) {
hour = time / 3600;
if (temp != 0) {
if (temp > 60) {
minutes = temp / 60;
if (temp % 60 != 0) {
sencond = temp % 60;
}
} else {
sencond = temp;
}
}
} else {
minutes = time / 60;
if (time % 60 != 0) {
sencond = time % 60;
}
}
str=(hour<10?("0"+hour):hour) + ":" + (minutes<10?("0"+minutes):minutes)
+ ":" + (sencond<10?("0"+sencond):sencond);
MainActivity.num.setText(str); //及时更新EditText的值
Thread.sleep(1000); //线程休眠1秒
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
- MainAcivity.java
package com.example.clock;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
MyService.MyBinder myBinder;
public static EditText num;
int flag = 0;
String str;
Intent intent;
public static TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.text1);
final Button btnStart = (Button) findViewById(R.id.btnStart);
num = (EditText) findViewById(R.id.num);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (flag == 0) {
if (num.getText().length() < 1) {
//如果未输入数值,则获取默认填充值(Hint)
str = String.valueOf(num.getHint());
}else {
str=num.getText().toString(); //获取输入的值
}
flag = 1; //用于判断按钮状态
btnStart.setText("暂停");
num.setEnabled(false); //将EditText设置为不可编辑
intent = new Intent(MainActivity.this, MyService.class); //创建启动Service的Intent对象
bindService(intent, conn, BIND_AUTO_CREATE); //绑定指定Service
Log.d("time", String.valueOf(str));
} else {
flag = 0;
btnStart.setText("开始");
myBinder.getMyService().onDestroy();
}
}
});
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//设置与服务进行通信
myBinder = (MyService.MyBinder) service; //获取服务中的MyBinder对象
Message message = new Message(); //创建消息对象
message.obj = str; //传递参数,str是获取到的值
MyService.MyHandler handler = myBinder.getHandler(); //获取MyService中的Handler对象
handler.sendMessage(message); //通过Handler对象发送消息
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
版权声明
本文为[osc_35cfk3ig]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4354530/blog/4709340
边栏推荐
猜你喜欢

共创爆款休闲游戏 “2020 Ohayoo游戏开发者沙龙”北京站报名开启

美国大选拜登获胜!硅谷的Python开发者用这种方式调侃懂王

嗯,查询滑动窗口最大值的这4种方法不错...

Handwriting Koa.js Source code

Interface tests how to pass files in post requests

分库分表的 9种分布式主键ID 生成方案,挺全乎的

Method of creating flat panel simulator by Android studio

SQL语句实现水仙花数求取

iPhone“连到系统上的设备没有发挥作用”原因分析及解决方法 20200105

Android权限大全
随机推荐
天啦撸!打印日志竟然只晓得 Log4j?
使用流读文件写文件处理大文件
nodejs学习笔记(慕课网nodejs从零开发web Server博客项目)
美国大选拜登获胜!硅谷的Python开发者用这种方式调侃懂王
Android check box and echo
AI fresh student's annual salary has increased to 400000, you can still make a career change now!
What really drags you down is sunk costs
开源ERP招聘了
Interview summary on November 7, 2020 (interview 12K)
手写Koa.js源码
AI应届生年薪涨到40万了,你现在转行还来得及!
An attempt to read or write to protected memory occurred using the CopyMemory API. This usually indicates that other memory is corrupted.
Source code analysis of ThinkPHP framework execution process
el-table动态表头
On the calculation of non interaction polarizability
for与for...in、for Each和map和for of
如何用函数框架快速开发大型 Web 应用 | 实战
Looking for better dynamic getter and setter solutions
The middle stage of vivo Monkey King activity
EFF 认为 RIAA 正在“滥用 DMCA”来关闭 YouTube-DL