Java Android 使用代码打开/关闭移动数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23100298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android turn on/off mobile data using code
提问by user2933671
I am trying to approach a problem in which I have to disable and then enable mobile data with some delay in between (reset mobile data 2G).
我正在尝试解决一个问题,即我必须禁用然后启用移动数据,中间有一些延迟(重置移动数据 2G)。
step 1: disable mobile data
第 1 步:禁用移动数据
step 2: wait till mobile data gets disabled
第 2 步:等到移动数据被禁用
step 3: some delay say 2 seconds
第 3 步:一些延迟说 2 秒
step 4: enable mobile data
第 4 步:启用移动数据
step 5: wait till mobile data gets enabled
第 5 步:等待移动数据启用
step 6: continue with the program.....
第 6 步:继续程序.....
doing some research I came up with this...
做了一些研究,我想出了这个......
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.button1);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(!mobileDataEnabled(getApplicationContext())){
setMobileDataEnabled(getApplicationContext(),true);
Toast.makeText(getApplicationContext(), "ENABLED", Toast.LENGTH_SHORT).show();
}else{
setMobileDataEnabled(getApplicationContext(),false);
Toast.makeText(getApplicationContext(), "DISABLED", Toast.LENGTH_SHORT).show();
}
}
});
}
//the method below enables/disables mobile data depending on the Boolean 'enabled' parameter.
private void setMobileDataEnabled(Context context, boolean enabled) {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Class conmanClass = null;
try {
conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// below method returns true if mobile data is on and vice versa
private boolean mobileDataEnabled(Context context){
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
return mobileDataEnabled;
}
The above code will turn on/off mobile data but it happens really quick. this quick that the mobile data doesn't even turn off actually. how do I add a delay in between and achieve the steps I mentioned above? any help would be appreciated. thanks!
上面的代码将打开/关闭移动数据,但它发生得非常快。如此之快以至于移动数据实际上甚至没有关闭。如何在两者之间添加延迟并实现我上面提到的步骤?任何帮助,将不胜感激。谢谢!
回答by SoulRayder
Just put
就放
Thread.sleep(1000);
in between the code statements (before setMobileDataAPIs) to achieve delay. The delay parameter is in milliseconds. So change it according to your requirement.
在代码语句之间(在setMobileDataAPI之前)以实现延迟。延迟参数以毫秒为单位。所以根据您的要求更改它。
EDIT:Try putting the delay into a handler, using this code:
编辑:尝试使用以下代码将延迟放入处理程序中:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//Whatever you want to do
}
}, 1000);
回答by Viswanath Lekshmanan
Try this may work. Use your code for turning off/on your packet data.
试试这个可能有用。使用您的代码关闭/打开您的数据包数据。
You should use a broadcast receiver for getting the events of connectivity.
您应该使用广播接收器来获取连接事件。
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
Check the below link for details
查看以下链接了解详情
回答by Viswanath Lekshmanan
public void mobiledataenable(boolean enabled) {
try {
final ConnectivityManager conman = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
final Class<?> conmanClass = Class.forName(conman.getClass().getName());
final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
iConnectivityManagerField.setAccessible(true);
final Object iConnectivityManager = iConnectivityManagerField.get(conman);
final Class<?> iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
回答by Arwy Shelke
// first check whether it is on\off...
// 首先检查是否开启\关闭...
public void setMobileDataEnabled(Context context, boolean status) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException
{
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(connectivityManager, status);
}