当前位置:网站首页>Clock service Android implementation of alarm clock
Clock service Android implementation of alarm clock
2020-11-09 12:12:00 【osc_35cfk3ig】
ClockService Android service application realizes alarm clock
establish ClockActivity, You can enter a time ( Use Time The text box ), Create another ClockService It's used for timing , When it's time , In the Activity To give notice of ( Underneath TextView It shows that “ Time out ”).
Be careful : This is where Service operation Activity



The experimental steps : Use BoundService Way to start the service
1、 First define the layout file , I won't go over it here

3、 Define a Service Service , Then define a class MyBinder The inner class of , Used to get Service Object and the Service Object state . Methods that must be implemented in inner classes onBind Method returns MyBinder service object . Define a... In an inner class getHandler Method to get Handler Object is used for MainActivity and MyService Message passing between .

Handler The key message passing code is as follows :


4、 establish MainActivity Click events in ,

5、 Service binding needs to be created ServiceConnection Object and implement the corresponding methods , And then rewriting onServiceConnected Method to get the background Service, The code is as follows :

- Activity_main.xml Code :
<?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=" alarm clock "
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=" Start "
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=" count down "
android:textSize="100sp"></TextView>
</LinearLayout>
- MyService.java Code
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(); // Methods that must be implemented , For binding between activities and services
}
public class MyBinder extends Binder {
MyHandler handler;
public MyService getMyService() {
return MyService.this;
}
public MyHandler getHandler() {
handler=new MyHandler();// Initialize a message object
return handler; // Return the message object
}
}
public class MyHandler extends Handler {
public String[] nums;
public String str;
public String str1;
public void handleMessage(Message msg) {
str1= String.valueOf(msg.obj); // obtain MainActivity The message in
Log.d(" residue ", str1);
new Thread(new Runnable() {
@Override
public void run() {
// Start a thread
nums=str1.split(":"); // Split the obtained string into an array
// Convert the time in a string to seconds
int time1=Integer.parseInt(nums[2])+60*60*Integer.parseInt(nums[1])+60*Integer.parseInt(nums[1]);
for(int time = time1;time>=0;time--){
// adopt for A loop is a cycle of time
if(time==0){
// If the countdown to 0, Is displayed ( Time out ) word
MainActivity.textView.setText(" Time out !");
}
try {
// take time Seconds are converted back to time strings
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); // update EditText Value
Thread.sleep(1000); // Thread to sleep 1 second
} 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) {
// If no value is entered , The default filling value is obtained (Hint)
str = String.valueOf(num.getHint());
}else {
str=num.getText().toString(); // Get the input value
}
flag = 1; // Used to judge the status of the button
btnStart.setText(" Pause ");
num.setEnabled(false); // take EditText Set to non editable
intent = new Intent(MainActivity.this, MyService.class); // Create a start Service Of Intent object
bindService(intent, conn, BIND_AUTO_CREATE); // Binding specifies Service
Log.d("time", String.valueOf(str));
} else {
flag = 0;
btnStart.setText(" Start ");
myBinder.getMyService().onDestroy();
}
}
});
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// Set up to communicate with the service
myBinder = (MyService.MyBinder) service; // Get the... In the service MyBinder object
Message message = new Message(); // Create message object
message.obj = str; // Pass parameters ,str Is the value obtained
MyService.MyHandler handler = myBinder.getHandler(); // obtain MyService Medium Handler object
handler.sendMessage(message); // adopt Handler Object to send a message
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
版权声明
本文为[osc_35cfk3ig]所创,转载请带上原文链接,感谢
边栏推荐
- Principle analysis and performance tuning of elasticsearch
- 在企业的降本增效诉求下,Cube如何助力科盾业务容器化“一步到位”?
- 阿里、腾讯、百度、网易、美团Android面试经验分享,拿到了百度、腾讯offer
- Android权限大全
- 10款必装软件,让Windows使用效率飞起!
- Shoes? Forecasting stock market trends? Taobao second kill? Python means what you want
- Show profile analysis of SQL statement performance overhead
- AI fresh student's annual salary has increased to 400000, you can still make a career change now!
- SHOW PROFILE分析SQL语句性能开销
- 共创爆款休闲游戏 “2020 Ohayoo游戏开发者沙龙”北京站报名开启
猜你喜欢

In the future, China Telecom will make cloud computing service the main business of China Telecom

The middle stage of vivo Monkey King activity

20201107第16课,使用Apache服务部署静态网站;使用Vsftpd服务传输文件

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

Android check box and echo

Method of creating flat panel simulator by Android studio

An attempt to read or write to protected memory occurred using the CopyMemory API. This usually indicates that other memory is corrupted.

TiDB x 微众银行 | 耗时降低 58%,分布式架构助力实现普惠金融

从编码、网络传输、架构设计揭秘腾讯云高质量、高可用实时音视频技术实践...

嘉宾专访|2020 PostgreSQL亚洲大会阿里云数据库专场:樊文凯
随机推荐
A simple way to realize terminal text paste board
使用rem,做到屏幕缩放时,字体大小随之改变
Wechat circle
Handwriting Koa.js Source code
Chrome browser engine blink & V8
In the future, China Telecom will make cloud computing service the main business of China Telecom
Python zero basics tutorial (01)
从编码、网络传输、架构设计揭秘腾讯云高质量、高可用实时音视频技术实践...
Interface tests how to pass files in post requests
Oh, my God! Printing log only knows log4j?
[design pattern] Chapter 4: Builder mode is not so difficult
The history of C1 research in Shenzhen
大型项目Objective-C - NSURLSession接入短信验证码应用实例分享
Reading design patterns adapter patterns
在嵌入式设备中实现webrtc的第三种方式③
Show profile analysis of SQL statement performance overhead
JVM学习(四)-垃圾回收器和内存分配
共创爆款休闲游戏 “2020 Ohayoo游戏开发者沙龙”北京站报名开启
An attempt to read or write to protected memory occurred using the CopyMemory API. This usually indicates that other memory is corrupted.
List of wechat video Number broadcasters October 2020