【问题标题】:How to turn on and off gprs with toggle button?如何使用切换按钮打开和关闭 gprs?
【发布时间】:2013-03-13 03:02:22
【问题描述】:

我有一个名为 gprs 的切换按钮。我需要它来打开和关闭 gprs。如何做到这一点?我看过here,但它给出了错误,我不知道如何在我的情况下使用它。

【问题讨论】:

标签: java android gprs


【解决方案1】:

好的,如果有人有同样的问题,我会在这里发布解决方案,使用切换按钮。首先,我为 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());

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

【讨论】:

  • 实际上它不像一个魅力。它可以工作,但是……即使我手机上的 gprs 已关闭但无线已打开,gprs 按钮仍处于打开状态。 :((
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 2011-09-21
相关资源
最近更新 更多