Search code examples
androidbroadcastreceiverandroid-broadcast

How to use data from the broadcast receiver, before the activity is shown, in android


I'm using receiver in order to know if the phone got internet connection.

I'm using this code:

public class SearchFragment extends Fragment {

    private Boolean netOk = false;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        ConnectionChangeReceiver1 netReceiver =  new ConnectionChangeReceiver1();
        IntentFilter filterNet = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
        getActivity().registerReceiver(netReceiver, filterNet);
    }

    @Override
    public void onResume() {
        super.onResume();

        if(netOk){
            Toast.makeText(getActivity(),"U GOT NET" , Toast.LENGTH_LONG).show();
        }else{
            Toast.makeText(getActivity(),"U DON'T GOT NET" , Toast.LENGTH_LONG).show();
        }
    }


    public class ConnectionChangeReceiver1 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){
                netOk= true;
            }else{
                netOk= false;
            }
        }
    }
}

The thing is, that the netOk, stays on false. Now I understand that only after - onCreate, onStart, onResume - only after than the receiver class is being called.

So the question is: if I want to know before the activity is shown to the user if there's a internet connection or not, what should I do?


Solution

  • You can try this to get the response synchronously.

    public static boolean checkInternetConnection(Context context) {
    
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        // test for connection
        if (cm != null && cm.getActiveNetworkInfo().isConnected() 
                && cm.getActiveNetworkInfo().isAvailable()) {
            return true;
        }
        return false;
    }