PhoneState查看拨号器状态及显示联系人信息

添加权限

 

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

 

private TextView myTextView1;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.phone_state);

		myTextView1 = (TextView) findViewById(R.id.myTextView1);

		/* 新增的PhoneStateListener */
		MyPhoneCallListener myPhoneCallListener = new MyPhoneCallListener();
		/* 取得电话服务 */
		TelephonyManager tm = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		/* 注册Listener */
		tm.listen(myPhoneCallListener, PhoneStateListener.LISTEN_CALL_STATE);

	}

	/* 内部class继承PhoneStateListener */
	public class MyPhoneCallListener extends PhoneStateListener {
		/* 重写onCallStateChanged当状态改变时改变myTextView1的文字及颜色 */
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			/* 无任务状态时 */
			case TelephonyManager.CALL_STATE_IDLE:
				myTextView1.setTextColor(Color.RED);
				myTextView1.setText("无任何状态");
				break;
			/* 接起电话时 */
			case TelephonyManager.CALL_STATE_OFFHOOK:
				myTextView1.setTextColor(Color.BLUE);
				myTextView1.setText("接起电话时");
				break;
			/* 电话进来时 */
			case TelephonyManager.CALL_STATE_RINGING:
				getContactPeople(incomingNumber);
				break;
			default:
				break;
			}
			super.onCallStateChanged(state, incomingNumber);
		}
	}

	private void getContactPeople(String incomingNumber) {
		myTextView1.setTextColor(Color.BLUE);
		ContentResolver contentResolver = getContentResolver();
		Cursor cursor = null;

		/* cursor里要放的字段名称 */
		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };

		/* 用来电电话号码查找该联系人 */
		cursor = contentResolver.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
				ContactsContract.CommonDataKinds.Phone.NUMBER + "=?",
				new String[] { incomingNumber }, "");

		/* 找不到联系人 */
		if (cursor.getCount() == 0) {
			myTextView1.setText("未知联系人:" + incomingNumber);
		} else if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			/* projection这个数组里 */
			String name = cursor.getString(1);
			myTextView1.setText(name + ":" + incomingNumber);
		}

	}
 


 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值