我的应用程序在后台运行时提供了模拟位置数据,使用诸如加速度计之类的传感器来检测用户的脚步。 我的后台服务在停止前仅运行一两分钟。我不确定我是否为Android O正确实施了后台服务,因为存在新的要求和限制。
在“主要活动”中,我通过以下几行启动服务:
Intent serviceIntent = new Intent();
BackgroundIntentService.enqueueWork(this, BackgroundIntentService.class, 6767, serviceIntent);
// Static variable to check in the JobIntentService if it should still run.
Config.backgroundServiceActive = true;
//Then I close the Mainactivity and the Service runs as expected in the background.
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
我的BackgroundIntentService是JobIntentService:
public class BackgroundIntentService extends JobIntentService {
@Override
protected void onHandleWork(@NonNull Intent intent) {
//here I create a new object which handles the sensors
//I also pass over the context of this JobIntentService
//This writes in the log just to check if the service is still running.
while (Config.backgroundServiceActive){
try{
Log.i("BackgroundService", "ICH AM AWAKE ");
}catch (Exception e) {
e.printStackTrace();
}
}
}
我已在清单中声明了该服务:
<service
android:name=".tools.BackgroundIntentService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false"/>
当MainActivity关闭并且我的服务在后台运行以完成其工作并写入日志时,一切看起来都很好。但是在1-2分钟后,服务便停止了。我做错了什么? 请确保您的回复考虑了Android O中的最新更改。
我使用了这个,这有点令人困惑:https://developer.android.com/training/run-background-service/create-service#java 这是https://developer.android.com/reference/androidx/core/app/JobIntentService