In Main Activity:
public void startService(View view) {
Intent intent = new Intent(MainActivity.this, MyServ.class);
startService(intent);
}
MyServ.java:
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();
}
}
}
应用程序终止后不显示日志或Toast(从最近列表或后退按钮清除)。为什么在活动结束后开始服务不工作?还有其他方法可以完成这项任务吗?