You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android类中检查WiFi状态报错:需用Application Context防内存泄漏

解决WIFI_SERVICE获取时的内存泄漏问题

这个问题本质是Context引用导致的内存泄漏风险——当你使用Activity或其他非Application级别的Context获取WifiManager时,系统的WifiManager会长期持有这个Context的引用。如果这个Context对应的组件(比如Activity)已经被销毁,GC无法回收它,就会造成内存泄漏,这就是错误提示的原因。

下面给你两种靠谱的修复方案:

方案一:强制使用Application Context(推荐,无需全局引用)

修改Wifi类的isOn()方法,让它接收Context参数,并在内部转为Application Context:

import android.content.Context;
import android.net.wifi.WifiManager;
import static androidx.core.content.ContextCompat.getSystemService;

public class Wifi {
    public static boolean isOn(Context context) {
        // 转为Application Context,避免持有组件级Context
        Context appContext = context.getApplicationContext();
        WifiManager wifiManager = (WifiManager) getSystemService(appContext, Context.WIFI_SERVICE);
        // 增加空判断,防止getSystemService返回null导致崩溃
        return wifiManager != null && wifiManager.isWifiEnabled();
    }
}

调用的时候,确保传入的Context可以获取到Application Context(比如在Activity里):

// 在Activity中调用
boolean wifiStatus = Wifi.isOn(getApplicationContext());

方案二:全局保存Application Context(适合频繁调用的场景)

如果不想每次调用都传Context,可以在App初始化时保存全局的Application Context引用:

  1. 自定义Application类:
import android.app.Application;

public class MyApp extends Application {
    private static Application sAppInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        sAppInstance = this;
    }

    public static Application getInstance() {
        return sAppInstance;
    }
}
  1. 在AndroidManifest.xml中注册这个Application:
<application
    android:name=".MyApp"
    <!-- 其他原有配置 -->
    >
    <!-- 你的Activity等组件 -->
</application>
  1. 修改Wifi类直接使用全局Application Context:
import android.content.Context;
import android.net.wifi.WifiManager;
import static androidx.core.content.ContextCompat.getSystemService;

public class Wifi {
    public static boolean isOn() {
        WifiManager wifiManager = (WifiManager) getSystemService(MyApp.getInstance(), Context.WIFI_SERVICE);
        return wifiManager != null && wifiManager.isWifiEnabled();
    }
}

这样你就可以直接调用Wifi.isOn(),不用担心内存泄漏问题了。

内容的提问来源于stack exchange,提问作者Elyas Behroozizade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 14:22:41