【问题标题】:onHandleIntent not firing with location updatesonHandleIntent 不会随着位置更新而触发
【发布时间】: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();
        }
    }
}

【问题讨论】:

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


【解决方案1】:

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

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

其次,你的构造函数不应该被使用。将其替换为零参数构造函数。

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

说您希望IntentService 通过onHandleIntent() 方法处理位置是合理的。但是,需要在该服务之外进行连接和断开连接,或者您将需要更复杂的服务。

【讨论】:

  • 谢谢,我明白我的错误了。我必须做的是将我的 Service 方法与管理数据收集的此类分开。我为我的 IntentService 创建了一个不同的类,现在我正在获取位置更新。再次感谢!
猜你喜欢
  • 2018-07-29
  • 2013-12-17
  • 1970-01-01
  • 1970-01-01
  • 2020-01-13
  • 2020-09-10
  • 1970-01-01
  • 2021-08-01
  • 2016-10-27
相关资源
最近更新 更多