本文介紹使用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>