我创建了一个使用firebase服务的应用程序 . 只要值发生变化,就会生成通知 . 因此,我的服务必须持续运行,否则将无法通知 . 我创建并成功地让它在pre-oreo Android OS中运行 . 即使在从最近关闭并强行关闭之后我的服务也能完美运行,但在Oreo中却没有 . 谷歌搜索后,我开始知道奥利奥的服务自动启动是被禁止的 . 我们需要JobScheduler用于此目的 .
这是我的JobService课程 -
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
@RequiresApi(api = Build.VERSION_CODES.O)
public class Serviceo extends JobService {
private JobParameters params;
@Override
public boolean onStartJob(JobParameters jobParameters) {
this.params = jobParameters;
Log.d("HEYY","i'm here");
Intent service = new Intent(getApplicationContext(), NotificationService.class);
getApplicationContext().startService(service);
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return false;
}
}
PS-扩展JobService给出错误,它需要min api = 21,所以我使用 @RequiresApi(api = Build.VERSION_CODES.O) 纠正了它
在我的服务的 onDestroy
方法中,我声明我的JobService像这样 -
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent broadcastIntent = new Intent("com.mukesh.mu.RestarterBroadcastReceiver");
sendBroadcast(broadcastIntent);
stoptimertask();
Log.i("BRUHHH","hi");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.i("BRUHHH","hi2");
jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(),
Serviceo.class.getName()));
//run job service after every 5 seconds
builder.setPeriodic(5000);
jobScheduler.schedule(builder.build());
}
执行此方法但服务未开始 . 我可以在logcat“hi2”中看到执行 . 我也在清单中宣布它
<service
android:name="com.mukesh.mu.Serviceoreo"
android:permission="android.permission.BIND_JOB_SERVICE"
/>
通过Intent和广播,在Oreo之前的所有工作都很好并且正常,但是在Oreo中没有工作 .
1 回答
您可以尝试替代工作服务 - Firebase JobDispatcher