Search code examples
androidbroadcastreceiver

My app gets crashed, when internet connection is turned off


In my app I'm checking whether internet is connection is available or not. I'm using broadcast receiver for this. When I run my app,(when internet is connected) it works. But when I disconnect the internet, it get crashed. What is happening. Here is my code: My activity:

public class BroadcastActivity extends ActionBarActivity {
  private static Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast);
        Intent intent=new Intent(this, ConnectionReciever.class);
        sendBroadcast(intent);

    }


}

Receiver class:

public class ConnectionReciever extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo=connectivityManager.getActiveNetworkInfo();
        if(activeNetInfo!=null & activeNetInfo.isConnected())
        {
            Toast.makeText(context, "Internet Connection is Active", Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(context, "Internet Connection Timed Out! Please Try Again!!", Toast.LENGTH_LONG).show();
        }

    }

}

Also i added the permissions in the manifest and registered the receiver in the manifest.

Log cat:

    Failed to install Check_Network_Status.apk on device 'emulator-5554': adb rejected install command with: device offline
    [2014-05-15 12:09:48 - Check_Network_Status] com.android.ddmlib.AdbCommandRejectedException: device offline
    [2014-05-15 12:09:48 - Check_Network_Status] Launch canceled!

Solution

  • replace the following code in receiver class, u need to check for one more condition isAvailable() inside if.

    ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo=connectivityManager.getActiveNetworkInfo();
        if(activeNetInfo!=null && activeNetInfo.isAvailable() && activeNetInfo.isConnected())
        {
            Toast.makeText(context, "Internet Connection is Active", Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(context, "Internet Connection Timed Out! Please Try Again!!", Toast.LENGTH_LONG).show();
        }