4

有谁知道在android中获取电话服务状态(IN_SERVICE、OUT_OF_SERVICE、EMERGENCY_ONLY、POWER_OFF)的方法。

我希望有一个广播接收器来识别这些变化,但我找不到任何东西。我知道有一个监听器,但我不确定如何在我的应用程序中使用它,因为它使用 WakefulIntentService(由 thecommonsguy 提供)作为服务运行。

使用诸如电池电量(即BATTERY_LOW、BATTERY_OKAY)之类的东西很容易,但我无法为电话服务更改解决类似的问题。

4

2 回答 2

2

注册一个接收器

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

当您对接收器感兴趣时,只需使用以下来自 android 源的小技巧

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

检查服务状态类的来源 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

于 2012-04-04T04:40:09.280 回答
0

您可以编写自己的广播接收器。您的接收器将接收连接更改并将更改通知您所需的实例(例如您自己的 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类以获取有关连接可用性的更多详细信息。

不要忘记在清单中注册 ACCESS_NETWORK_STATE 权限:

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

我希望这有帮助。问候

于 2011-01-30T23:55:16.213 回答