我希望 android 应用程序仅使用移动数据,即使 WIFI 和移动数据都在Android 6中。如何仅将 android 进程绑定到移动数据。
请建议。例子会很好。
问问题
3582 次
3 回答
5
如果你的安卓版本是 M 或以上,你可以很容易地做到这一点。首先,您需要正确的清单权限: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
这是一个应该做你需要的示例方法:
public static void forceConnectionToMobile2(Context context) {
final ConnectivityManager connection_manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkRequest.Builder request = new NetworkRequest.Builder();
Log.d(TAG,"request TRANSPORT_CELLULAR");
request.addCapability(NetworkCapabilities.TRANSPORT_CELLULAR);
connection_manager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.d(TAG,"binding app to cellular network");
connection_manager.bindProcessToNetwork(network);
}
}
});
}
}
于 2016-10-24T19:10:32.773 回答
2
boolean mobileDataEnabled = false;
try {
Class cmClass = Class.forName(connection_manager.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true);
mobileDataEnabled = (Boolean) method.invoke(connection_manager);
} catch (Exception e) {
}
First check if mobile data enable or disable then do
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
connection_manager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
connection_manager.bindProcessToNetwork(network);
}
}
于 2017-09-29T10:34:53.420 回答
0
您可以访问Android force app使用移动数据通道
manager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
if(manager.isWifiEnabled()) {
manager.setWifiEnabled(false);
}
// and to be sure:
ConnectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
于 2016-10-24T10:58:51.540 回答