gpt4 book ai didi

Android:ConnectivityManager 总是返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:48 24 4
gpt4 key购买 nike

我总是得到一个空指针异常,即使我在这段代码上连接到 wifi 也是如此:

       ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
Log.d("Problem", connectivityManager.getActiveNetworkInfo().toString());

我的权限是:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.SEND_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CONNECTIVITY_CHANGE" />

我错过了什么:/?我只需要知道他何时连接到 wifi 热点以及何时发生变化。但是连接管理器总是在 ActiveNetworkInfo 上返回 null

最佳答案

用这个可以知道WIFI有没有连上。

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class Network {
private Context context;
private ConnectivityManager connManager;

public Network(Context ctx) {
this.context = ctx;
}

public boolean getConnectivityStatus() {
connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo info = connManager.getActiveNetworkInfo();
if (info != null)
return info.isConnected(); // WIFI connected
else
return false; // no info object implies no connectivity
}

关于Android:ConnectivityManager 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9664757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com