Checking internet connection with service on android

后端 未结 3 2073
时光取名叫无心
时光取名叫无心 2020-12-31 19:39

I know how to check for internet connectivity when my app is open using activity. But how to check for connectivity in service when my app is not running?

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 20:13

    You might need to use broadcast receiver. You will continuously receive updates in connectivity.(Connected/Disconnected)

    Example:

    Manifest:

    Permissions:

        
        
    

    Register broadcast receiver:

    
        
            
        
    
    

    Create receiver class:

    public class ConnectivityChangeReceiver extends BroadcastReceiver {
    
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
            // Explicitly specify that which service class will handle the intent.
            ComponentName comp = new ComponentName(context.getPackageName(),
                    YourService.class.getName());
            intent.putExtra("isNetworkConnected",isConnected(context));
            startService(context, (intent.setComponent(comp)));
        }
    
     public  boolean isConnected(Context context) {
               ConnectivityManager connectivityManager = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE));
               NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
               return networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected();
       }
    
    }
    

    Your service class:

    class YourService extends IntentService{
    
        @Override
        protected void onHandleIntent(Intent intent) {
          Bundle extras = intent.getExtras();
          boolean isNetworkConnected = extras.getBoolean("isNetworkConnected");
          // your code
    
       }
    
    }
    

提交回复
热议问题