我正在使用 FusedLocationProvider 开发位置跟踪应用程序。我有一个后台服务,每 5 分钟跟踪一次电话的位置。
一切正常,但一旦手机空闲 3 到 4 小时后,后台服务就会停止定位。当用户解锁手机时,跟踪再次开始。
有人可以指导我可能导致问题的原因吗?
我正在使用 FusedLocationProvider 开发位置跟踪应用程序。我有一个后台服务,每 5 分钟跟踪一次电话的位置。
一切正常,但一旦手机空闲 3 到 4 小时后,后台服务就会停止定位。当用户解锁手机时,跟踪再次开始。
有人可以指导我可能导致问题的原因吗?
一种可能是 Android M 打盹模式。当设备拔出并静止一段时间后,系统会尝试通过限制应用程序访问 CPU 密集型服务来节省电池电量。打盹模式在大约 1 小时不活动后启动,然后将定期任务等安排到维护窗口。当用户解锁设备时,打盹模式再次关闭。
您可以在开发者文档中找到有关打盹模式的更多信息:http: //developer.android.com/training/monitoring-device-state/doze-standby.html
也许您的服务正在停止,因为手机需要释放内存,因此它会终止您的服务。确保您的服务设置为前台服务。
前台服务是一种被认为是用户主动意识到的服务,因此不会在内存不足时被系统杀死。前台服务必须为状态栏提供通知,该通知位于“正在进行”标题下,这意味着除非服务停止或从前台删除,否则无法解除通知。 http://developer.android.com/guide/components/services.html
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
Android 会在闲置一段时间后让您的服务进入睡眠状态。您可以使用WakeLock来防止这种情况发生。
public int onStartCommand (Intent intent, int flags, int startId)
{
PowerManager mgr = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
mWakeLock.acquire();
...
return START_STICKY;
}
public void onDestroy(){
...
mWakeLock.release();
}