`

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);
		}

	}
 


 

 

  • 大小: 11.8 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics