19

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

public class ConnectionChangeReceiver extends BroadcastReceiver
{
  @Override
  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?

MHSFisher
  • 733
  • 1
  • 12
  • 34
Beginner
  • 1,384
  • 2
  • 20
  • 39

3 Answers3

64

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

Link: https://developer.android.com/preview/features/background-optimization.html#connectivity-action

Use: WorkManager or JobScheduler for same.


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" >
    <intent-filter>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>

and

public class UpdateReceiver extends BroadcastReceiver {

    @Override
    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", "Connected" + isConnected);   
          else 
              Log.i("NET", "Not Connected" + isConnected);
    }
}

Dhaval Parmar
  • 18,175
  • 7
  • 77
  • 170
  • i have added the below statements in my manifest file. But still getting that problem – Beginner Mar 21 '13 at 11:59
  • it's same problem.. i have added reciever in manifest file before only – Beginner Mar 21 '13 at 12:12
  • now in logcat i got the following error '03-21 12:13:01.340: E/chromium(801): external/chromium/net/disk_cache/entry_impl.cc:904: [0321/121301:ERROR:entry_impl.cc(904)] Failed to save user data 03-21 12:13:01.340: E/chromium(801): external/chromium/net/disk_cache/entry_impl.cc:904: [0321/121301:ERROR:entry_impl.cc(904)] Failed to save user data ' – Beginner Mar 21 '13 at 12:14
  • its working fine at my END. i have checked your code. check log : 03-21 18:03:42.795: I/NET(1607): connectetrue 03-21 18:04:08.415: I/NET(1607): not connectefalse 03-21 18:04:17.295: I/NET(1607): connectetrue – Dhaval Parmar Mar 21 '13 at 12:35
  • thanks it's working now. but once if disconnect and connect i am not getting any logs in logcat and each time i need to close the old AVD and need to open new AVD. why is this problem?. – Beginner Mar 21 '13 at 12:52
  • i have used the above code. but the toast message is getting displayed in other apps also. how can i avoid it. thanks:) – Beginner Apr 17 '13 at 09:16
  • thanks:). but if i remove toast will i be notified about the status of network in my entire application? – Beginner Apr 17 '13 at 10:12
  • i have made something similar.. like `public class MyApplication extends Application { private static Context context; public void onCreate(){ super.onCreate(); MyApplication.context = getApplicationContext(); } public static Context getAppContext() { return MyApplication.context; } }` and displaying toast as `Toast.makeText(MyApplication.getAppContext(), "net Connected", Toast.LENGTH_LONG) .show();` but still i am facing that problem. – Beginner Apr 17 '13 at 10:25
  • yu have to make one static class in your app. in that class create one variable.. like appisrunning = false; now, in your all activity oncreate do myclassname.appisrunning = true; and in onDestroy myclassname.appisrunning = false; and in broadcast if(myclassname.appisrunning){ show toast }. – Dhaval Parmar Apr 17 '13 at 10:28
  • 'public boolean isOnline(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { return true; } return false; }' – AZ_ Mar 10 '14 at 16:15
6

The above code was not properly working for wi-fi connection. This is the Modified

SIMPLE ONE

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

inside application tag of androidmanifest.xml

<receiver android:name="android.YOUR-JAVA-CLASS-PATH.BackgroundSync" android:enabled="true">
      <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
      </intent-filter>
</receiver>

BackgroundSync.java

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager; 
import android.util.Log;
import android.widget.Toast;

public class BackgroundSync extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) { 
        ConnectivityManager cm =(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm.getActiveNetworkInfo()!=null){
            Toast.makeText(context, "Connected to Internet", Toast.LENGTH_LONG).show();
        }
        else Log.i("INTERNET","---------------------> Internet Disconnected. ");
    }
}
shreedhar bhat
  • 4,223
  • 1
  • 14
  • 23
1

Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest. Apps will still receive broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

https://developer.android.google.cn/reference/android/net/ConnectivityManager.html?hl=zh-cn#CONNECTIVITY_ACTION

BJDM
  • 101
  • 2
  • 4
  • 1
    Please don't post the same answer to more than one question. If the questions are basically the same, [flag them](https://stackoverflow.com/privileges/flag-posts) as duplicates. Otherwise, customize the answer to the question. (Also, posts that are nothing but a quote are often less than helpful. Also also, all quotes must be formatted so it's clear what you're quoting; otherwise you're plagiarizing by misrepresenting what you wrote.) – Nathan Tuggy Jul 05 '17 at 04:34