英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论