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));
}
}
本文作者:一起来学python
本文链接:https://www.cnblogs.com/c-x-a/p/16195383.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2018-04-26 python 666
2018-04-26 python 的requests如何使用代理
2016-04-26 Child Process模块