当前位置:网站首页>Android Development - service application, timer implementation (thread + service)
Android Development - service application, timer implementation (thread + service)
2020-11-09 10:56:00 【osc_t4xzns0d】
Experimental topics
- Implement a countdown clock , Create sub line to realize timing function , Use asynchronous message mechanism to display timing results on the interface , Pictured , Enter the number in the text box ( Use Number The text box ), After you click the start button , The number in the text box below is minus... Per second 1, Click stop to stop the countdown
- establish ClockActivity, You can enter a time , 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
Experiment 1
Code :
MainActivity :
public class MainActivity extends AppCompatActivity {
boolean iswork;
String number;
EditText edtNumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart=(Button)findViewById(R.id.btnStart);
Button btnStop=(Button)findViewById(R.id.btnStop);
final Handler handler=new Handler(){
public void handleMessage(Message msg){
edtNumber=(EditText)findViewById(R.id.edtNumber);
edtNumber.setText(String.valueOf(msg.what));
}
};
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText edtCount=(EditText)findViewById(R.id.edtNumber);
number=String.valueOf(edtCount.getText());
iswork=true;
new Thread(new Runnable() {
@Override
public void run() {
try {
for (int i=Integer.valueOf(number)-1;i>=0;i--){
if (iswork){
// One second apart
Thread.sleep(1000);
Message msg=new Message();
msg.what=i;
handler.sendMessage(msg);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (iswork){
// stop it
iswork=false;
}
}
});
}
}
Layout file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="150dp"
android:layout_marginLeft="15dp"
android:layout_height="wrap_content"
android:onClick="Camera_onClick"
android:id="@+id/btnStart"
android:text=" Start "></Button>
<Button
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:onClick="Album_onClick"
android:id="@+id/btnStop"
android:text=" stop it "></Button>
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="100"
android:textSize="150sp"
android:id="@+id/edtNumber"
android:background="#D3D3D3"
android:textAlignment="center"></EditText>
</LinearLayout>
Experiment two
Code :
ClockActivity :
public class ClockActivity extends AppCompatActivity {
private TextView tvClock;
public static final String CLOCK_ACTION="com.lcl.test8.Clock_Action";
public static int TIME=0;// The countdown time
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clock);
tvClock=(TextView)super.findViewById(R.id.tvClock);
// Registration of radio
regReceiver();
}
private void regReceiver(){
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(CLOCK_ACTION);
super.registerReceiver(clockReceiver, intentFilter);
}
// Radio receivers , from ClockService( Time service ) Broadcast of ,ClockService Broadcast every second
private BroadcastReceiver clockReceiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
changeTime();// change TextView Show time in
}
};
// Click on Button determine Start sending the broadcast , Start timing
public void StartTimeOnclick(View view){
EditText editTime = (EditText)findViewById(R.id.inputTime);
// Get input EditText Time for
String inputTime = String.valueOf(editTime.getText());
// Will get the string time with ":" Divided into , branch , second
String[] str =inputTime.split("[:]");
int hours = Integer.valueOf(str[0]).intValue();
int minutes = Integer.valueOf(str[1]).intValue();
int seconds = Integer.valueOf(str[2]).intValue();
TIME=hours*60*60*1000+minutes*60*1000+seconds*1000;
// Start the timer service
startService(new Intent(this,ClockService.class));
}
// Time shows dynamic change
private void changeTime(){
String timeStr="";
if(TIME==0){
timeStr=" Time out !";
}else{
int hour=TIME/(1000*60*60);
int minute=TIME%(1000*60*60)/(60*1000);
int second=(TIME%(1000*60*60))%(60*1000)/1000;
String hourStr = String.valueOf(hour);
String minuteStr =String.valueOf(minute);
String secondStr = String.valueOf(second);
if(hour<=9){
hourStr="0"+hour;
}
if(minute<=9){
minuteStr="0"+minute;
}
if (second<=9){
secondStr="0"+second;
}
timeStr= hourStr+":"+ minuteStr+ ":"+ secondStr;
}
tvClock.setText(timeStr);
}
}
ClockService :
public class ClockService extends Service {
public ClockService() {
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
countTime();// Perform timing function
return super.onStartCommand(intent, flags, startId);
}
// Realize timing function , Reduce the total time every second and MainActivity Send a broadcast
private void countTime() {
new Thread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(ClockActivity.CLOCK_ACTION);
while (true) {
try {
Thread.sleep(1000);
if (ClockActivity.TIME <= 0) {
sendBroadcast(intent);
break;
}
ClockActivity.TIME -= 1000;
sendBroadcast(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Layout file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="horizontal">
<EditText
android:layout_width="200dp"
android:layout_height="80dp"
android:id="@+id/inputTime"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:text=" Input time "
android:textAlignment="center"></EditText>
<Button
android:layout_width="150dp"
android:layout_height="80dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="20dp"
android:textSize="30dp"
android:text=" determine "
android:onClick="StartTimeOnclick"
/>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="400dp">
<TextView
android:layout_width="380dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="#BDBDBD"
android:text=" timing "
android:textSize="75dp"
android:id="@+id/tvClock"
android:gravity="center">
</TextView></RelativeLayout>
</LinearLayout>
Refer to the post :
https://blog.csdn.net/h2503652646/article/details/86471273
https://blog.csdn.net/weixin_33913377/article/details/93254934
版权声明
本文为[osc_t4xzns0d]所创,转载请带上原文链接,感谢
边栏推荐
- LTM understanding and configuration notes
- When Python calls ffmpeg, 'ffmpeg' is not an internal or external command, nor a runnable program
- After SQL group query, get the first n records of each group
- Several rolling captions based on LabVIEW
- Method of creating flat panel simulator by Android studio
- 2020,Android开发者打破寒冬的利器是什么?
- Explain Python input() function: get user input string
- 典型分布式系统分析:Dynamo
- 美国大选拜登获胜!硅谷的Python开发者用这种方式调侃懂王
- EasyNTS上云网关设备在雪亮工程项目中的实战应用
猜你喜欢
重新开始学习离散数学
el-table动态表头
操作系统之bios
WordPress Import 上传的文件尺寸超过php.ini中定义的upload_max_filesize值--&gt;解决方法。
基于synchronized锁的深度解析
图节点分类与消息传递 - 知乎
range_sensor_layer
Reading design patterns adapter patterns
Handwritten digital image recognition convolution neural network
Interview summary on November 7, 2020 (interview 12K)
随机推荐
首次开通csdn,这篇文章送给过去的自己和正在发生的你
2 normal mode
How to ensure that messages are not consumed repeatedly? (how to ensure the idempotent of message consumption)
From the practice, this paper discusses the problems caused by the inconsistent design of ruby syntax.
典型分布式系统分析:Dynamo
BIOS of operating system
for与for...in、for Each和map和for of
WordPress Import 上传的文件尺寸超过php.ini中定义的upload_max_filesize值--&gt;解决方法。
从实践谈 Ruby 语法上的几个设计不一致带来的问题。
2 普通模式
使用流读文件写文件处理大文件
el-table动态表头
操作系统之bios
1450. Number of students doing homework at a given time
For and for... In, for each and map and for of
共创爆款休闲游戏 “2020 Ohayoo游戏开发者沙龙”北京站报名开启
【QT】子类化QThread实现多线程
Complete set of linked list operations of data structure and algorithm series (3) (go)
再读《重构》
Unemployment log, November 5