backgroundtask android java,每x秒永久

c9x0cxw0  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(417)

到目前为止,我一直使用“alertmanager”来执行后台任务。这在新的android版本上已经不能正常工作了。必须每15秒启动一次,在任何情况下都不能被系统停止。重新启动手机时,后台任务也必须启动。现在后台任务只启动了一次,然后就什么也没发生了。
有解决办法吗?
我就是这样计划我的任务的:
主活动.java

  1. AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  2. Intent startServiceIntent = new Intent(context, hintergrundModus.class);
  3. PendingIntent startServicePendingIntent = PendingIntent.getService(context,0,startServiceIntent,0);
  4. Calendar calendar = Calendar.getInstance();
  5. calendar.setTimeInMillis(System.currentTimeMillis());
  6. if(alarmManager != null)
  7. alarmManager.set(AlarmManager.RTC_WAKEUP,hintergrundModus.timeHintergrundmodus,startServicePendingIntent);
6uxekuva

6uxekuva1#

对于较新版本的android,您需要替换 IntentServiceandroidx.core.app.JobIntentService . (别忘了删除 IntentService#onBind(Intent) ,否则您的服务将永远无法启动)

  1. class hintergrundModus extends IntentService
  2. @Override
  3. protected IBinder onBind(Intent arg0) {
  4. return null
  5. }
  6. @Override
  7. protected void onHandleIntent(Intent arg0) {
  8. ...
  9. }
  10. }

将成为

  1. import androidx.core.app.JobIntentService;
  2. class hintergrundModus extends JobIntentService {
  3. @Override
  4. public void onHandleWork(Intent arg0) {
  5. ...
  6. }
  7. }

对于 AlarmManager ,您也不再直接使用 PendingIntent#getService ,但将创建一个中介 BroadcastReceiver 当调用时,它可以将您的工作排队。

  1. import static androidx.core.app.JobIntentService.enqueueWork;
  2. public class ServiceLaunchReceiver extends BroadcastReceiver {
  3. public static final String RECEIVER_KEY = "com.package.ACTION";
  4. public static final int UNIQUE_JOB_ID = 0;
  5. @Override
  6. public void onReceive(Context context, Intent intent) {
  7. if (intent.getAction().equals(RECEIVER_KEY)) {
  8. enqueueWork(context, hintergrundModus.class, UNIQUE_JOB_ID , intent);
  9. }
  10. }
  11. }

然后可以引用 PendingIntent#getBroadcast ```
Intent launcherReceiverIntent = new Intent(context, ServiceLaunchReceiver.class);
PendingIntent startServicePendingIntent = PendingIntent.getBroadcast(context, 0, launcherReceiverIntent, 0);

  1. 你也可以考虑使用 `AlarmManager#setExact` 或者 `AlarmManager#setExactAndAllowWhileIdle` 在运行api 19或更高版本的设备上,如果需要重复的计时精度。然后,您可以在中的工作完成后安排后续警报 `JobIntentService` 已完成,而不是安排重复报警。从这张纸条开始 `AlarmManager#set` :
  2. api 19开始,传递给此方法的触发时间被视为不精确的:在此时间之前不会传递警报,但可能会延迟一段时间并在稍后传递。
  3. 您还将发现,在终止后台应用程序方面,较新版本的android可能非常激进。因为您的服务似乎是短暂的,所以将其绑定到前台通知(通过 `startForeground(Int, Notification)` )可能不适合你。在这种情况下,您可能需要在运行时向用户请求电池优化排除,以避免系统限制。
  4. 最后,在 `BroadcastReceiver` 为了监听系统启动通知,请实现上面的代码,以便将新的 `JobIntentService` ,或安排第一个警报推迟到以后。
展开查看全部

相关问题