PhoneStateListener
PhoneStateListener是Android SDK提供用來監控目前和SIM卡網路狀態有關的一個類別,
從官網可以看到有以下狀態可查看:
LISTEN_CALL_FORWARDING_INDICATOR
查看來電轉接狀態是否有改變
LISTEN_CALL_STATE
查看通話狀態是否有改變
LISTEN_CELL_INFO
查看連線到的基地台資訊
LISTEN_CELL_LOCATION
查看連線到的基地台位置
LISTEN_DATA_ACTIVITY
查看以SIM卡上網的網路傳輸狀態改變
LISTEN_DATA_CONNECTION_STATE
查看以SIM卡上網的連線狀態改變
LISTEN_MESSAGE_WAITING_INDICATOR
查看語音留言狀態的改變
LISTEN_NONE
用以取消所有監控的事件
LISTEN_SERVICE_STATE
查看以SIM卡上網的網路狀態改變
LISTEN_SIGNAL_STRENGTHS
查看以SIM卡上網的訊號改變
使用方式:
// get TelephonyManager
mTelephonyManager=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
stateListener = new PhoneStateListener(){
@Override
public void onDataConnectionStateChanged(int state){
switch(state){
case TelephonyManager.DATA_DISCONNECTED:
Log.i("State: ", "DISCONNECTED");
break;
case TelephonyManager.DATA_SUSPENDED:
Log.i("State: ", "SUSPENDED");
break;
}
}
@Override
public void onServiceStateChanged (ServiceState serviceState) {
super.onServiceStateChanged(serviceState);
String phonestate;
switch(serviceState.getState()) {
case ServiceState.STATE_EMERGENCY_ONLY:
phonestate ="STATE_EMERGENCY_ONLY";
break;
case ServiceState.STATE_IN_SERVICE:
phonestate ="STATE_IN_SERVICE";
break;
case ServiceState.STATE_OUT_OF_SERVICE:
phonestate ="STATE_OUT_OF_SERVICE";
break;
case ServiceState.STATE_POWER_OFF:
phonestate ="STATE_POWER_OFF";
break;
default:
phonestate = "Unknown";
break;
}
}
};
//start listening
mTelephonyManager.listen(stateListener,
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
|PhoneStateListener.LISTEN_SERVICE_STATE);