Broadcast receiver for checking internet connection in android app

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

    First of all we will make a class that will check the connectivity of the network state. So lets create a class :

    public class AppStatus {
        private static AppStatus instance = new AppStatus();
        static Context context;
        ConnectivityManager connectivityManager;
        NetworkInfo wifiInfo, mobileInfo;
        boolean connected = false;
    
        public static AppStatus getInstance(Context ctx) {
            context = ctx.getApplicationContext();
            return instance;
        }
    
        public boolean isOnline() {
            try {
                connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
    
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                connected = networkInfo != null && networkInfo.isAvailable() &&
                        networkInfo.isConnected();
                return connected;
    
    
            } catch (Exception e) {
                System.out.println("CheckConnectivity Exception: " + e.getMessage());
                Log.v("connectivity", e.toString());
            }
            return connected;
        }
    }
    

    Now Make a new Broadcast receiver class :

    public class ConnectivityReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (AppStatus.getInstance(context).isOnline()) {
    
                Intent intent1=new Intent(context,DisplayAct.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent1);
    
    
    
    
            } else {
    
                Toast.makeText(context, "Please !! Make your network ON", Toast.LENGTH_SHORT).show();
    
            }
        }
    }
    

    and Now register your broadcast receiver on manifest:

    
                
                    
                
            
    

提交回复
热议问题