ITeye博客

监听电话状态

zhangle2612 · 2010-10-22 17:16 · Android · 移动开发 · Markdown

监听手机的通话状态,是空闲还是正在通话中: public class PhoneStateListenerActivity extends Activity {

private TextView mTextView;


protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	
	setContentView(R.layout.phone_state_listener);
	
	Log.i("Lowry","==============activity on create");
	mTextView = (TextView) findViewById(R.id.phont_state_textView);
	
	ExPhoneCallListener exp = new ExPhoneCallListener(); 
	
	TelephonyManager tpm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
	
	tpm.listen(exp, PhoneStateListener.LISTEN_CALL_STATE);
	
	Log.i("Lowry","==============activity on create2");
}


public class ExPhoneCallListener extends PhoneStateListener {

	@Override
	public void onCallStateChanged(int state, String incomingNumber) {
		Log.i("Lowry","==============Call stata changed----"+state+"-----"+incomingNumber);
		switch (state) {
		case TelephonyManager.CALL_STATE_IDLE:
		
			mTextView.setText("空闲");
			break;
		case TelephonyManager.CALL_STATE_OFFHOOK:
		
			mTextView.setText("接起电话");
			break;
		case TelephonyManager.CALL_STATE_RINGING:
			getContactPeople(incomingNumber);
			break;
		default:
			break;
		}
		
		super.onCallStateChanged(state, incomingNumber);
		
		
	}
	
	
}


private void getContactPeople(String incomingNumber){
	mTextView.setTextColor(R.drawable.white);
	ContentResolver contentResolver = getContentResolver();
	Cursor cursor = null;
	String projection = new String{Contacts.People._ID,Contacts.People.NAME,Contacts.People.NUMBER};
	
	cursor = contentResolver.query(Contacts.People.CONTENT_URI,
			projection, Contacts.People.NUMBER+"=?", new String{incomingNumber}, 
			Contacts.People.DEFAULT_SORT_ORDER);
	
	Log.i("Lowry", "++++++++++++++++++++"+cursor.getCount());
	
	if(cursor.getCount()==0){
		mTextView.setText("Unknown Number:"+incomingNumber);
		
	}
	else if(cursor.getCount()>0){
		cursor.moveToFirst();
		String name = cursor.getString(1);
		mTextView.setText(name+"====="+incomingNumber);
	}
	
}

}

通过setSystemService()取得TelePhonyManager对象,再向TelephonyManager对象注册PhoneCallListener,注册时,传入PhoneCallListener类以及要倾听的事件名称,本应用所聆听的是电话状态,所以聆听事件要带入PhoneStateListener.LISTEN_CALL_STATE 得到电话状态并在mTextView中做显示,可以直观的看到当前的电话状态。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。