android - 带有 PendingIntent 的 RequestLocationUpdates 永远不会触发

标签 android android-pendingintent android-intentservice fusedlocationproviderapi

我尝试在后台经常运行位置检查,因此我尝试使用 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);
        ...
    }
    ...
}

我错过了什么吗?

最佳答案

您提供给 requestLocationUpdates()PendingIntent 将触发广播 Intent,因为您已调用 PendingIntent.getBroadcast( )。但是,您在 PendingIntent 中提供的类是一个 Service。将 getBroadcast() 替换为 getService()`。

关于android - 带有 PendingIntent 的 RequestLocationUpdates 永远不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28267209/

相关文章:

android - 具有未决 Intent 的通知操作不适用于 JellyBean+

kotlin - 从 RecyclerView 适配器内部访问 AlarmManager

java - Android中执行后台定时重复任务,以及IntentService和Runnable的区别

android - 停止 Activity 中的服务

android - EditText 只允许所有语言的字母、数字

java - 滚动 AlphabetIndexer 时快速滚动拇指消失

Android 不重用主 Activity 并启动多个实例(仅在使用 PendingIntent 后行为)

java - Android 如何播放 Assets 文件夹中的媒体文件 (.mp4)

android - 我可以在 Android Box 中安装自定义 APK 吗?

android设计注意事项: AsyncTask vs Service (IntentService?)