我在Android中遇到错误。尝试使用
registerNetworkCallback(NetworkRequest request, ConnectivityManager.NetworkCallback networkCallback)
api用于寄存器以接收有关满足给定NetworkRequest的所有网络的通知。 https://developer.android.com/reference/android/net/ConnectivityManager.html
错误消息是
Error:(29, 39) error: cannot find symbol class NetworkCallback
我的理解是NetworkCallback是android.net.ConnectivityManager中的嵌套静态类。 proguard.pro不保留该类。所以编译器找不到它。
代码是
import android.net.ConnectivityManager.NetworkCallback;
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder = null;
if (android.os.Build.VERSION.SDK_INT >= 21) {
builder = new NetworkRequest.Builder();
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
};
NetworkRequest networkRequest = builder.build();
connMgr.requestNetwork(networkRequest, networkCallback);
connMgr.registerNetworkCallback(networkRequest, networkCallback);
}
proguard.pro是
-keep class android.net.** { *; }
gradle build
compileSdkVersion 25
buildToolsVersion '25.0.3'
minSdkVersion 15
targetSdkVersion 25
如何解决错误?
答案 0 :(得分:0)
我设法用
完成了import android.net.ConnectivityManager;
...
...
然后,我创建了一个特定的回调
private ConnectivityManager.NetworkCallback x = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
Log.d(TAG, "requestNetwork onAvailable()");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
connectivityManager.bindProcessToNetwork(network);
}
} else {
//This method was deprecated in API level 23
ConnectivityManager.setProcessDefaultNetwork(network);
}
// Your job can be done here ..
// then
connectivityManager.unregisterNetworkCallback(this);
}
@Override
public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
Log.d(TAG, "requestNetwork onCapabilitiesChanged()");
}
@Override
public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {
Log.d(TAG, "requestNetwork onLinkPropertiesChanged()");
}
@Override
public void onLosing(Network network, int maxMsToLive) {
Log.d(TAG, "requestNetwork onLosing()");
}
@Override
public void onLost(Network network) {
Log.d(TAG, "requestNetwork onLost()");
}
};
...
...
然后,在你的主程序中,例如,如果你想使用wifi连接,没有互联网访问
NetworkRequest.Builder builder = new NetworkRequest.Builder();
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
builder.removeTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
NetworkRequest request = builder.build();
final ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.requestNetwork(request, x);