Check if background restriction data is enabled or not?

﹥>﹥吖頭↗ 提交于 2019-12-06 05:03:34

问题


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*/
    
    }
    


来源:https://stackoverflow.com/questions/28986395/check-if-background-restriction-data-is-enabled-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!