有没有人知道在Android中获取电话服务状态(IN_SERVICE,OUT_OF_SERVICE,EMERGENCY_ONLY,POWER_OFF)的方法。
我希望有一个广播记录来识别这些变化,但我找不到任何东西。我知道有一个听众,但我不确定如何使用我的应用程序,因为它使用WakefulIntentService(通过thecommonsguy)作为服务运行。
有了类似电池电量的东西(即BATTERY_LOW,BATTERY_OKAY),这很容易,但我无法解决类似的电话服务变化问题。
答案 0 :(得分: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
}
}
答案 1 :(得分: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课程,了解有关连接可用性的更多详细信息。
不要忘记在清单中注册ACCESS_NETWORK_STATE权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
我希望这会有所帮助。此致