我有一个MainActivity,它启动MainService以使用 GoogleApiClient 记录某些位置。
onLocationChanged 在服务中(但我在MainActivy中有另一个地图)。
活动运行时,会正常调用 onLocationChanged 。当Activity停止时,永远不会调用 onLocationChanged (但服务仍在运行)。
服务以 startForeground 启动, onStartCommand 返回 START_STICKY ;
为什么停止调用onLocationChanged?
编辑:代码
...
public class MainService extends Service implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
@Override
public void onCreate() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My App")
.setContentText("Working")
.setContentIntent(pendingIntent).build();
startForeground(42, notification);
initGoogleApi();
super.onCreate();
}
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
LocalBroadcastManager.getInstance(this).registerReceiver((broadcastReceiver),
new IntentFilter(Config.SERVICE_RESULT));
return START_STICKY;
}
private void initGoogleApi(){
if (mGoogleApiClient == null) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mLocationRequest.setSmallestDisplacement(50F);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
}
@Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
@Override
public void onLocationChanged(Location location) {
doStuff(location);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
protected void startLocationUpdates() {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//TODO
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} catch (IllegalStateException e) {
Log.e("Service", "SERVICE IllegalStateException in startLocationUpdates");
}
}