歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程:使用TelephonyManager獲取移動網絡信息

Android開發教程:使用TelephonyManager獲取移動網絡信息

日期:2017/3/1 10:30:28   编辑:Linux編程

本文介紹使用TelephonyManager來獲取手機SIM卡的狀態和移動網絡的相關信息,主要使用了TelephonyManager.listen函數,這個函數源碼如下:

[java]
  1. public void listen(PhoneStateListener listener, int events) {
  2. String pkgForDebug = mContext != null ? mContext.getPackageName() : "<unknown>";
  3. try {
  4. Boolean notifyNow = (getITelephony() != null);
  5. mRegistry.listen(pkgForDebug, listener.callback, events, notifyNow);
  6. } catch (RemoteException ex) {
  7. // system process dead
  8. } catch (NullPointerException ex) {
  9. // system process dead
  10. }
  11. }

具體的實現不是本文的重點,這裡只來了解函數的兩個參數:

1)PhoneStateListener listener

一般根據events的值,來實現相應的回調函數接口,在回調函數裡面執行我們的處理,這些接口包括:

[java]
  1. public void onServiceStateChanged(ServiceState serviceState)
  2. public void onMessageWaitingIndicatorChanged(boolean mwi)
  3. public void onCallForwardingIndicatorChanged(boolean cfi)
  4. public void onCellLocationChanged(CellLocation location)
  5. public void onCallStateChanged(int state, String incomingNumber)
  6. public void onDataConnectionStateChanged(int state)
  7. public void onDataConnectionStateChanged(int state, int networkType)
  8. public void onDataActivity(int direction)
  9. public void onSignalStrengthsChanged(SignalStrength signalStrength)

2)int events

Events取值如下:

[java]
  1. public static final int LISTEN_NONE = 0; //停止監聽
  2. public static final int LISTEN_SERVICE_STATE = 0x00000001;
  3. public static final int LISTEN_MESSAGE_WAITING_INDICATOR = 0x00000004;
  4. public static final int LISTEN_CALL_FORWARDING_INDICATOR = 0x00000008;
  5. public static final int LISTEN_CELL_LOCATION = 0x00000010;
  6. public static final int LISTEN_CALL_STATE = 0x00000020;
  7. public static final int LISTEN_DATA_CONNECTION_STATE = 0x00000040;
  8. public static final int LISTEN_DATA_ACTIVITY = 0x00000080;
  9. public static final int LISTEN_SIGNAL_STRENGTHS = 0x00000100;

下面就是使用了上面知識點的代碼了,先看布局文件network_detector.xml:

[html]
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView android:id="@+id/phone_type"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content" />
  10. <TextView android:id="@+id/network_name"
  11. android:layout_width="fill_parent"
  12. android:layout_height="wrap_content" />
  13. <TextView android:id="@+id/sim_state"
  14. android:layout_width="fill_parent"
  15. android:layout_height="wrap_content" />
  16. <TextView android:id="@+id/network_type"
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content" />
  19. </LinearLayout>
Copyright © Linux教程網 All Rights Reserved