I am trying to get the internet connectivity state using BroadcastReceiver in my app. If there is no internet available, I want to show an AlertDialog box.
Here is my BroadcastReceiver:
public class ConnectivityChangedReceiver extends BroadcastReceiver{
@Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
} else {
showInternetAlertDialog(context);
}
}
public void showInternetAlertDialog(Context context){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("You have no internet connection.")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
}
});
builder.show();
return;
}
}
I have defined this receiver in my manifest too . I have defined the permission for accessing network state in manifest.
<receiver android:name="com.lisnx.service.ConnectivityChangedReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
But when internet is gone and AlertDialog box tries to open, I get the following exception :
10-19 16:25:21.474 E/AndroidRuntime( 6864): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.view.ViewRoot.setView(ViewRoot.java:509)
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-19 16:25:21.474 E/AndroidRuntime( 6864): at android.app.Dialog.show(Dialog.java:241)
I think its an issue of Context but I can’t find out what exactly is the problem. Please help me on this. Any solutions will be appreciated. Thanx in advance.
That is not possible to display
AlertDialogfromBroadCast Receiver.You have to start some activity from BroadCast Receiver and in that activity you have to display AlertDialog.
You can set Dialog theme to activity or you can provide transparent layout to that activity.
Edit :
Make sure that you start new activity with
FLAG_ACTIVITY_NEW_TASKintent flag.