【问题标题】:How to remove the install/unistall receiver on killing the applicationfrom multitask pane/force closing the app?如何在从多任务窗格中删除应用程序时删除安装/卸载接收器/强制关闭应用程序?
【发布时间】:2015-12-25 16:44:46
【问题描述】:

我在 react-native 中编写了一个插件,用于在安装新应用程序或卸载现有应用程序(已卸载应用程序的包名)时将事件发送到 Javascript(已安装应用程序的包名称)。

我面临的问题是,当我杀死应用程序(从多任务窗格中删除)时,接收器将继续监听安装/卸载事件。这表示不幸的是应用程序已关闭。

请找到我写的代码如下:

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?显示代码并指明何时/何时完成。
  • @DavidWasser 我已添加

标签: android events broadcastreceiver react-native


【解决方案1】:

您需要在某处保留对MyReceiver 的引用,以便您可以使用它来取消注册。我假设您在Activity 中创建和注册MyReceiver。如果是这样,您应该可以在onDestroy() 中取消注册:

context.unregisterReceiver(myReceiver);

您需要确保调用 unregisterReceiver() 时使用的 Context 与您之前调用 registerReceiver() 的相同。


另外,作为安全网,您应该检查this.module != null 中的MyReceiver.onReceive()。如果是null,则忽略对onReceive() 的调用,什么也不做。这将防止您的应用崩溃。

【讨论】:

  • 谢谢。我会检查并告诉你
猜你喜欢
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 2017-04-21
  • 1970-01-01
相关资源
最近更新 更多