在作业调度程序中使用BroadcastReceiver来检测节电器

时间:2018-03-30 05:07:13

标签: android broadcastreceiver android-jobscheduler

如何在jobScheduler中使用BroadcastReceiver?由于广播接收器的节电滤波器被发送到注册接收器,因此在清单中声明接收器不起作用。从此以后它应该在课堂上注册。我在jobScheduler中尝试过它(Plz看看下面的代码)但是它没有用。

public class MainActivity extends AppCompatActivity 
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (jobScheduler == null) {
            jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);

            ComponentName jobService =
                    new ComponentName(getPackageName(), MyJobService.class.getName());

            JobInfo jobInfo
                    = new JobInfo.Builder(MYJOBID, jobService).setPeriodic(15 * 60 * 1000L)
                    .setExtras(bundle)
                    .setPersisted(true)
                    .setRequiresDeviceIdle(false)
                    .build();

            int jobId = jobScheduler.schedule(jobInfo);

            if (jobScheduler.schedule(jobInfo) > 0) {
            } else {
            }
        }
    }
}

MyJobService.java

public class MyJobService extends JobService {

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        jobP = jobParameters;

    if (mLocationRequest == null) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(100 * 1000);
        mLocationRequest.setFastestInterval(60 * 1000);
    }

    if (client == null) {
        client = LocationServices.getFusedLocationProviderClient(this);
        client.requestLocationUpdates(mLocationRequest, new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                onLocationChanged(locationResult.getLastLocation());
            }
            @Override
            public void onLocationAvailability(LocationAvailability locationAvailability) {
            }
        },
        Looper.myLooper());
    }
    if (powerSaverChangeReceiver == null) {
        powerSaverChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.e("powerSaver", "powerSaver");
            }
        };
    }

    if (filter == null) {
        filter = new IntentFilter();
        filter.addAction("android.os.action.POWER_SAVE_MODE_CHANGED");
        registerReceiver(powerSaverChangeReceiver, filter);
    }
return true;
}

@Override
public boolean onStopJob(JobParameters jobParameters) {
    Log.e("onStopJob", "onStopJob");//for debug
    if (ul != null) {
        ul.cancel(true);
    }
    return true;
}

@Override
public void onDestroy() {
    unregisterReceiver(powerSaverChangeReceiver);
}
}

0 个答案:

没有答案