记录Android7.0监控sim卡信号值
控制台打印效果
对象和常量
private TelephonyManager mTelephonyManager;
private static final int NETWORKTYPE_WIFI = 0;
private static final int NETWORKTYPE_4G = 1;
private static final int NETWORKTYPE_2G = 2;
private static final int NETWORKTYPE_NONE = 3;
开始监听定义对象 顺序不可变
getPhoneStateListener();//开始监听
//获取telephonyManager
mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//监听信号强度
mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
显示网络信号
/**
* 显示网络信号
*/
public void getPhoneStateListener() {
//开始监听
Log.e("TAG", "getPhoneStateListener: ");
mListener = new PhoneStateListener() {
@SuppressLint("SetTextI18n")
@Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
int gsmSignalStrength = signalStrength.getGsmSignalStrength();
signal = gsmSignalStrength + "";
//获取网络类型
int netWorkType = getNetWorkType(MyApplication.getMyApplication());
switch (netWorkType) {
case NETWORKTYPE_WIFI:
CommonUtil.showLog("wifi信号:" + gsmSignalStrength);
break;
case NETWORKTYPE_4G:
CommonUtil.showLog("4G信号:" + gsmSignalStrength);
break;
case NETWORKTYPE_NONE:
LogUtils.startLog("当前没有网络,信号强度为:" + gsmSignalStrength);
break;
case -1:
LogUtils.startLog("当前网络错误,信号强度为:" + gsmSignalStrength);
break;
}
}
};
}
判断网络类型
/**
* 判断网络类型
*/
private static boolean isFastMobileNetwork(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE) {
//这里只简单区分两种类型网络,认为4G网络为快速,但最终还需要参考信号值
return true;
}
return false;
}
判断是wifi还是sim卡
/**
* 判断是wifi还是sim卡
*/
public static int getNetWorkType(Context context) {
int mNetWorkType = -1;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String type = networkInfo.getTypeName();
if (type.equalsIgnoreCase("WIFI")) {
mNetWorkType = NETWORKTYPE_WIFI;
} else if (type.equalsIgnoreCase("MOBILE")) {
//返回是4G还是2G
return isFastMobileNetwork(context) ? NETWORKTYPE_4G : NETWORKTYPE_2G;
//我不管就是返回4G
//return NETWORKTYPE_4G;
}
} else {
mNetWorkType = NETWORKTYPE_NONE;//没有网络
}
return mNetWorkType;
}
protected void onResume() {
super.onResume();
mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
protected void onPause() {
super.onPause();
//用户不在当前页面时,停止监听
mTelephonyManager.listen(mListener, PhoneStateListener.LISTEN_NONE);
}