获取当前/状态已更改的单元信号强度。从不调用onStateSignalChanged

时间:2018-08-12 15:07:57

标签: java android

目标:获取当前/状态已更改的单元信号强度。

问题 :(在此处以及在developer.android网站上)的阅读使我了解了此代码。但这是行不通的。我的意思是我已经尝试在onSignalStrengthChanged回调调用上设置断点,但是从未调用过。 我还声明了对Android清单的粗略位置权限(getAllCellInfo()需要此权限。

问题:

1)为什么从未onSignalStrengthChanged被调用?

2)我想刚才的回调将在信号强度改变时被调用。但是如何在改变之前获得当前信号强度?

@Override
        protected void onCreate(Bundle savedInstanceState) {
 telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            telephonyManager.listen(new PhoneStateListener(), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}

public void onSignalStrengthsChanged(SignalStrength signalStrength){
            try{
                int level;

                for (final CellInfo info : telephonyManager.getAllCellInfo() ){

                    if (info instanceof CellInfoGsm) {
                        final CellSignalStrengthGsm gsm = ((CellInfoGsm) info).getCellSignalStrength();
                        // do what you need
                        level = gsm.getLevel();
                        Toast.makeText(getApplicationContext(), "gsm rssi"+level, Toast.LENGTH_LONG).show();
                    } else if (info instanceof CellInfoCdma) {
                        final CellSignalStrengthCdma cdma = ((CellInfoCdma) info).getCellSignalStrength();
                        // do what you need
                        level = cdma.getLevel();
                        Toast.makeText(getApplicationContext(), "cdma rssi"+level, Toast.LENGTH_LONG).show();
                    } else if (info instanceof CellInfoLte) {
                        final CellSignalStrengthLte lte = ((CellInfoLte) info).getCellSignalStrength();
                        // do what you need
                        level = lte.getLevel();
                        Toast.makeText(getApplicationContext(), "lte rssi"+level, Toast.LENGTH_LONG).show();
                    } else {
                        throw new Exception("Unknown type of cell signal!");
                    }


                }

            }
            catch (Exception e) {

            }

        }

1 个答案:

答案 0 :(得分:1)

首先全局定义以下提到的变量:

TelephonyManager telephonyManager;
MyPhoneStateListener psListener;
TextView txtSignalStr;

onCreate方法:

@Override
protected void onCreate(final Bundle savedInstanceState) {
 psListener = new MyPhoneStateListener();
 telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
 telephonyManager.listen(psListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}

创建将扩展PhoneStateListener

的内部类

并在@Override之类的方法之前使用onSignalStrengthsChanged注释

创建MyPhoneStateListener类:

public class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength)
{
 super.onSignalStrengthsChanged(signalStrength);
//your Code
 }
}