首先创建Service类 LongRunningService
public class LongRunningService extends Service { private static final String TAG = "LongRunningService"; @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(new Runnable() { @Override public void run() { //在这里执行具体的逻辑操作 Log.d(TAG, "run: "+"10秒执行一次!" ); } }).start(); //获取AlarmManager的实例 AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); int anHour = 10 * 1000; // SystemClock.elapsedRealtime()获取系统开机至今的毫秒数 long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this,LongRunningService.class); PendingIntent pi = PendingIntent.getService(this,0,i,0); //设置一个定时任务,这里设置的一个10秒之后执行一次 //AlarmManager.ELAPSED_REALTIME_WAKEUP 表示让定时任务的触发时间从系统开机开始算起,会唤醒CPU manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pi); return super.onStartCommand(intent, flags, startId); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } }
之后在Activity中启动定时服务
Intent intent = new Intent(this, LongRunningService.class); startService(intent);
这样一旦启动了LongRunningService,就会在onStartCommand()方法里设定一个定时任务,这样10秒后,就会再次再次启动LongRunningService,从而也就形成了一个永久循环,保证LongRunningService的onStartCommand()方法每隔10秒就执行一次。
最后别忘了在配置清单文件中注册
<service android:name=".service.LongRunningService"/>