1

您在我的應用程序中做了JobScheduler的示例。 這是我如何啓動它作業調度程序停止工作,如果應用程序死亡android

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

而且我發現在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; 
} 

} 

,這是工作完全正常的,甚至我試圖關閉網絡和後臺查殺應用程序。 然後我嘗試在我的一個庫中創建類似的東西。我在庫中編寫了相同的代碼,我從我的應用程序MainActivity中調用它。但這一次,當我從後臺殺死應用程序,它停止工作。誰能告訴我爲什麼?

MainActivity,我將其初始化

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

它工作時,我從開始的onCreate它,而不是工作,如果我從一個回調funtion啓動它()。

任何幫助真的很感激。

回答

1

製作這回真

@Override 
public boolean onStartJob(JobParameters params) { 

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

    return true; 
} 

,並從這裏開始一個新的線程(因爲這是在mainthread只執行)。

onStartJob 

added in API level 21 
boolean onStartJob (JobParameters params) 
Override this method with the callback logic for your job. Any such logic needs to be performed on a separate thread, as this function is executed on your application's main thread. 

Parameters 
params JobParameters: Parameters specifying info about this job, including the extras bundle you optionally provided at job-creation time. 
Returns 
boolean True if your service needs to process the work (on a separate thread). False if there's no more work to be done for this job. 
+0

我不明白..怎麼可能呢?你能解釋一下嗎? –

+0

我已經添加谷歌頁面的解釋,請讓我知道,如果它不清楚給你。 –