1
I'm trying to implement a scenario, if my application loses internet connectivity I'm posting a alert dialog to the user.

I'm planning to use Broadcast receiver to check internet connectivity in my app by using register and unregister in my main activity.

Here is the code:

**BroadcastReceiver** class : here I'm checking the internet connectivity.

I'm checking wifi or data connectivity service and if not available I'm alerting the user.

public class NetworkChangeReceiver extends BroadcastReceiver {

    private static final String TAG = "ConnectionReceiver";

    private AlertDialog alertDialog;

    public NetworkChangeReceiver() {
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
            ConnectivityManager cm =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();
            if (isConnected) {
                try {
                    if (alertDialog != null && alertDialog.isShowing())
                        alertDialog.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                if (alertDialog == null || !alertDialog.isShowing()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("No internet connection");
                    builder.setMessage("check your connection.");
                    builder.setPositiveButton(context.getString(R.string.confirm_button_text), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                    alertDialog = builder.create();
                    alertDialog.show();
                }
            }
        }
    }
}



**And in my Activity I'm registering the broadcast receiver.** :

public class MyActivity extends Activity {

    private NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();

@Override
    protected void onResume() {
        super.onResume();
        registerReceiver(networkChangeReceiver, new IntentFilter(
                "android.net.conn.CONNECTIVITY_CHANGE"));
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(networkChangeReceiver);
    }

}


When I put my phone in airplane mode , alert dialog pops up and after 2 seconds my app gives an "Unable to add window -- token null is not for an application " exception. and this exception occurs 2 times.

**here is my log**:

AndroidRuntime: FATAL EXCEPTION: main Process: , PID: 9923 java.lang.RuntimeException: Unable to start receiver xxxx.NetworkChangeReceiver: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application


My **Manifest** file:

<application
        android:name="xxxxx"
        android:allowBackup="true"
        tools:replace = "android:icon"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <receiver android:name=".xxx.NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>


<activity
            android:name="xxxx"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

Can someone help me out how to resolve the exception, and why is the exception occurring twice?

Nikhil
  • 3,711
  • 8
  • 32
  • 43
DroidDev
  • 789
  • 9
  • 19
  • Possible duplicate of [How to raise an alert dialog from BroadcastReceiver class?](http://stackoverflow.com/questions/7229951/how-to-raise-an-alert-dialog-from-broadcastreceiver-class) – Mike M. Sep 30 '16 at 18:36
  • 1
    It's happening twice because you're registering the Receiver in two places; the manifest, and the `Activity`. – Mike M. Sep 30 '16 at 18:37
  • Within my activity i have 20 other fragments. I want to show alert dialog every time the user moves to other fragment. But its only displaying when onResume is called i.e once. After i dismiss my alert dialog if i move to other fragment i want to pop up alert again . Any idea how to do it ? Do i need to register in all fragments? – DroidDev Sep 30 '16 at 19:34
  • I don't understand what you're asking. You're registering the Receiver for the `CONNECTIVITY_CHANGE` broadcast. Why should it fire just because the user navigates to another `Fragment`? – Mike M. Sep 30 '16 at 19:38
  • I mean i have bottom tabs on my app, when my app launches and there is no internet connectivity i pop up an alert and after user dismiss it by pressing "OK" and navigates to other tab i.e. a new fragment I want to alert user again that there is no connectivity. In short whenever he navigates to other fragment i want to alter the user about internet connectivity . – DroidDev Sep 30 '16 at 19:46
  • I wouldn't be using the Receiver registration for that. You can just do a direct check whenever they navigate, and show the `Dialog` if needed. That is, just do what you're doing to figure the `boolean isConnected` in your Receiver. – Mike M. Sep 30 '16 at 19:51
  • So you mean Check whenever they navigate i.e check the same code in all 20 fragments i have? – DroidDev Sep 30 '16 at 22:22
  • I'd just make one method in the `Activity` that does the check whenever the tab changes. – Mike M. Sep 30 '16 at 22:35

1 Answers1

0

Just removing my receiver from manifest.xml solved my issue. Thanks.

DroidDev
  • 789
  • 9
  • 19