1

我试图让我的应用程序在手机连接到 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”。

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

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

<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:无法实例化接收器”。

任何想法如何解决它?

4

2 回答 2

2

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

BroadcastReceiver使用元素在清单中注册您的<receiver>,并让接收者调用方法startActivity()Context提供的onReceive()方法。

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

于 2012-06-21T20:05:20.957 回答
1

根据链接活动已泄漏 IntentReceiver

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

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

于 2012-06-21T19:59:14.133 回答