【发布时间】:2015-06-07 20:19:16
【问题描述】:
我正在尝试使用 Play Services Location API 来监听位置变化。
我想要做的是使用后台应用程序方法并使用PendingIntent 获取更新。然而,onHandleIntent() 函数根本没有被调用。
我没有找到关于这种方法的综合文档的单一来源。你能告诉我我做错了什么吗?
public class LocationCollector extends IntentService implements GoogleApiClient.ConnectionCallbacks
, GoogleApiClient.OnConnectionFailedListener {
private Context mContext;
private GoogleApiClient mLocationClient;
public LocationCollector(Context context){
super("LocationCollector");
mContext = context;
mLocationClient = new GoogleApiClient.Builder(mContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
public void start(){
mLocationClient.connect();
}
public void stop(){
mLocationClient.disconnect();
}
@Override
public void onConnected(Bundle bundle) {
LocationRequest request = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Intent locationIntent = new Intent(mContext, LocationCollector.class);
PendingIntent locationPendingIntent = PendingIntent.getService(mContext, 1, locationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingResult<Status> result = LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, request, locationPendingIntent);
}
@Override
public void onConnectionSuspended(int i) {
Log.d("Location","Api connection suspended");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("Location","Api connection failed");
}
@Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
if(location != null){
String time= intent.getStringExtra("time");
Toast.makeText(mContext,location.toString(),Toast.LENGTH_SHORT).show();
}
}
}
【问题讨论】:
-
@CommonsWare 的答案很准确(一如既往)。此外,这个问题的答案中的代码可能对您有所帮助:stackoverflow.com/questions/30141631/…
标签: java android google-play-services android-location