我正在尝试开发 JobScheduler
,我希望该应用在被系统杀死时每1分钟做某事。
androidManifest.xml
<service
android:name=".BaiduPush.BaiduJobService"
android:enabled="true"
android:permission="android.permission.BIND_JOB_SERVICE"/>
MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main2)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
startJobService()
}
}
private fun startJobService() {
Log.d(TAG,"startBaiduJobService")
val JOB = 10
val jobScheler = getSystemService((Context.JOB_SCHEDULER_SERVICE)) as JobScheduler
val jobinfo = JobInfo.Builder(JOB, ComponentName(packageName,BaiduJobService::class.java.name))
//.setPeriodic(AlarmManager.INTERVAL_FIFTEEN_MINUTES)
.setOverrideDeadline(60000)
.setPersisted(true)
.build()
jobScheler.schedule(jobinfo)
}
baidujobservice
class BaiduJobService : JobService() {
val TAG = "BaiduJobService"
override fun onStartJob(params: JobParameters?): Boolean {
Log.d(TAG,"BaiduJobService onStartJob")
return true
}
override fun onStopJob(params: JobParameters?): Boolean {
return false
}
}
当我使用setPeriodic(AlarmManager.INTERVAL_FIFTEEN_MINUTES)
时。onStartJob
尚未调用。
当我使用setOverrideDeadline(60000)
时。onStartJob
首先仅显示一次。
但是,时间到了,BaiduJobService
似乎没有调用。
我错过了什么吗?预先感谢。
我正在使用警报管理器来保持服务的活力,这比作业调度程序更好。我在Service OnCreate((方法中实现此代码。
public class CallService extends Service {
@Override
public void onCreate() {
super.onCreate();
Intent intent = new Intent(this, RestartServiceBroadcast.class);
mKeepAlivePendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
((AlarmManager) this.getSystemService(Context.ALARM_SERVICE)).setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60000, 60000, mKeepAlivePendingIntent);
}
}
创建Broadcastreceiver在OnRecieve
中再次致电服务public class RestartServiceBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("service.RestartService")) {
// Here Call a Service
}
}
}
像这样的表现
<receiver
android:name=".service.receiver.RestartServiceBroadcast"
android:enabled="true"
android:exported="true"
android:process=":sipStack">
<intent-filter>
<action android:name="service.RestartService" />
</intent-filter>
</receiver>
<service
android:name=".service.CallService"
android:enabled="true"
android:exported="false"
android:stopWithTask="false">
</service>