自动关闭应用程序时如何自动关闭WiFi。

huangapple go评论66阅读模式
英文:

How to turn OFF WiFi automatically when the app closes

问题

我已经使用以下代码打开了 WiFi:

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null)
    wifiManager.setWifiEnabled(true);

现在当我关闭我的应用程序时,我想将 WiFi 关闭。我尝试过使用 onDestroy() 方法,但它不起作用,请指导我。

英文:

I have already turned ON WiFi using this :

 WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (wifiManager != null)
        wifiManager.setWifiEnabled(true);

Now I want to turn it off when I close my app I have tried by using onDestory() method it does not work guide me.

答案1

得分: 2

尝试在调用super.onDestroy()之前使用setWifiEnabled(false)

@Override
public void onDestroy() {
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
    if(wifiManager!=null) wifiManager.setWifiEnabled(false);
    super.onDestroy();
}

注意,此方法在API 29及更高版本中已被弃用,在您的应用程序目标为API 29或更高版本(这是在Google Play上发布时必需的,或者即将成为必需的)时,将返回false并且不会更改WiFi状态。

英文:

try to setWifiEnabled(false) before calling super.onDestroy()

@Override
public void onDestroy() {
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
    if(wifiManager!=null) wifiManager.setWifiEnabled(false);
    super.onDestroy();
}

note that this method is deprecated in API29 and above, will return false and won't change WiFi state when your app will target API29 or above (which is, or will be soon, mandatory for publishing in Google Play)

huangapple
  • 本文由 发表于 2020年8月31日 21:42:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63671963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定