onHandleIntent不会触发位置更新

时间:2015-06-07 20:19:16

标签: java android google-play-services android-location

我正在尝试使用Play服务位置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();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

  

你能告诉我有什么我做错了吗?

首先,ServiceContext。你不需要 - 甚至想要 - 将一些Context传递给它。

其次,永远不要使用你的构造函数。将其替换为零参数构造函数。

第三,start()stop()不是IntentService上的生命周期方法,因此我不太确定您所期望的是什么。再加上之前的问题,这意味着这项服务不会发生任何事情。

假设您希望IntentService通过onHandleIntent()方法处理这些位置,这是合理的。但是,该服务之外的东西需要进行连接和断开连接,否则您将需要更复杂的服务。

相关问题