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

Posted

技术标签:

【中文标题】onHandleWork 从未收到来自 pendingintent 地理围栏的意图【英文标题】:onHandleWork never receives intent from pending intent Geofencing 【发布时间】:2018-06-16 00:13:22 【问题描述】:

我正在开发一个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() 方法中显示的消息

【问题讨论】:

我认为你缺少 startService(intent); @AssemMahrous 那是错误的。通过调用PendingIntent.getService()PendingIntent.getBroadCast(),您可以检索一个 PendingIntent 以分别启动服务或广播。对startService() 的调用会导致服务启动。启动的服务无限期运行,为了同时处理多个请求,建议使用IntentService。处理完所有请求后,服务会自行停止。 【参考方案1】:

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

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

如果等待不起作用,你可能想延长GEOFENCE_RADIUS,说到3000米检查看看是否有任何变化。此外,将过期持续时间设置为更高的值或Geofence.NEVER_EXPIRE

【讨论】:

以上是关于onHandleWork 从未收到来自 pendingintent 地理围栏的意图的主要内容,如果未能解决你的问题,请参考以下文章

在 JobIntentService 中可以在没有 onHandleWork() 的情况下调用 onDestroy() 吗?

JobIntentService - onHandleWork 并不总是被调用?

JobIntentService onHandleWork 无法正常工作

来自 JobIntentService 的吐司

连接 throw stropes.js 时未收到来自 Openfire Xmpp 的通信

从未收到 Instagram 沙盒用户邀请