Android开发教程:借助TelephonyManager获取移动网络信息
发布时间:2021-11-24 13:16:46 所属栏目:教程 来源:互联网
导读:本文介绍使用TelephonyManager来获取手机SIM卡的状态和移动网络的相关信息,主要使用了TelephonyManager.listen函数,这个函数源码如下: [java] public void listen(PhoneStateListener listener, int events) { String pkgForDebug = mContext != null ? m
|
本文介绍使用TelephonyManager来获取手机SIM卡的状态和移动网络的相关信息,主要使用了TelephonyManager.listen函数,这个函数源码如下: [java] public void listen(PhoneStateListener listener, int events) { String pkgForDebug = mContext != null ? mContext.getPackageName() : "<unknown>"; try { Boolean notifyNow = (getITelephony() != null); mRegistry.listen(pkgForDebug, listener.callback, events, notifyNow); } catch (RemoteException ex) { // system process dead } catch (NullPointerException ex) { // system process dead } } 具体的实现不是本文的重点,这里只来了解函数的两个参数: 1)PhoneStateListener listener 一般根据events的值,来实现相应的回调函数接口,在回调函数里面执行我们的处理,这些接口包括: [java] public void onServiceStateChanged(ServiceState serviceState) public void onMessageWaitingIndicatorChanged(boolean mwi) public void onCallForwardingIndicatorChanged(boolean cfi) public void onCellLocationChanged(CellLocation location) public void onCallStateChanged(int state, String incomingNumber) public void onDataConnectionStateChanged(int state) public void onDataConnectionStateChanged(int state, int networkType) public void onDataActivity(int direction) public void onSignalStrengthsChanged(SignalStrength signalStrength) 2)int events Events取值如下: [java] public static final int LISTEN_NONE = 0; //停止监听 public static final int LISTEN_SERVICE_STATE = 0x00000001; public static final int LISTEN_MESSAGE_WAITING_INDICATOR = 0x00000004; public static final int LISTEN_CALL_FORWARDING_INDICATOR = 0x00000008; public static final int LISTEN_CELL_LOCATION = 0x00000010; public static final int LISTEN_CALL_STATE = 0x00000020; public static final int LISTEN_DATA_CONNECTION_STATE = 0x00000040; public static final int LISTEN_DATA_ACTIVITY = 0x00000080; public static final int LISTEN_SIGNAL_STRENGTHS = 0x00000100; 下面就是使用了上面知识点的代码了,先看布局文件network_detector.xml: [html] <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/phone_type" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/network_name" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/sim_state" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/network_type" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> ![]() (编辑:文章分享网_茂名站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |


