onHandleWork 从未收到来自 pendingintent 地理围栏的意图

onHandleWork never receives intent from pending intent Geofencing

我正在开发 Geofencing 应用程序。处理 GeofenceTransitionsJobIntentService 子类永远不会收到意图。我每隔一分钟接收一次位置更新,然后创建一个新的地理围栏列表,然后根据用户的当前位置添加地理围栏。

这是我的 AndroidManifest.xml

 ........

 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.WAKE_LOCK" />

<service
            android:name=".GeofenceTransitionsService"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE">

        </service>

        <receiver
            android:name=".GeofenceBroadcastReceiver"
            android:enabled="true"
            android:exported="true" />
.............

我的GeofenceBroadcastReceiver.java

public class GeofenceBroadcastReceiver extends BroadcastReceiver {

    /**
     * Receives incoming intents.
     *
     * @param context the application context.
     * @param intent  sent by Location Services. This Intent is provided to Location
     *                Services (inside a PendingIntent) when addGeofences() is called.
     */
    @Override
    public void onReceive(Context context, Intent intent) {
        // Enqueues a JobIntentService passing the context and intent as parameters
        GeofenceTransitionsService.enqueueWork(context, intent);
    }
}

我的 GeofenceTransitionsService.java 处理触发的地理围栏

public class GeofenceTransitionsService extends JobIntentService {
   ..........

    /**
     * Convenience method for enqueuing work in to this service
     * Enqueue new work to be dispatched to onHandleWork
     */
    public static void enqueueWork(Context context, Intent intent) {
        Log.d(TAG, "Received intent: " + intent);
        enqueueWork(context, GeofenceTransitionsService.class, JOB_ID, intent);
    }

@Override
    protected void onHandleWork(Intent intent){
        // We have received work to do.  The system or framework is already
        // holding a wake lock for us at this point, so we can just go.
        Log.d(TAG, "Received intent: " + intent);
    }
}

这是我在 PointOfInterestMapFragment.java 中创建地理围栏请求、创建未决意图并添加地理围栏的部分代码

     /* Use the GeofencingRequest class and its nested GeofencingRequestBuilder
         * class to specify the geofences to monitor and to set how related geofence events are
         * triggered
         */
        private GeofencingRequest getGeofencingRequest(){
            GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
            //tell Location services that GEOFENCE_TRANSITION_DWELL should be triggered if the
            //device is already inside the geofence
            builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
            builder.addGeofences(mGeofenceList);
            return builder.build();
        }//end method getGeofencingRequest

        /*Pending intent that starts the IntentService*/
        private PendingIntent getGeofencePendingIntent(){
            Log.d(TAG, "getPendingIntent()");
            //Reuse the pending intent if we already have it
            if(mGeofencePendingIntent != null) {
                return mGeofencePendingIntent;
            }

            Intent intent = new Intent(getActivity(), GeofenceBroadcastReceiver.class);

            // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
            // calling addGeofences() and removeGeofences().
            mGeofencePendingIntent = PendingIntent.getBroadcast(getActivity()
                    , 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            return mGeofencePendingIntent;
        }//end method PendingIntent

        /*Add geofences*/
        @SuppressWarnings("MissingPermission")
        private void addGeofence(){
            if(checkPermissions()){
                mGeofencingClient.addGeofences(getGeofencingRequest(), getGeofencePendingIntent())
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {

                                Log.d(TAG, "Geofence added");
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.d(TAG, "Failed to add geofence: " + e.getMessage());
                            }
                        })
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                //drawGeofence();

                            }
                        });


            }else{
                requestPermissions();
            }
        }//end method addGeofence

这是 PointOfInterestMapFragment.java 中的代码部分,我在其中接收位置更新,填充 GeofenceList 然后添加地理围栏

/**
     * Creates a callback for receiving location events.
     */
    private void createLocationCallback() {
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);

                mCurrentLocation = locationResult.getLastLocation();
                mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());

                //populateGeofenceList to reflect the new current location bounds
                populateGeofenceList();
                addGeofence();

            }
        };
    }

当应用程序执行时,我从 getGeofencePendingIntent() 中的代码行 Log.d(TAG, "getPendingIntent()"); 中获取日志 cat 中的消息,但从未获取应该在 onHandleWork() 方法中显示的消息

我有一个类似的 'problem'。代码很好。就我而言,我认为代码无法正常工作,因为我没有正确理解地理围栏的工作原理。我想添加地理围栏,在你的情况下调用 addGeofence() 是触发器,所以我在等待在那个特定时间点看到通知。但是,对该方法的调用只会添加 监控 的地理围栏,然后仅当满足任何过滤器时才会将意图传递给服务(Geofence.GEOFENCE_TRANSITION_DWELLGeofence.GEOFENCE_TRANSITION_EXITGeofence.GEOFENCE_TRANSITION_ENTER) 添加地理围栏。您可以从文档中阅读更多内容 here

因此,您可能会在您的日志猫中收到 地理围栏已添加 消息,但这就是字面意思,地理围栏已添加但未触发。添加地理围栏后等待一段时间,如果添加的地理围栏满足任何过滤器,则发送意图。所以对我有用的解决方案是等待,一段时间后我收到了意图和通知。

如果等待不行,可以延长GEOFENCE_RADIUS,说到3000米看看有没有变化。此外,将到期持续时间设置为更高的值或 Geofence.NEVER_EXPIRE