onStartJob and onStopJob Not Working in android to run background Thread

梦想与她 提交于 2019-12-08 07:42:29

问题


Actually I want to use JobScheduler for Notification even app is active or not. I am new to android first just am trying to run background AsyncTask to check if its working fine but its not working.

Here is My JobService Code:

public class JobSchedularClass extends JobService {
    private static final String TAG = "JobSchedularClass";

   private BackgroundJob backgroundJob;
    @Override
    public boolean onStartJob(final JobParameters params) {

        Log.d(TAG, "onStartJob: ");

         backgroundJob=new BackgroundJob(){
            @Override
            protected void onPostExecute(String s) {
                Toast.makeText(getApplicationContext(),s+"kjk",Toast.LENGTH_SHORT).show();
                jobFinished(params,false);

            }
        };

        backgroundJob.execute();
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d(TAG, "onStopJob: ");
        backgroundJob.cancel(true);
        return false;
    }
}

AsyncTask Class:

public class BackgroundJob extends AsyncTask<Void,Void,String> {
    private static final String TAG = "BackgroundJob";
    @Override
    protected String doInBackground(Void... voids) {
        Log.d(TAG, "doInBackground: ");
        return "BackGround Job is running";
    }
}

MainActivity Code:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ComponentName componentName=new ComponentName(MainActivity.this,JobSchedularClass.class);
         jobInfo =new JobInfo.Builder(code,componentName)
        .setPeriodic(5000)
        .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
        .setPersisted(true)
         .build();
      jobScheduler=(JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);

    }

    public void Startjob(View view) {
       int code_result= jobScheduler.schedule(jobInfo);
        Toast.makeText(this," Job scheduling...",Toast.LENGTH_SHORT).show();
       if(code_result==JobScheduler.RESULT_SUCCESS){
           Toast.makeText(this," Job scheduling done...",Toast.LENGTH_SHORT).show();
       }
       else{
           Toast.makeText(this," Job scheduling  failed...",Toast.LENGTH_SHORT).show();
       }

    }

    public void Stopjob(View view) {

        jobScheduler.cancel(code);
        Toast.makeText(this," Job cancel...",Toast.LENGTH_SHORT).show();
    }

Here is Manifest Permissions and service Registered code:

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  <service android:name=".JobSchedularClass"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:exported="true"
      />

Note: I am using API 21 as it Required. Please guide me where I am making mistake. Thanks In Advance


回答1:


There were some issues with setPeriodic() on Android Version < N (Although I don't have official link to issue). You need to use setMinimuLatency() to make it work across all version

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        jobInfo = new JobInfo.Builder(id, name)
                .setMinimumLatency(5000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build();
    } else {
        jobInfo = new JobInfo.Builder(id, name)
                .setPeriodic(5000)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                .setPersisted(true)
                .build();
   }

working fine but time is taking longer than 5 second to execute again

Based on the documentation for setMinimumLatency():

Milliseconds before which this job will not be considered for execution

Based on the documentation for setPeriodic():

You have no control over when within this interval this job will be executed, only the guarantee that it will be executed at most once within this interval

Overall you cannot control when the scheduled job will be executed. The system will decide when to execute it.

In my code I want to check and send FCM notification after every 5 minutes even app is active or not

Its not a great idea to do it. You can never guarantee that you will successfully execute the task ever 5 minutes when the doze mode kicks in.

Although there are alternatives like creating foreground service or triggering your AlarmManager every 5 minutes, but these approaches will drain battery.

You can instead reduce the frequency with which you notify your server. Lets say every 2 hours or twice in a day. But using JobScheduler you won't be able to pin point the exact time. If your requirement is exact time, then go for AlarmManager. Refer this link to check how it can be achieved



来源:https://stackoverflow.com/questions/50099403/onstartjob-and-onstopjob-not-working-in-android-to-run-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!