2009-12-27 94 views
20

我想寫一個非常簡單的Android應用程序,檢查當前單元格的信號強度。到目前爲止,我只找到一種叫做getNeighboringCellInfo()的東西,但我不確定那是否包含當前單元格。如何在Android中獲取細胞服務信號強度?

如何獲得Android中的CURRENT單元信號強度?

getNeighborCellInfo()是否獲取當前單元格?它似乎不是基於我已經能夠得到的結果。這裏是我當前的代碼:

List<NeighboringCellInfo> n = tm.getNeighboringCellInfo(); 

//Construct the string 
String s = ""; 
int rss = 0; 
int cid = 0; 
for (NeighboringCellInfo nci : n) 
{ 
    cid = nci.getCid(); 
    rss = -113 + 2*nci.getRssi(); 
    s += "Cell ID: " + Integer.toString(cid) + "  Signal Power (dBm): " + 
      Integer.toString(rss) + "\n"; 
} 

mainText.setText(s); 
+0

不錯的d容易[教程](http://www.firstdroid.com/2010/05/12/get-provider-gsm-signal-strength/) – mjosh 2013-05-26 19:41:31

回答

19

創建PhoneStateListener和處理onSignalStrengthChanged回調。當你的應用程序初始化時,它應該給你一個初始通知。這是1.x.在2.x中,這裏有一個開放的issue

+0

這是否工作在3.x和4.x? – Supuhstar 2014-03-18 02:11:45

+0

4.x - 8.x的任何解決方案? – gtzinos 2017-09-04 19:31:35

13

此代碼可以幫助:

PhoneStateListener phoneStateListener = new PhoneStateListener() { 
public void onCallForwardingIndicatorChanged(boolean cfi) {} 
public void onCallStateChanged(int state, String incomingNumber) {} 
public void onCellLocationChanged(CellLocation location) {} 
public void onDataActivity(int direction) {} 
public void onDataConnectionStateChanged(int state) {} 
public void onMessageWaitingIndicatorChanged(boolean mwi) {} 
public void onServiceStateChanged(ServiceState serviceState) {} 
public void onSignalStrengthChanged(int asu) {} 
}; 

一旦你創建了自己的電話狀態偵聽器,使用位掩碼來指示要監聽的事件與電話管理器註冊,如圖所示下面的代碼片段:

TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); 

telephonyManager.listen(phoneStateListener, 
PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR | 
PhoneStateListener.LISTEN_CALL_STATE | 
PhoneStateListener.LISTEN_CELL_LOCATION | 
PhoneStateListener.LISTEN_DATA_ACTIVITY | 
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE | 
PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR | 
PhoneStateListener.LISTEN_SERVICE_STATE | 
PhoneStateListener.LISTEN_SIGNAL_STRENGTH); 

此外,需要將這些添加到AndroidManifest.xml中:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>