Detecting “use only 2G networks” setting

前端 未结 2 1269
面向向阳花
面向向阳花 2021-02-09 05:36

Is there a way of returning the value of Android\'s mobile network setting for \"use only 2G networks\"?

The app being developed measures the internet speed at a certain

2条回答
  •  渐次进展
    2021-02-09 06:35

    As far as I can tell, there is no documented way of getting value for that setting. But there is a Use2GOnlyCheckBoxPreference class that can be used as an example. It uses internal Phone and PhoneFactory classes to obtain the current value of prefer_2g setting.

    You can use Phone and PhoneFactory classes via reflection. But of cause this is undocumented and is on your own risk. Here is relevant code from Use2GOnlyCheckBoxPreference:

    import com.android.internal.telephony.Phone;
    import com.android.internal.telephony.PhoneFactory;
    
    public class Use2GOnlyCheckBoxPreference extends CheckBoxPreference {
    
        private Phone mPhone;
        private MyHandler mHandler;
    
        public Use2GOnlyCheckBoxPreference(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            mPhone = PhoneFactory.getDefaultPhone();
            mHandler = new MyHandler();
            mPhone.getPreferredNetworkType(
                    mHandler.obtainMessage(MyHandler.MESSAGE_GET_PREFERRED_NETWORK_TYPE));
        }
    
        private class MyHandler extends Handler {
    
            private static final int MESSAGE_GET_PREFERRED_NETWORK_TYPE = 0;
    
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MESSAGE_GET_PREFERRED_NETWORK_TYPE:
                        handleGetPreferredNetworkTypeResponse(msg);
                        break;
                }
            }
    
            private void handleGetPreferredNetworkTypeResponse(Message msg) {
                AsyncResult ar = (AsyncResult) msg.obj;
    
                if (ar.exception == null) {
                    int type = ((int[])ar.result)[0];
                    Log.i(LOG_TAG, "get preferred network type="+type);
                    setChecked(type == Phone.NT_MODE_GSM_ONLY);
                } else {
                    // Weird state, disable the setting
                    Log.i(LOG_TAG, "get preferred network type, exception="+ar.exception);
                    setEnabled(false);
                }
            }
        }   
    }
    

提交回复
热议问题