TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TelephonyManager 提供了一种获取手机信息的方式,包括通话状态、网络连接、运营商信息等,
下面通过一个实例展示TelephonyManager 对通话状态监控:
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "Telephony";
TextView view = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TelephonyManager mTelephonyMgr =
(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.listen(new TeleListener(),PhoneStateListener.LISTEN_CALL_STATE);
view = new TextView(this);
view.setText("listen the state of phone\n");
setContentView(view);
}
class TeleListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber)
{
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE: {
Log.d(TAG, "CALL_STATE_IDLE");
view.append("CALL_STATE_IDLE " + "\n");
break;
}
case TelephonyManager.CALL_STATE_OFFHOOK: {
Log.d(TAG, "CALL_STATE_OFFHOOK");
view.append("CALL_STATE_OFFHOOK" + "\n");
break;
}
case TelephonyManager.CALL_STATE_RINGING: {
Log.d(TAG, "CALL_STATE_RINGING");
view.append("CALL_STATE_RINGING" + "\n");
break;
}
default:
Log.d(TAG, " the statu is"+state);
break;
}
}
}
}