Check if background restriction data is enabled or

2019-04-10 13:06发布

问题:

I have a service which is running on the main thread not in the background. In the service I'm checking net connection via broadcastreciver. When I enable restriction data enabled in Settings, broadcastreciver is catching intent well, but internet connection(Mobile data) is disabled to my app although it has on my device. I've seen this question, and android docs.

intentFilter.addAction("android.net.conn.ACTION_BACKGROUND_DATA_SETTING_CHANGED");
    intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    registerReceiver(this.connectionStatusReceiver, intentFilter);


private BroadcastReceiver connectionStatusReceiver = new BroadcastReceiver() {
    @Override
    public synchronized void onReceive(Context context, Intent intent) {
        log.info("connection state changed");            
        checkConnectionState();
    }
};

 getActiveNetworkInfo() - *will always display CONNECTED when i switch on *restriction**

One more thing, when I switch on background data restrict, I checked intent.getAction. It always returns android.net.conn.CONNECTIVITY_CHANGE. How can I check background restriction data is switched on/off?

回答1:

You can check that from Android 7.0 (API 24) and above. Google added the howto in their android developer site. Here is the link Optimizing Network Data Usage



回答2:

1.Use the following code to check whether the wifi or mobile data has been switched on or not.

public boolean isConnectingToInternet()
    {

        ConnectivityManager connectivity = 
                             (ConnectivityManager) getApplicationContext().getSystemService(
                              Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }
  1. Then on basis of true or false, check for restricted data:

    if(isConnectingToInternet())
    {
    
          /*
          your code to check network state*/
    
    }