android 后台定时任务

以下功能可用JobScheduler、JobService更简单实现。

定义Service:

public class DemoService extends Service {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       
        //每隔两分钟定时发送广播 单位为毫秒值  120000=2分钟
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long triggerTime = SystemClock.elapsedRealtime() + 120000;
        Intent i = new Intent(this, DemoReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, pi);

        //doSomething
        return super.onStartCommand(intent, flags, startId);
    }
}

定义Receiver:

//收到广播即开启服务
public class DemoReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, DemoService.class));
    }
}

 

在需要开始定时任务的时候执行:

startService(new Intent(context, DemoService.class));

注意:在清单文件中注册service、Receiver.

android:exported、android:exported不是必须

BOOT_COMPLETED为开机启动时可以开始定时任务


    
        
    


 

你可能感兴趣的:(android 后台定时任务)