问题描述
我正在尝试让一个应用在后台运行时提供位置更新。打开应用程序后,服务运行正常。当应用程序在后台运行时,服务将继续运行,但位置更新将停止。我曾尝试使用前台服务,但这无济于事。
我正在使用Google的fusedLocationProviderClient
public int onStartCommand(Intent intent,int flags,int startId) {
client.requestLocationUpdates(locationRequest,locationCallback,Looper.myLooper());
}
使用在onCreate()中定义的位置请求
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(500);
locationRequest.setFastestInterval(500);
并将回调定义为:
private final LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() != 0) {
Location location = locationList.get(0);
Log.e("AppLocationService","Latitude - " +location.getLatitude()+",longitude - " +location.getLongitude() );
}
}
我真的是android studio的新手,所以非常感谢您的帮助!
更新:
通过startService()启动服务
public class BackgroundService2 extends Service {
private FusedLocationProviderClient client;
private LocationRequest locationRequest;
@Override
public void onCreate() {
super.onCreate();
client = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(500);
locationRequest.setFastestInterval(500);
}
@Override
public int onStartCommand(Intent intent,int startId) {
super.onStartCommand(intent,flags,startId);
try {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission( getBaseContext(),android.Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( getBaseContext(),android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
client.requestLocationUpdates(locationRequest,Looper.myLooper());
}
} catch (SecurityException ignore) {
Log.e("AppLocationService","SecurityException - " + ignore.toString(),ignore);
}
return START_STICKY;
}
private final LocationCallback locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() != 0) {
Location location = locationList.get(0);
Log.e("AppLocationService",longitude - " +location.getLongitude() );
}
}
};
@Override
public IBinder onBind(Intent intent) {
// Todo: Return the communication channel to the service.
return null;
}
}
解决方法
原来是我的清单有问题。不仅必须声明服务,还必须声明其类型。
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
以及
<service
android:name=".BackgroundService"
android:enabled="true"
android:exported="true"
android:foregroundServiceType="location" />