已启动服务在应用程序终止后停止侦听位置更新#android
MyServ.java:已启动服务在应用程序终止后停止侦听位置更新#android,android,Android,MyServ.java: In Main Activity: public void startService(View view) { Intent intent = new Intent(MainActivity.this, MyServ.class); startService(intent); } 应用程序终止后不会显示日志或土司(从最近列表中清除或按“上一步”按钮清除)。为什么启动的服务在其活动关闭后不工作?是否有其他方法来完成此任务?这可能会帮助您感谢Jas的回复,
In Main Activity:
public void startService(View view) {
Intent intent = new Intent(MainActivity.this, MyServ.class);
startService(intent);
}
应用程序终止后不会显示日志或土司(从最近列表中清除或按“上一步”按钮清除)。为什么启动的服务在其活动关闭后不工作?是否有其他方法来完成此任务?这可能会帮助您感谢Jas的回复,但我不想运行前台服务。还有其他方法吗?当GoogleAppClient连接时:onConnected(Bundle Bundle){..您的代码似乎是正确的。您应该等待几秒钟才能重新启动服务!检查此
Log.d(“vats”,“在用:onCreate()”);
在您的日志中。应用程序终止后,它不会打印任何内容,但当应用程序未关闭时,它会正常工作,并在几秒钟后发送更新
public class MyServ extends Service implements LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private long INTERVAL = 500, FASTEST_INTERVAL = 100;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d("vats", "In Service : onCreate()");
}
private void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
listenToLocation();
}
}).start();
return START_STICKY;
}
private void listenToLocation() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.d("vats", "In Service :connected...");
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("vats", "Connection failed: " + connectionResult.toString());
}
})
.build();
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
Log.d("vats", "location updates: " + location.toString());
Toast.makeText(MyServ.this, "location changes", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("vats","onDestroy()");
if (mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()) {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
}