您在我的应用中做了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)
.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启动它时它正在工作,如果我从回调函数()启动它就无法工作。
非常感谢任何帮助。
答案 0 :(得分:1)
让此返回true
@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.
答案 1 :(得分:1)
Android> 7自动节省电池电量。您必须启用该应用的省电功能停止
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);
}
}
将此添加到AndroidManifest.xml
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>