2011-01-30 95 views
4

有誰知道在android中獲取電話服務狀態(IN_SERVICE,OUT_OF_SERVICE,EMERGENCY_ONLY,POWER_OFF)的方法。廣播接收器獲取服務狀態信息

我希望有一個廣播回憶者來識別這些變化,但我找不到任何東西。我知道有一個監聽器,但我不知道如何從我的應用程序使用它,因爲它使用WakefulIntentService(bycommonsguy)作爲服務運行。

像電池電量(即BATTERY_LOW,BATTERY_OKAY)這很容易,但我不能爲電話服務的變化制定類似的事情。

回答

0

你可以編寫自己的BroadcastReceiver。您的接收器將接收連接的變化,並告知您需要的情況下對變化(例如自己CommunicationManager):

public class ConnectivityReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 
    Log.i(getClass().getName(), "A change in network connectivity has occurred. Notifying communication manager for further action."); 
    NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); 
    if(info != null) { 
     Log.v(getClass().getName(), "Reported connectivity status is " + info.getState() + "."); 
    } 
    CommunicationManager.updateConnectivityState(); // Notify connection manager 
} 

} 

例如這裏您CommunicationManager例如,將被通知連接的變化:

protected static void updateConnectivityState() 
{ 
    boolean isConnected = false; 
    if (_connec != null && (_connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) ||(_connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)){ 
     isConnected = true; 
     Log.i(CommunicationManager.class.getName(), "Device is connected to the network. Online mode is available."); 
    }else if (_connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || _connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {    
     isConnected = false; 
     Log.w(CommunicationManager.class.getName(), "Device is NOT connected to the network. Offline mode."); 
    } 
    _isConnected = isConnected; 
} 

請查看NetworkInfo類以獲取有關連接可用性的更多詳細信息。

不要忘了在你的清單中註冊許可權在未經許可:

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

我希望這有助於。問候

+0

爲什麼這是低調?有任何想法嗎? – cbrulak 2012-08-09 03:06:16

+1

可能因爲ServiceState不是NetworkState。 ServiceState是電話無線電的狀態,而NetworkState會爲您提供數據連接的狀態(可能是wifi,wimax ...即不是電話網絡) – 2012-12-17 16:39:27

2

當你在你接收器的意圖只是使用下面的小黑客從Android的源服務狀態類的

public void onReceive(Context context, Intent intent) { 
    int state = intent.getExtras().getInt("state"); 
    if(state == ServiceState.STATE_IN_SERVICE) 
    { 
     //Do whatever you want 
    } 
    } 

檢查源註冊一個接收器

public static final String ACTION_SERVICE_STATE_CHANGED = "android.intent.action.SERVICE_STATE"; 

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/1.5_r4/android/telephony/ServiceState.java#ServiceState.setFromNotifierBundle%28android.os.Bundle%29