我在决定实现后台自定义服务类的方式时有点困惑。
我需要什么:
我是Android的后台处理新手,我不知道如何实现它。
是否可以创建ThreadPoolExecutor(任务管理器类,runnables等)并处理线程间通信?
如果是,是否可以在Thread类中收听位置更新?
目前,我正在使用此库(Smart-location-lib)来收听位置更新。
有更好的解决方案吗?
非常感谢任何帮助!
答案 0 :(得分:0)
这是在后台服务中使用Google API的最佳方式 你没有解释活动识别是什么意思?
public class MyLocationService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public MyLocationService() {
}
@Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this)
.build();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
Toast.makeText(this, "Location services started", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onLocationChanged(Location location) {
System.out.println("MyLocationService.onLocationChanged");
// TODO with location updateshere
}
@Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
sendMyLocUpdate(loc, UserProfile.DRIVER);
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onDestroy() {
Toast.makeText(this, "Location services stopped", Toast.LENGTH_LONG).show();
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
sendMyLocUpdate(loc, UserProfile.PASSENGER);
mGoogleApiClient.disconnect();
super.onDestroy();
}
}