Beginner Beginner - 1 year ago 89
Android Question

unfortunately app is getting stopped while checking for network

I am using the following code to check for the internet connection throughout my app.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class ConnectionChangeReceiver extends BroadcastReceiver
public void onReceive( Context context, Intent intent )
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo
(ConnectivityManager.TYPE_MOBILE );
if ( activeNetInfo != null )
Toast.makeText( context, "Active Network Type : " +
activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
if( mobNetInfo != null )
Toast.makeText( context, "Mobile Network Type : " +
mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();

And I have defined required permission in the manifest file

Whenever I try to disconnect/connect the network using F8 key I will receive "UNFORTUNATELY APP HAS STOPPED", and I am not getting any print in logcat.
Can I know what is the mistake I am doing?

Answer Source

Have you added this in androidmanifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

if you have added above then check this code:

<receiver android:name=".UpdateReceiver" >
            <action android:name="" />


public class UpdateReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {

          ConnectivityManager connectivityManager = (ConnectivityManager) 
                                       context.getSystemService(Context.CONNECTIVITY_SERVICE );
          NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
          boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();   
          if (isConnected)       
              Log.i("NET", "connecte" +isConnected);   
          else Log.i("NET", "not connecte" +isConnected);

NOTE: If you're targeting android N Preview. Above receiver will not work as per constrained restricted by Google. Link:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download