当前位置:网站首页>安卓开发——服务应用,计时器的实现(线程+服务)
安卓开发——服务应用,计时器的实现(线程+服务)
2020-11-09 10:56:00 【osc_t4xzns0d】
实验题目
- 实现一个倒计时时钟,创建子线实现计时功能,使用异步消息机制将计时结果显示在界面上,如图,在文本框中输入数字(使用Number文本框),点击开始按钮后,下方文本框的数字每秒减1,点击停止即停止倒计时
- 创建ClockActivity,可输入一个时间,再创建一个ClockService在用于计时,到时间后,以在Activity中发出通知(在下方的TextView中显示“时间到”)。
注意:这里涉及到了Service操作Activity
实验一
代码:
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){
//间隔一秒
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){
//停止
iswork=false;
}
}
});
}
}
布局文件:
<?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="开始"></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="停止"></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>
实验二
代码:
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;//倒计时的时间
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clock);
tvClock=(TextView)super.findViewById(R.id.tvClock);
//注册广播
regReceiver();
}
private void regReceiver(){
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction(CLOCK_ACTION);
super.registerReceiver(clockReceiver, intentFilter);
}
//广播接受者,接受来自ClockService(计时服务)的广播,ClockService每隔一秒钟发一次广播
private BroadcastReceiver clockReceiver=new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
changeTime();//改变TextView中的显示时间
}
};
//点击Button确定 开始发送广播,开始计时
public void StartTimeOnclick(View view){
EditText editTime = (EditText)findViewById(R.id.inputTime);
//获取输入EditText的时间
String inputTime = String.valueOf(editTime.getText());
//将获取的字符串时间用":"分割为时,分,秒
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;
//启动计时服务
startService(new Intent(this,ClockService.class));
}
//时间展示动态变化
private void changeTime(){
String timeStr="";
if(TIME==0){
timeStr="时间到!";
}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();//执行计时功能
return super.onStartCommand(intent, flags, startId);
}
//实现计时功能,每隔一秒减少总时间并MainActivity发送广播
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;
}
}
布局文件:
<?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="输入时间"
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="确定"
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="计时"
android:textSize="75dp"
android:id="@+id/tvClock"
android:gravity="center">
</TextView></RelativeLayout>
</LinearLayout>
参考博文:
https://blog.csdn.net/h2503652646/article/details/86471273
https://blog.csdn.net/weixin_33913377/article/details/93254934
版权声明
本文为[osc_t4xzns0d]所创,转载请带上原文链接,感谢
https://my.oschina.net/u/4383691/blog/4708759
边栏推荐
- SHOW PROFILE分析SQL语句性能开销
- Natural language processing (NLP) roadmap - KDnuggets
- Do you know how the computer starts?
- How to do thread dump analysis in Windows Environment
- Graph node classification and message passing
- 图节点分类与消息传递 - 知乎
- 商品管理系统——整合仓库服务以及获取仓库列表
- 卧槽,这年轻人不讲武德,应届生凭“小抄”干掉5年老鸟,成功拿到字节20Koffer
- range_sensor_layer
- 你不好奇 CPU 是如何执行任务的吗?
猜你喜欢
随机推荐
Graph node classification and message passing
彩虹排序 | 荷兰旗问题
财富自由梦缓?蚂蚁金服暂停上市,监管后估值或下跌
操作系统之bios
商品管理系统——SPU检索功能
《MFC dialog中加入OpenGL窗体》
商品管理系统——整合仓库服务以及获取仓库列表
Service grid is still difficult - CNCF
Open source projects for beginners on GitHub (Python)
Apache Iceberg 中三种操作表的方式
Natural language processing (NLP) roadmap - KDnuggets
Why don't we use graphql? - Wundergraph
Application of cloud gateway equipment on easynts in Xueliang project
14. Introduction to kubenetes
Android emulator error: x86 emulation currently requires hardware acceleration solution
从实践谈 Ruby 语法上的几个设计不一致带来的问题。
Oschina plays disorderly on Monday
结合阿里云 FC 谈谈我对 FaaS 的理解
When Python calls ffmpeg, 'ffmpeg' is not an internal or external command, nor a runnable program
SHOW PROFILE分析SQL语句性能开销





