欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android 后台定时任务

程序员文章站 2022-07-14 18:26:12
...

以下功能可用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为开机启动时可以开始定时任务

<receiver android:name="com.demo.service.DemoReceiver"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
    </intent-filter>
</receiver>

<service android:name="com.demo.service.DemoService"
    android:enabled="true"
    android:exported="true"/>