当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- For the first time open CSDN, this article is for the past self and what is happening to you
- Gather in Beijing! Openi / O 2020 Qizhi Developer Conference enters countdown
- 配置交换机Trunk接口流量本地优先转发(集群/堆叠)
- Composition - API
- [Python from zero to one] 5. Detailed explanation of beautiful soup basic syntax of web crawler
- 上周热点回顾(11.2-11.8)
- 050_ object-oriented
- Using stream to read and write files to process large files
- 你不好奇 CPU 是如何执行任务的吗?
- SQL第二章第三章
猜你喜欢
WordPress Import 上传的文件尺寸超过php.ini中定义的upload_max_filesize值--&gt;解决方法。
SQL statement to achieve the number of daffodils
El table dynamic header
JT-day09
5 个我不可或缺的开源工具
失业日志 11月5日
Complete set of linked list operations of data structure and algorithm series (3) (go)
结合阿里云 FC 谈谈我对 FaaS 的理解
nodejs学习笔记(慕课网nodejs从零开发web Server博客项目)
AI应届生年薪涨到40万了,你现在转行还来得及!
随机推荐
Understanding data structures starts with this article~
Source code analysis of ThinkPHP framework execution process
android studio创建平板模拟器方法
LTM理解及配置笔记记录
详解Python input()函数:获取用户输入的字符串
Review of hot spots of last week (11.2-11.8)
The whole process of building a fully distributed cluster
Impact of libssl on CentOS login
SQL第二章第三章
【QT】子类化QThread实现多线程
1486. Array XOR operation
结合阿里云 FC 谈谈我对 FaaS 的理解
Reading design patterns adapter patterns
JT-day09
SHOW PROFILE分析SQL语句性能开销
捕获冒泡?难道浏览器是鱼吗?
Interview summary on November 7, 2020 (interview 12K)
彩虹排序 | 荷兰旗问题
GitHub 上适合新手的开源项目(Python 篇)
Front end code style practice prettier + eslint + git hook + lint staged