Detect CONNECTIVITY CHANGE in Android 7 and above when app is killed/in background

后端 未结 5 1674
礼貌的吻别
礼貌的吻别 2020-11-27 12:56

Problem:

So the problem is that I have an app which sends a request to our backend whenever WiFi is connected (with the connected SSID and other inf

5条回答
  •  猫巷女王i
    2020-11-27 13:12

    The best way to grab Connectivity change Android Os 7 and above is register your ConnectivityReceiver broadcast in Application class like below, This helps you to get changes in background as well until your app alive.

    public class MyApplication extends Application {
    
          private ConnectivityReceiver connectivityReceiver;
    
          private ConnectivityReceiver getConnectivityReceiver() {
              if (connectivityReceiver == null)
                   connectivityReceiver = new ConnectivityReceiver();
    
              return connectivityReceiver;
           }
           @Override
           public void onCreate() {
             super.onCreate();
             registerConnectivityReceiver();
           }
    
         // register here your filtters 
         private void registerConnectivityReceiver(){
           try {
              // if (android.os.Build.VERSION.SDK_INT >= 26) {
              IntentFilter filter = new IntentFilter();
              filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
              //filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
              //filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
              //filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
              registerReceiver(getConnectivityReceiver(), filter);
           } catch (Exception e) {
             MLog.e(TAG, e.getMessage());
           }
     }
    
    }
    

    And then in manifest

         
    

    Here is your ConnectivityReceiver.java

     public class ConnectivityReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(final Context context, final Intent intent) {
          MLog.v(TAG, "onReceive().." + intent.getAction());
          }
        }
    

提交回复
热议问题