要解决Android定期作业调度器在运行10-12小时后停止的问题,可以使用以下方法:
方法一:使用AlarmManager和BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 执行定时任务的代码
}
}
public class MyService extends Service {
private static final long INTERVAL = 10 * 60 * 60 * 1000; // 10小时
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 创建定时任务
Intent alarmIntent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + INTERVAL, INTERVAL, pendingIntent);
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
方法二:使用Handler和Runnable
public class MyRunnable implements Runnable {
private static final long INTERVAL = 10 * 60 * 60 * 1000; // 10小时
private Handler handler;
public MyRunnable(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
// 执行定时任务的代码
// 重复调度任务
handler.postDelayed(this, INTERVAL);
}
}
public class MainActivity extends AppCompatActivity {
private Handler handler;
private MyRunnable myRunnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
myRunnable = new MyRunnable(handler);
handler.postDelayed(myRunnable, MyRunnable.INTERVAL);
}
}
在以上两种方法中,通过设置定时任务的重复间隔时间为10小时,即可让定期作业调度器每运行10-12小时后再次执行任务。
下一篇:android定时更新数据库