如何使用切换按钮打开和关闭gprs?

时间:2013-03-13 03:02:22

标签: java android gprs

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

1 个答案:

答案 0 :(得分: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());

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

相关问题