监听手机来电

来源:互联网 发布:李维斯眼镜框 知乎 编辑:程序博客网 时间:2024/06/10 06:16

上文通过TelephonyManager获取了手机网络、SIM卡的相关信息,在本文中通过监听TelephonyManager的通话状态来监听手机的所有来电,代码如下:

package com.guyun.activity;import com.guyun.listenphonestate.R;import android.app.Activity;import android.os.Bundle;import android.telephony.PhoneStateListener;import android.telephony.TelephonyManager;import android.widget.Toast;public class PhoneStateActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// 获取系统服务(电话管理器)TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);// 创建电话状态改变的监听器PhoneStateListener phoneListener = new PhoneStateListener() {// 当来电状态改变时触发@Overridepublic void onCallStateChanged(int state, String incomingNumber) {super.onCallStateChanged(state, incomingNumber);switch (state) {// 无任何状态case TelephonyManager.CALL_STATE_IDLE:Toast.makeText(PhoneStateActivity.this, "无任何状态",Toast.LENGTH_LONG).show();break;// 接通电话状态case TelephonyManager.CALL_STATE_OFFHOOK:Toast.makeText(PhoneStateActivity.this, "电话已接通",Toast.LENGTH_LONG).show();break;// 来电状态case TelephonyManager.CALL_STATE_RINGING:Toast.makeText(PhoneStateActivity.this,"来电显示:" + incomingNumber, Toast.LENGTH_LONG).show();break;}}};// 为TelephonyManager注册监听器tm.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);}}


布局XML省略