JobSchedulerService电池消耗过多警告

时间:2018-10-01 14:22:25

标签: android-jobscheduler

MainActivity.class

Intent receiverIntent = new Intent(context, AlarmReceiver.class);
        sendBroadcast(receiverIntent);
        PendingIntent pendingIntentRepeating = PendingIntent.getBroadcast(context, 79, receiverIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 24 * 60 * 1000, pendingIntentRepeating);

AlarmReceiver.class

public class AlarmReceiver extends BroadcastReceiver {

@SuppressLint("UnsafeProtectedBroadcastReceiver")
@Override
public void onReceive(final Context context, Intent intent) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        scheduler.cancel(208352939);

        ComponentName componentName = new ComponentName(context, JobSchedulerService.class);
        JobInfo info = new JobInfo.Builder(208352939, componentName)
                .setPersisted(true)
                .setOverrideDeadline(5000)
                .build();

        scheduler.schedule(info);
    }
}

}

JobSchedulerService.class

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class JobSchedulerService extends JobService {

private boolean jobCancelled = false;

@SuppressLint("SimpleDateFormat")
@Override
public boolean onStartJob(JobParameters params) {
    Fabric.with(context, new Crashlytics());
    doBackgroundWork(params);
    return true;
}

private void doBackgroundWork(final JobParameters params) {
    new Thread(new Runnable() {
        @SuppressLint("SimpleDateFormat")
        @Override
        public void run() {

            for (int j = 0; j < trm; j++) {

                //my code

                if (jobCancelled) {
                    return;
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            jobFinished(params, false);
        }
    }).start();
}

@Override
public boolean onStopJob(JobParameters params) {
    jobCancelled = true;
    return true;
  }
}

我每两秒钟触发一次。但是,几天后,它会发出更多的电池消耗警告……还是应该尝试其他方法?这是什么原因。我觉得有必要向您寻求帮助。预先感谢。

0 个答案:

没有答案