Android实现定时功能,闹钟+前台服务
1.首先在MainActitvty里的Onclick启动服务
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_server:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stop_server:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
default:
break;
}
}
然后在Myservice里面添加下面的内容
在Oncreate方法里面,也就是服务第一次创建的时候加入下面代码
@Override
public void onCreate() {
super.onCreate();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = null;
channel = new NotificationChannel("sid", getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH); //sid标示可以改为别的
notificationManager.createNotificationChannel(channel);
Notification notification = new Notification.Builder(getApplicationContext(), "sid").build();
startForeground(1, notification); //开启前台服务模式,会在通知的位置弹出一个框。
}
}
然后在OnStartCommand里面添加下面代码
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
//这里写要运行的代码
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int interval = 30 * 1000; //30s 运行一次
long triggerTime = SystemClock.elapsedRealtime() + interval; //系统开机到现在的毫秒数+延迟执行时间
Intent i = new Intent(this, MyService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pi);
return super.onStartCommand(intent, flags, startId);
}
如果服务被销毁了想重新拉起,可以修改OnDestory代码如下
@Override
public void onDestroy() {
super.onDestroy();
Log.d("cxa", "MyService---->onDestroy,前台service被杀死");
// 重启自己
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getApplicationContext().startForegroundService(new Intent(getApplicationContext(), MyService.class));
} else {
getApplicationContext().startService(new Intent(getApplicationContext(), MyService.class));
}
}