2

我试图在后台每隔一段时间进行一次位置检查,所以我试图使用 IntentService 从 FusedLocationApi 获取位置更新。但是 PendingIntent 永远不会触发。

代码:

public class LocationIntentService extends IntentService
   implements
       GoogleApiClient.ConnectionCallbacks,
       GoogleApiClient.OnConnectionFailedListener
{
    private static GoogleApiClient mApiClient;
    ...
    @Override
    public void onCreate() {
        if (mApiClient == null) {
            mApiClient = new GoogleApiClient.Builder(getApplicationContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
            mApiClient.connect();
        }
    }
    ...
    @Override
    public void onConnected(Bundle bundle) {
        LocationRequest locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        locationRequest.setInterval(Constants.LOCATION_UPDATE_INTERVAL_MILIS);
        locationRequest.setFastestInterval(Constants.LOCATION_UPDATE_INTERVAL_MILIS / 2);

        Intent locationIntent = new Intent(getApplicationContext(), LocationIntentService.class);
        PendingIntent locationPendingIntent = PendingIntent.getBroadcast(
            getApplicationContext(),
            0,
            locationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT
        );

        LocationServices.FusedLocationApi
            .requestLocationUpdates(mApiClient, locationRequest,locationPendingIntent);
        ...
    }
    ...
}

我错过了什么吗?

4

1 回答 1

4

PendingIntent您提供的将requestLocationUpdates()触发广播Intent,因为您已调用PendingIntent.getBroadcast(). 但是,您在 中提供的课程PendingIntentService. 替换getBroadcast() withgetService()`。

于 2015-02-01T21:40:09.050 回答