监听手机状态--PhoneStateListener

通过向TelephonyManager注册一个listener,就可以监听手机的一些状态的变化。

自定义的监听器:

class MyPhoneStateListener extends PhoneStateListener
{
	Context context;
	public MyPhoneStateListener(Context con)
	{
		 context = con;
	}
	
	public void onCallForwardingIndicatorChanged(boolean cfi) 
	{
		
	}
	
	public void onCallStateChanged(int state, String incomingNumber) 
	{
		switch(state)
		{
		case TelephonyManager.CALL_STATE_IDLE:
			Toast.makeText(context, "call not answer", Toast.LENGTH_LONG).show();
			break;
			
		case TelephonyManager.CALL_STATE_RINGING:
			Toast.makeText(context, "incoming", Toast.LENGTH_LONG).show();
			
			break;
			
		case TelephonyManager.CALL_STATE_OFFHOOK:
			Toast.makeText(context, "in a call", Toast.LENGTH_LONG).show();
			break;
		}
	}
	
	public void onCellLocationChanged(CellLocation location) {}
	
	public void onDataActivity(int direction) {}
	
	public void onDataConnectionStateChanged(int state) {}
	
	public void onMessageWaitingIndicatorChanged(boolean mwi) {}
	
	public void onServiceStateChanged(ServiceState serviceState) {}
	
	public void onSignalStrengthChanged(int asu) {}
}

注册自己的监听器:

String srvcName = Context.TELEPHONY_SERVICE;
        TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName);
        
        MyPhoneStateListener phoneStateListener = new MyPhoneStateListener(this);
        telephonyManager.listen(phoneStateListener,
        		PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR |
        		PhoneStateListener.LISTEN_CALL_STATE |
        		PhoneStateListener.LISTEN_CELL_LOCATION |
        		PhoneStateListener.LISTEN_DATA_ACTIVITY |
        		PhoneStateListener.LISTEN_DATA_CONNECTION_STATE |
        		PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR |
        		PhoneStateListener.LISTEN_SERVICE_STATE |
        		PhoneStateListener.LISTEN_SIGNAL_STRENGTH);



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值