我创建了一个Android应用程序,每隔5分钟将坐标发送到我的服务器,在6.0版本之后,当手机进入睡眠/休眠模式时,警报(我测试了每种类型的警报)每1或2小时被触发,尽管app是在白名单中!
我创建了一个firebase通知,只发送启动服务的数据,但结果是相同的,onMessageReceived在屏幕关闭后大约10分钟被触发,并在手机唤醒时再次启动... 我看到越来越多的话题关注这种情况,但没有人建议一个有效的解决方案。
有人知道我可以不停地在后台发送坐标吗?
请帮助我谢谢
答案 0 :(得分:0)
@Cristian你需要使用JobScheduler执行API 21以上的后台任务,这对你有用,请参考下面的链接
以下是定期执行JobService操作的示例:
ComponentName serviceComponent = new ComponentName(context, yourJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
builder.setRequiresDeviceIdle(false);
builder.setRequiresCharging(false);
builder.setPeriodic(60000); // <<<<---- 60 seconds interval
JobScheduler jobScheduler = (JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
https://developer.android.com/reference/android/app/job/JobScheduler.html
https://github.com/googlesamples/android-JobScheduler
OR
你可以使用firebase jobdispatcher它也会照顾设备的电池寿命,并且兼容API 9
答案 1 :(得分:0)
我有MyJobService扩展JobService
String TAG = "heyTaxiLOG";
@Override
public boolean onStartJob(JobParameters job) {
// Do some work here
Log.d(TAG,"JobService on Start");
//Start Service extends IntentService
startService(new Intent(this, GPSTracker.class));
return false; // Answers the question: "Is there still work going on?"
}
@Override
public boolean onStopJob(JobParameters job) {
return false; // Answers the question: "Should this job be retried?"
}
作为IntentService的GPSTracker从谷歌获取位置,没问题,对于发布来说太长了!
和调度程序在MainActivity中的OnCreate方法中调用
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag("GPS")
// one-off job
.setRecurring(true)
// don't persist past a device reboot
.setLifetime(Lifetime.FOREVER)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(180, 180))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(true)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
Constraint.ON_ANY_NETWORK
)
//.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
Firebase Job Dispatcher会运行吗?还处于打盹模式?