【问题标题】:Android: how to launch my app upon receiving a specific Broadcast?Android:如何在收到特定广播后启动我的应用程序?
【发布时间】:2012-06-21 19:55:44
【问题描述】:

我正在尝试在手机连接到 wifi 时自动启动我的应用程序。这是我用来设置广播接收器并指定接收到广播后我希望启动“已连接”活动的代码:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
receiver = new BroadcastReceiver(){
                public void onReceive(Context context, Intent intent){
                    Intent intent2 = new Intent(getApplicationContext(),com.example.package.Connected.class);
                    startActivity(intent2);
                }
            };
registerReceiver(receiver,intentFilter); 

不幸的是,它不起作用。 logcat 说我的活动“泄露了 IntentReceiver”。

有谁知道我该如何解决这个问题?

编辑:我也尝试通过 Manifest 文件注册接收器。我将此代码添加到清单中:

<receiver android:name="com.example.package.receiver">
    <intent-filter>
          <action android:name="android.net.wifi.STATE_CHANGE" />
    </intent-filter>
</receiver>

然后将这段代码添加到我的主要活动中:

private BroadcastReceiver receiver = new BroadcastReceiver(){
        public void onReceive(Context context, Intent intent){
            Intent intent2 = new Intent(getApplicationContext(),com.example.package.Connected.class);
            context.startActivity(intent2);
        }
    };

但是现在,一旦手机连接到 wifi,我的应用程序就会崩溃。 Logcat 说“RuntimeException:无法实例化接收器”。

有什么办法解决吗?

【问题讨论】:

  • 在第二种情况下,您需要创建一个单独的类扩展 BroadcastReceiver 并在 android:name="com.example.package.receiver" 中提供该类的包,包括类名
  • 谢谢,正在努力。
  • 这是一个显示清单注册接收器的示例应用程序:github.com/commonsguy/cw-omnibus/tree/master/SystemEvents/…
  • 应用程序仍然崩溃。现在 logcat 说“无法启动接收器”。
  • @CommonsWare,谢谢,我会检查一下。我现在也给你们发一封关于咨询工作的电子邮件:)。

标签: android


【解决方案1】:

我正在尝试在手机连接到 wifi 时自动启动我的应用程序。

使用&lt;receiver&gt; 元素在清单中注册您的BroadcastReceiver,并在onReceive() 方法中提供的Context 上让接收者调用startActivity()

请注意,用户可能不会因为设备连接到 WiFi 而对您弹出活动感到满意。

【讨论】:

  • 我试过这个,但现在崩溃了。如果您可以看一下,我在上面粘贴了我的代码。非常感谢。
【解决方案2】:

根据linkActivity has leaked IntentReceiver

取消注册您在 onCreate() 中创建的广播接收器

在 onRestart() 中重新注册一个全新的广播接收器。

【讨论】:

  • 但我希望即使在应用程序暂停或未运行时也能正常工作。我应该注销广播接收器吗?
猜你喜欢
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多