当前位置:网站首页>安卓开发——服务应用,计时器的实现(线程+服务)
安卓开发——服务应用,计时器的实现(线程+服务)
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
边栏推荐
猜你喜欢
Android emulator error: x86 emulation currently requires hardware acceleration solution
1.操作系统是干什么的?
嘉宾专访|2020 PostgreSQL亚洲大会阿里云数据库专场:樊文凯
python生日贺卡制作以及细节问题的解决最后把python项目发布为exe可执行程序过程
Commodity management system -- integrate warehouse services and obtain warehouse list
程序员的十年之痒
Mac 终端(terminal) oh-my-zsh+solarized配置
Initial installation of linx7.5
range_sensor_layer
The file size uploaded by WordPress import exceeds php.ini Upload defined in_ max_ Filesize value -- & gt; solution.
随机推荐
How does FC game console work?
OSChina 周一乱弹 —— 程序媛的青春
图节点分类与消息传递 - 知乎
Exception capture and handling in C + +
【QT】子类化QThread实现多线程
商品管理系统——整合仓库服务以及获取仓库列表
Service grid is still difficult - CNCF
商品管理系统——SPU检索功能
In 2020, what are the best tools for Android developers to break the cold winter?
Several rolling captions based on LabVIEW
Rainbow sorting | Dutch flag problem
Mac 必备优质工具推荐
The whole process of building a fully distributed cluster
百亿级数据分表后怎么分页查询?
彩虹排序 | 荷兰旗问题
When iperf is installed under centos7, the solution of make: * no targets specified and no makefile found. Stop
Apache Iceberg 中三种操作表的方式
Graph node classification and message passing
理解 OC 中 RunLoop
Bifrost 之 文件队列(一)