I am trying to get my app automatically launched when the phone gets connected to wifi. Here’s the code I am using to both set the Broadcast receiver and to specify that once the broadcast is received I want the “Connected” activity to be launched:
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);
Unfortunately it’s not working. The logcat says my activity has “leaked IntentReceiver”.
Does anyone know how I can solve this?
EDIT: I also tried to register the receiver via the Manifest file. I added this code to the manifest:
<receiver android:name="com.example.package.receiver">
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
And then this code to my main activity:
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);
}
};
But now my app crashes once the phone connects to wifi. Logcat says “RuntimeException: Unable to instantiate receiver”.
Any ideas how to solve it?
Register your
BroadcastReceiverin the manifest, using a<receiver>element, and have the receiver callstartActivity()on theContextsupplied in theonReceive()method.Note that users may not appreciate your popping up an activity just because the device connected to WiFi.