场景:我从A设备向B设备推送数据,B设备收到推送后调用NativeModules方法 "invokeApp({ data: "someValue" })"。
在我的原生模块中,我写了以下代码。
private static ReactApplicationContext reactContext;
public static final String LOG_TAG = "RNInvokeApp";
private static Bundle bundle = null;
public RNInvokeApp(ReactApplicationContext context) {
super(context);
reactContext = context;
}
@Override
public String getName() {
return "RNInvokeApp";
}
@ReactMethod
public void invokeApp(ReadableMap params) {
String packageName = reactContext.getPackageName();
Intent launchIntent = reactContext.getPackageManager().getLaunchIntentForPackage(packageName);
String className = launchIntent.getComponent().getClassName();
try {
Class<?> activityClass = Class.forName(className);
Intent activityIntent = new Intent(reactContext, activityClass);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent
.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
reactContext.startActivity(activityIntent);
} catch(Exception e) {
Log.e(LOG_TAG, "Class not found", e);
return;
}
WritableMap paramsData = Arguments.createMap();
paramsData.putString("eventProperty", "someValue");
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("appInvoked", paramsData);
}
}
如果设备B处于后台或前台,这就完美地工作了。但是当设备B处于被杀死的状态时,我在设备B中没有任何发射。
const eventEmitter = new NativeEventEmitter(NativeModules.RNInvokeApp);
eventEmitter.addListener('appInvoked', (event) => {
console.log(event.eventProperty);
});