Broadcast receiver for checking internet connection in android app

后端 未结 21 3212
温柔的废话
温柔的废话 2020-11-21 22:28

I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get

相关标签:
21条回答
  • 2020-11-21 22:51

    Use this method to check the network state:

    private void checkInternetConnection() {
    
        if (br == null) {
    
            br = new BroadcastReceiver() {
    
                @Override
                public void onReceive(Context context, Intent intent) {
    
                    Bundle extras = intent.getExtras();
    
                    NetworkInfo info = (NetworkInfo) extras
                            .getParcelable("networkInfo");
    
                    State state = info.getState();
                    Log.d("TEST Internet", info.toString() + " "
                            + state.toString());
    
                    if (state == State.CONNECTED) {
                          Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();
    
                    } else {
                           Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
                    }
    
                }
            };
    
            final IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver((BroadcastReceiver) br, intentFilter);
        }
    }
    

    remember to unregister service in onDestroy.

    Cheers!!

    0 讨论(0)
  • 2020-11-21 22:54

    Broadcast receiver code to check internet connectivity change:

    public class BroadCastDetecter extends BroadcastReceiver {
        public static boolean internet_status = false;
        public static void checkInternetConenction(Context context) {
            internet_status = false;
            ConnectivityManager check = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (check != null) {
                NetworkInfo[] info = check.getAllNetworkInfo();
                if (info != null)
                    for (int i = 0; i < info.length; i++)
                    {
                        if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                            internet_status = true;
                        }
                    }
                if(internet_status)
                {
                   //do what you want to if internet connection is available
                }
            }
        }
    
        @Override
        public void onReceive(Context context, Intent intent)
        {
            try {
                checkInternetConenction(context);
            }catch(Exception e){
    
            }
        }
    }
    

    add this in manifest file:

     <receiver android:name=".BroadCastDetecter">
                <intent-filter>
                    <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                </intent-filter>
            </receiver>
    
    0 讨论(0)
  • 2020-11-21 22:57
    public class AsyncCheckInternet extends AsyncTask<String, Void, Boolean> {
    
    public static final int TIME_OUT = 10 * 1000;
    
    private OnCallBack listener;
    
    public interface OnCallBack {
    
        public void onBack(Boolean value);
    }
    
    public AsyncCheckInternet(OnCallBack listener) {
        this.listener = listener;
    }
    
    @Override
    protected void onPreExecute() {
    }
    
    @Override
    protected Boolean doInBackground(String... params) {
    
        ConnectivityManager connectivityManager = (ConnectivityManager) General.context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
    
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    
        if ((networkInfo != null && networkInfo.isConnected())
                && ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI) || (networkInfo
                        .getType() == ConnectivityManager.TYPE_MOBILE))) {
            HttpURLConnection urlc;
            try {
                urlc = (HttpURLConnection) (new URL("http://www.google.com")
                        .openConnection());
                urlc.setConnectTimeout(TIME_OUT);
                urlc.connect();
                if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    return true;
                } else {
                    return false;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return false;
    
            } catch (IOException e) {
                e.printStackTrace();
                return false;
    
            }
        } else {
            return false;
        }
    }
    
    @Override
    protected void onPostExecute(Boolean result) {
        if (listener != null) {
            listener.onBack(result);
        }
    }
    

    }

    0 讨论(0)
提交回复
热议问题