0
我正在编写一个应用程序,我需要从后台获得真正快速的位置更新。 因此,我写了一个服务来实现所需的结果。LocationListener在安卓服务的某个时间不提供更新
我从一个活动的onCreate()方法启动服务。
我面临的问题是,该服务能够提供从服务激活时间起约20至30秒的位置更新。然后我没有得到任何更新。
下面是服务的代码:
public class MyLocService extends Service
implements
LocationListener{
private final LocationListener locationListener = this;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
if (checkPermission()) {
manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
else{
//Request Permission
Intent permissionIntent = new Intent();
permissionIntent.setAction(LOCATION_PERMISSION_REQUIRED);
sendBroadcast(permissionIntent);
}
Looper.loop();
}
};
handler.post(runnable);
//Create notification nad run in foreground
startForeground(
NotificationCreator.getNotificationId(),
NotificationCreator.getNotification(context)
);
return Service.START_STICKY;
}
@Override
public void onLocationChanged(Location location) {
Log.d("LocUpdate", location.getLatitude() + " : " + location.getLongitude());
}
我每次从活动启动该服务,如:
Intent intent = new Intent(this, MyLocService.class);
startService(intent);
我得到更新在onLocationChange()为20至30秒。另一种观察是:如果我保持活动(从我开始服务的地方开放并可见),然后我继续获取位置更新。 但是,当我关闭活动或终止应用并允许服务(单独)在后台运行时,虽然服务正在运行,但我无法获取位置更新,因为我可以在屏幕顶部看到通知。
我在做什么错?
你能看到运行在应用程序列表上的服务吗?您的手机是否允许该服务运行?某些电话ROM不允许按默认的START_STICKY重新启动服务,如果它被杀死 –
是的。我可以看到服务正在运行。我正在用棉花糖测试redmi note 4。什么是出路? – Priyabrata
我的红旗注意事项3有问题,因为如果它们被杀,MIUI不会默认让服务重启。试试这个,去设置>权限>自动启动>,并允许您的应用程序自动启动 –