onStartJob和onStopJob无法在android中运行以运行后台线程 [英] onStartJob and onStopJob Not Working in android to run background Thread

查看:337
本文介绍了onStartJob和onStopJob无法在android中运行以运行后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我希望使用JobScheduler进行通知,即使应用程序是否处于活动状态也是如此.我是刚接触android的新手,只是想尝试运行后台AsyncTask来检查其是否工作正常,但无法正常工作.

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.

这是我的JobService代码:

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类:

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代码:

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"
      />

注意:我正在使用API​​ 21,因为它是必需的.请指导我在哪里出错.在此先感谢

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

推荐答案

Android版本<上的setPeriodic()存在一些问题. N(尽管我没有发布官方链接).您需要使用setMinimuLatency()使其适用于所有版本

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();
   }

工作正常,但要花费5秒以上的时间才能再次执行

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

基于 setMinimumLatency()的文档:

在未完成此任务之前毫秒的时间

基于 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.

在我的代码中,我想每隔5个检查并发送FCM通知 分钟,甚至应用程序是否处于活动状态

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

这样做不是一个好主意.您永远不能保证打the睡模式启动后每5分钟就会成功执行任务.

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.

尽管有其他选择,例如创建前台服务或每5分钟触发一次AlarmManager,但是这些方法会消耗大量电池.

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

您可以改为减少通知服务器的频率.假设每天每2个小时或两次.但是,使用JobScheduler您将无法查明确切的时间.如果您的要求是确切时间,请使用AlarmManager.请参考此链接,以检查如何实现此链接

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

这篇关于onStartJob和onStopJob无法在android中运行以运行后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆