How to correctly use a JobService?

问题: I have implemented an application in Android that uses JobService to check for updates. I have tested it with some devices: Samsung J3, RedMi 5+, RedMi note pro, MI A2 lite...

问题:

I have implemented an application in Android that uses JobService to check for updates. I have tested it with some devices: Samsung J3, RedMi 5+, RedMi note pro, MI A2 lite. It is working correctly in J3 but, in other phones that I have tested JobService is not being scheduled if an application is not active or application is not in the recent apps list.

Here is how I have implemented.

MainActivity.java

public static void scheduleJob(Context context) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            JobScheduler js =
                    (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
            JobInfo job = new JobInfo.Builder(
                    MY_BACKGROUND_JOB,
                    new ComponentName(context, CheckAdService.class))
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                    .setPersisted(true)
                    .setPeriodic(15 * 60 * 1000)
                    .build();
            int resultCode = js.schedule(job);
            if (resultCode == JobScheduler.RESULT_SUCCESS) {
                Log.d("JOB", "Scheduled");
            } else {
                Log.d("JOB", "Not Scheduled");
            }
        }
    }

Service.java

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

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d("NetworkAvailable", "Flag No 2");
        doBackgroundWork(params);
        return true;
    }

    private void doBackgroundWork(final JobParameters params) {
        final Context context = getApplicationContext();
              ...

            IonDB ionDB = new IonDB(CheckAdService.this, "checkStatus");
            ionDB.getData(new OnDbData() {
                @Override
                public void OnDbDataReceived(JsonObject jsonObject, boolean withError) {
                   ...
                   // after notifying user with news I call jobFinished with rescheduling true option 
                     jobFinished(params, true);

                }
           });
     }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.d("DBDATA", "Job cancelled before completion");
        return true;
    }
}

Please correct my implementation of JobService so that it works in all android versions >= LOLLIPOP.

Considering that I'm new in Android if I made some coding mistakes please let me know any suggestion.


回答1:

I guess if you will use worker Manager it will be more correct.
It has capability between the different Android versions.

  • 发表于 2019-04-01 20:59
  • 阅读 ( 79 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除