我有一个名为gprs的ToggleButton。我需要它来打开和关闭gprs。如何做到这一点?我看过here,但它给出了错误,我无法弄清楚如何在我的情况下使用它。

最佳答案

好的,如果有任何问题,我将在此处使用切换按钮发布解决方案。首先,我为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());


就是这样,就像一个魅力。

07-24 15:36