Broadcast receiver for checking internet connection in android app

后端 未结 21 3187
温柔的废话
温柔的废话 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:45

    Answer to your first question: Your broadcast receiver is being called two times because

    You have added two

    1. Change in network connection :

    2. Change in WiFi state:

    Just use one:
    .

    It will respond to only one action instead of two. See here for more information.

    Answer to your second question (you want receiver to call only one time if internet connection available):

    Your code is perfect; you notify only when internet is available.

    UPDATE

    You can use this method to check your connectivity if you want just to check whether mobile is connected with the internet or not.

    public boolean isOnline(Context context) {
    
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        //should check null because in airplane mode it will be null
        return (netInfo != null && netInfo.isConnected());
    }
    

提交回复
热议问题