出于某种原因,当通过 IntentService
发出事件时,Javascript 端没有任何反应。这是我正在做的:
使用
onHandleIntent
方法创建一个IntentService
,如下所示:@Override protected void onHandleIntent(@Nullable final Intent intent) { if (intent != null) { logger.info("Broadcasting event"); intent.setAction(ACTION); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } }
将
IntentService
注册到com.google.android.gms.location.GeofencingClient
:Intent intent = new Intent(getReactApplicationContext().getBaseContext(), BoundaryEventIntentService.class); this.mBoundaryPendingIntent = PendingIntent.getService(getReactApplicationContext().getBaseContext(), 0, intent, PendingIntent. FLAG_UPDATE_CURRENT);
为
IntentService
创建BroadcastReceiver
以将消息广播到:public class GeofenceEventBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); if (geofencingEvent.hasError()) { // handle errors } switch (geofencingEvent.getGeofenceTransition()) { case Geofence.GEOFENCE_TRANSITION_ENTER: Log.i(TAG, "Enter geofence event detected. Sending event."); WritableArray writableArray = Arguments.createArray(); for (Geofence geofence : geofencingEvent.getTriggeringGeofences()) { writableArray.pushString(geofence.getRequestId()); } sendEvent(ON_ENTER, writableArray); break; // handle other events e.g. GEOFENCE_TRANSITION_EXIT } } }
最后是我的
sendEvent
方法:private void sendEvent(String event, Object params) { Log.i(TAG, "Sending events " + event); getReactApplicationContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(event, params); Log.i(TAG, "Sent events"); }
我的 BroadcastReceiver
是我的 ReactContextBaseJavaModule
上的一个内部类,因此它可以访问我的 React 应用程序上下文和 sendEvent
方法。一切都成功触发,除了 javascript 端没有收到事件。我意识到这是相当多的代码,我可能没有包含所有需要的上下文。图书馆可以找到here如果需要更多上下文。
最佳答案
一个可能的原因是您正在使用 intent 服务,它会受到 doze 模式的影响。更新以使用 Job Intent Service 而不是 Intent 服务。
https://developer.android.com/reference/android/support/v4/app/JobIntentService
Android 后台位置限制 为了保护电池、用户体验和系统健康,在运行 Android 8.0 的设备上使用时,后台应用程序接收位置更新的频率较低。此行为更改会影响所有接收位置更新的应用,包括 Google Play 服务。
这些更改会影响以下 API:
融合位置提供商 (FLP) 地理围栏 全局导航卫星系统测量 位置经理 Wi-Fi 管理器
阅读此链接以了解在 8.0 中所做的更改
https://developer.android.com/about/versions/oreo/android-8.0-changes
注意: IntentService 是一种服务,因此受到后台服务的新限制。因此,许多依赖 IntentService 的应用在面向 Android 8.0 或更高版本时无法正常运行。为此,Android 支持库 26.0.0 引入了一个新的 JobIntentService 类,它提供与 IntentService 相同的功能,但在 Android 8.0 或更高版本上运行时使用作业而不是服务。
关于android - 从 IntentService 调用时,React native 事件无法发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51979251/