Android 如何从多任务窗格/强制关闭应用程序时删除install/unistall接收器?
我已经在react native中编写了一个插件,用于在安装新应用程序或现有应用程序的unistalling(卸载应用程序的包名)时将事件发送到Javascript(已安装应用程序的包名) 我面临的问题是,当i kill应用程序(从多任务窗格中删除)时,接收器将继续侦听安装/卸载事件。不幸的是,该应用程序已关闭 请查找我编写的代码,如下所示:Android 如何从多任务窗格/强制关闭应用程序时删除install/unistall接收器?,android,events,broadcastreceiver,react-native,Android,Events,Broadcastreceiver,React Native,我已经在react native中编写了一个插件,用于在安装新应用程序或现有应用程序的unistalling(卸载应用程序的包名)时将事件发送到Javascript(已安装应用程序的包名) 我面临的问题是,当i kill应用程序(从多任务窗格中删除)时,接收器将继续侦听安装/卸载事件。不幸的是,该应用程序已关闭 请查找我编写的代码,如下所示: public class MyReceiver extends BroadcastReceiver { Context context;
public class MyReceiver extends BroadcastReceiver {
Context context;
private static AppListModule module;
public MyReceiver(AppListModule module) {
this.module = module;
}
public MyReceiver() {}
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
// This condition will be called when package removed
if (intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")) {
String packageName = intent.getDataString();
Log.e(" BroadcastReceiver ", "onReceive called "
+ " PACKAGE_REMOVED ");
WritableMap params = Arguments.createMap();
params.putString("message", packageName);
this.module.sendEvent(this.module.getReactApplicationContextModule(), "InstallUninstall", params);
}
// This condition will be called when package installed
else if (intent.getAction().equals("android.intent.action.PACKAGE_ADDED")) {
String packageName = intent.getDataString();
Log.e(" BroadcastReceiver ", "onReceive called " + "PACKAGE_ADDED");
WritableMap params = Arguments.createMap();
params.putString("message", packageName);
if(this.module!=null) {
this.module.sendEvent(this.module.getReactApplicationContextModule(), "InstallUninstall", params);
}
}
}
我唯一的问题是,当我关闭应用程序时,如何移除接收器。请在这方面提供帮助
设置MyReceiver.java
public void setData(ReactApplicationContext mcontext, AppListModule module) {
context = mcontext;
this.module = module;
this.eventsReceiver = new MyReceiver(this.module);
}
您需要在某处保留对MyReceiver的引用,以便使用该引用注销它。我假设您正在
活动中创建并注册MyReceiver
。如果是这样,您应该能够在onDestroy()
中注销它:
您需要确保调用unregisterReceiver()
的上下文与调用registerReceiver()
的上下文相同
此外,作为安全网,您应该检查this.module!=MyReceiver.onReceive()中的null
。如果它是null
,只需忽略对onReceive()
的调用,而不执行任何操作。这将防止应用程序崩溃。如何创建MyReceiver
?显示代码并指出完成此操作的位置/时间。@DavidWasser我已添加感谢。我会检查一下,然后告诉你
context.unregisterReceiver(myReceiver);