温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在android应用中利用service实现一个计时器功能

发布时间:2020-12-05 17:00:47 来源:亿速云 阅读:617 作者:Leah 栏目:移动开发

本篇文章给大家分享的是有关如何在android应用中利用service实现一个计时器功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1、首先建立主页面的设计:activity_time.xml

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/self_driving_wait_ll"
 android:layout_width="match_parent"
 android:layout_height="match_parent">


 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:gravity="center"
 android:orientation="vertical">

 <TextView
  android:id="@+id/tv_time"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerInParent="true"
  android:layout_marginTop="20.0dp"
  android:gravity="center_horizontal"
  android:text="00:00:00"
  android:textSize="88.0sp" />
 </LinearLayout>
</RelativeLayout>

2、Activity的建立:TimeActivity

public class TimeActivity extends AppCompatActivity {

 public static String TIME_CHANGED_ACTION = "com.yy.time.TIME_CHANGED_ACTION";
 public static TextView tv_time;
 private SharedPreferencesUtil util;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_time);
 tv_time= (TextView) findViewById(R.id.tv_time);
 util=new SharedPreferencesUtil(this);
 util.saveString(MyContant.STARTTIME, StringUtils.gettime());
 startService(new Intent(this, TimeService.class));

 }
}

3、Service的建立:TimeService

public class TimeService extends Service {
private String TAG = "TimeService";
private Timer timer = null;
private Intent timeIntent = null;
private SharedPreferencesUtil util;

@Override
public void onCreate() {
 super.onCreate();
 Log.i(TAG,"TimeService->onCreate");
 //初始化
 this.init();
 //定时器发送广播
 timer.schedule(new TimerTask() {
 @Override
 public void run() {
  //发送广播
  sendTimeChangedBroadcast();
 }
 }, 1000,1000);
}
@Override
public IBinder onBind(Intent intent) {
 Log.i(TAG,"TimeService->onBind");
 return null;
}
/**
 * 相关变量初始化
 */
private void init(){
 util=new SharedPreferencesUtil(this);
 timer = new Timer();
 timeIntent = new Intent();
}

/**
 * 发送广播,通知UI层时间已改变
 */
private void sendTimeChangedBroadcast(){
 try {
 timeIntent.putExtra("time",getTime());
 timeIntent.setAction(TimeActivity.TIME_CHANGED_ACTION);
 //发送广播,通知UI层时间改变了
 sendBroadcast(timeIntent);
 } catch (ParseException e) {
 e.printStackTrace();
 }
}
/**
 * 获取最新时间
 * @return
 */
private String getTime() throws ParseException {

 String time;
 time=getsubtract(util.readString(MyContant.STARTTIME));
 return time;
}

//时间相减 得到计时时间
public String getsubtract(String starttime) throws ParseException {

 SimpleDateFormat myFormatter = new SimpleDateFormat( "hh:mm:ss");
 String newtime= StringUtils.gettime();
 Date date= myFormatter.parse(newtime);
 Date mydate= myFormatter.parse(starttime);
 int sec= (int) ((date.getTime()-mydate.getTime())/1000);
 int min=sec/60;
 int hour=min/60;

 if (sec >= 60) {
 sec = (sec % 60);
 }

 if (min >= 60) {
 min = (min % 60);
 }
 String hString;
 String mString;
 String string;
 if (hour < 10) {
 hString = "0" + String.valueOf(hour);
 } else {
 hString = String.valueOf(hour);
 }
 if (min < 10) {
 mString = "0" + String.valueOf(min);
 } else {
 mString = String.valueOf(min);
 }
 if (sec < 10) {
 string = "0" + String.valueOf(sec);
 } else {
 string = String.valueOf(sec);
 }

 return hString + ":" + mString + ":" + string;
}

@Override
public ComponentName startService(Intent service) {
 Log.i(TAG,"TimeService->startService");
 return super.startService(service);
}

@Override
public void onDestroy() {
 super.onDestroy();
 Log.i(TAG,"TimeService->onDestroy");
}
}

4、BroadcastReceiver广播接受者,更新UI界面的时间:UITimeReceiver

public class UITimeReceiver extends BroadcastReceiver {
private TimeActivity dUIActivity = new TimeActivity();
@Override
public void onReceive(Context context, Intent intent) {
 String action = intent.getAction();
 if(TimeActivity.TIME_CHANGED_ACTION.equals(action)){
 String strtime = intent.getStringExtra("time");
 //此处实现不够优雅,为了在UITimeReceiver中使用DynamicUIActivity中的TextView组件time,而将其设置为public类型,
 //更好的实现是将UITimeReceiver作为DynamicUIActivity的内部类
 dUIActivity.tv_time.setText(strtime);
 }
}
}

5、记住要在配置文件里面配置哦!

 <service android:name=".Service.TimeService"/>
 <receiver android:name=".Service.UITimeReceiver">
 <intent-filter>
  <action android:name="com.yy.time.TIME_CHANGED_ACTION"/>
 </intent-filter>
 </receiver>

以上就是如何在android应用中利用service实现一个计时器功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI