I have a ToggleButton named gprs. I need it to turn on and off the gprs. How to accomplish that? I've looked here but it gives errros and I can't figure it out how to use it in my case.
问问题
818 次
1 回答
0
好的,如果有人有同样的问题,我会在这里发布解决方案,使用切换按钮。首先,我为 gprs 设置创建了单独的类:
public class GprsSettings {
static void setMobileDataEnabled(Context context, boolean enabled) {
try {
final ConnectivityManager conman = (ConnectivityManager) context.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);
Log.i("setMobileDataEnabled()","OK");
}
catch (Exception e)
{
e.printStackTrace();
Log.i("setMobileDataEnabled()","FAIL");
}
}
}
然后,首先在我的活动中添加一些代码来检查 gprs 是打开还是关闭....将它放在您的 onCreate 方法之上:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
}
然后,在我的活动中,我将此代码用于带有 toast 的切换按钮:
gprs.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
if (((ToggleButton)v).isChecked()) {
GprsSettings.setMobileDataEnabled(getApplicationContext(), true);
Toast.makeText(getApplicationContext(), "GPRS is ON", Toast.LENGTH_LONG).show();
}else{
GprsSettings.setMobileDataEnabled(getApplicationContext(), false);
Toast.makeText(getApplicationContext(), "GPRS is OFF", Toast.LENGTH_LONG).show();
}
}
catch (Exception localException) {
Log.e("SwarmPopup", "error on GPRS listerner: " + localException.getMessage(), localException);
}
}
});
gprs.setChecked(isNetworkConnected());
就是这样,就像一个魅力。
于 2013-03-13T12:30:10.590 回答