创建一个名为AutoStartReceiver的广播接收器,在AndroidManifest.xml中注册,并在onReceive方法中启动需要自动运行的程序。
(图片来源网络,侵删)
创建广播接收器
1、在AndroidManifest.xml文件中注册广播接收器:
<receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>
2、创建一个名为MyBroadcastReceiver的类,继承自BroadcastReceiver:
public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { // 在这里编写自动运行的程序代码 } } }
使用AlarmManager定时执行任务
1、在AndroidManifest.xml文件中添加权限:
<uses-permission android:name="android.permission.WAKE_LOCK" />
2、创建一个名为MyAlarmService的服务类,继承自Service:
public class MyAlarmService extends Service { private AlarmManager alarmManager; private PendingIntent pendingIntent; private static final int REQUEST_CODE = 1; @Override public void onCreate() { super.onCreate(); alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent = new Intent(this, MyBroadcastReceiver.class); pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); } @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent != null && intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, pendingIntent); // 每隔60秒执行一次任务 } return super.onStartCommand(intent, flags, startId); } }
3、在AndroidManifest.xml文件中注册服务:
<service android:name=".MyAlarmService" />
4、在MainActivity中启动服务:
startService(new Intent(this, MyAlarmService.class));
5、在MyBroadcastReceiver的onReceive方法中停止服务:
stopService(new Intent(context, MyAlarmService.class));
问题与解答
(图片来源网络,侵删)
1、问题:如何取消定时任务?
解答:可以在MyBroadcastReceiver的onReceive方法中取消定时任务,调用alarmManager.cancel(pendingIntent)
方法,需要在MyAlarmService的onDestroy方法中取消定时任务,调用alarmManager.cancel(pendingIntent)
方法,在MainActivity中停止服务时,也需要取消定时任务。
(图片来源网络,侵删)
原创文章,作者:数码侠,如若转载,请注明出处:https://www.mingyunw.com/archives/96081.html