小弟原创文章,转载请注明本文出处
前言
公司之前做的一个电视机上的播报应用(类似于银行的那种播报“请某某某到几号窗口”),现在要我做个定时重启
正题
整体思路:定时任务在服务里执行,当时间等于某个特定的值就重启
服务的代码:
/**
* Created by mk_who on 2017/8/3/0003.
*/
public class MyService extends Service {
private IBinder mBinder=new Binder();
private Timer mTimer;
private TimerTask mTimerTask;
private Intent intent = new Intent("com.example.restart.RECEIVER");
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
mTimer = new Timer();
mTimerTask = new TimerTask() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String dateStr = sdf.format(new Date());
if (dateStr.equals("16:20")){
sendBroadcast(intent);//发送广播
}
}
}).start();
}
};
mTimer.schedule(mTimerTask,5000,59000);
mTimer=null;
mTimerTask=null;
}
@Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel();
mTimerTask.cancel();
}
}
开启服务的页面的部分代码:
private void startMyService() {
Intent intent = new Intent(getApplicationContext(), MyService.class);
bindService(intent, connServiceconn, BIND_AUTO_CREATE);
}
private Serviceconn connServiceconn = new Serviceconn();
private class Serviceconn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e("--------", "------开启服务成功---");
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
@Override
protected void onResume() {
super.onResume();
startMyService();//开启服务
filter.addAction("com.example.restart.RECEIVER");
registerReceiver(reStartReceiver, filter);
}
service跟activity通信的广播代码:
private BroadcastReceiver reStartReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("com.example.restart.RECEIVER")) {
finish();
Intent i = Main.this.getPackageManager()
.getLaunchIntentForPackage(Main.this.getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
};
当时是下午五点半(六点钟下班)接到的任务,着急下班吃饭(就是不想加班),就用了能想到的最简单的实现方式。