Job scheduler stops working if app killed android

Viewed 3017

Hi did a sample of JobScheduler in my app. This is how I initiate it

jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
ComponentName jobService = new ComponentName(getPackageName(),
        MyJobService.class.getName());
JobInfo jobInfo = new JobInfo.Builder(MYJOBID, jobService)
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        .setExtras(bundle).build();
jobScheduler.schedule(jobInfo);

And I showed a toast in the JobService:

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class MyJobService extends JobService {

public MyJobService() {
}

@Override
public boolean onStartJob(JobParameters params) {

   // UtilityMethods.showToast(this,params.getExtras().getString("json"));
    Toast.makeText(this,"test",Toast.LENGTH_SHORT).show();

    return false;
}

@Override
public boolean onStopJob(JobParameters params) {
    UtilityMethods.showToast(this,"onStop()");
    return false;
}

}

And this was working perfectly fine even I tried turning off the internet and killing app from background. I then tried building a similar thing in one of my libraries. I wrote the same code in the library and I am calling it from my app's MainActivity. But this time, When I kill app from background, it stops working. Can anyone tell me why?

My MainActivity where I initialize it

JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
ComponentName jobService = new ComponentName(getPackageName(),
        MyJobService.class.getName());
JobInfo jobInfo = new JobInfo.Builder(MYJOBID, jobService)
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY).build();
jobScheduler.schedule(jobInfo);

It is working when I start it from onCreate and not working if I start it from a callback funtion().

Any help is really appreciated.

2 Answers

Android> 7 automatically saves battery power. You must enable the app's battery saver stop

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent();
            String packageName = getPackageName();
            PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + packageName));
                startActivity(intent);
            }
        }

add this to AndroidManifest.xml

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
Related