现在的位置: 首页 > 综合 > 正文

监听手机状态–PhoneStateListener

2013年11月29日 ⁄ 综合 ⁄ 共 3653字 ⁄ 字号 评论关闭

 

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

自定义的监听器:

  1. class MyPhoneStateListener extends PhoneStateListener  
  2. {  
  3.     Context context;  
  4.     public MyPhoneStateListener(Context con)  
  5.     {  
  6.          context = con;  
  7.     }  
  8.       
  9.     public void onCallForwardingIndicatorChanged(boolean cfi)   
  10.     {  
  11.           
  12.     }  
  13.       
  14.     public void onCallStateChanged(int state, String incomingNumber)   
  15.     {  
  16.         switch(state)  
  17.         {  
  18.         case TelephonyManager.CALL_STATE_IDLE:  
  19.             Toast.makeText(context, "call not answer", Toast.LENGTH_LONG).show();  
  20.             break;  
  21.               
  22.         case TelephonyManager.CALL_STATE_RINGING:  
  23.             Toast.makeText(context, "incoming", Toast.LENGTH_LONG).show();  
  24.               
  25.             break;  
  26.               
  27.         case TelephonyManager.CALL_STATE_OFFHOOK:  
  28.             Toast.makeText(context, "in a call", Toast.LENGTH_LONG).show();  
  29.             break;  
  30.         }  
  31.     }  
  32.       
  33.     public void onCellLocationChanged(CellLocation location) {}  
  34.       
  35.     public void onDataActivity(int direction) {}  
  36.       
  37.     public void onDataConnectionStateChanged(int state) {}  
  38.       
  39.     public void onMessageWaitingIndicatorChanged(boolean mwi) {}  
  40.       
  41.     public void onServiceStateChanged(ServiceState serviceState) {}  
  42.       
  43.     public void onSignalStrengthChanged(int asu) {}  
  44. }  


注册自己的监听器:

  1. String srvcName = Context.TELEPHONY_SERVICE;  
  2.         TelephonyManager telephonyManager = (TelephonyManager)getSystemService(srvcName);  
  3.           
  4.         MyPhoneStateListener phoneStateListener = new MyPhoneStateListener(this);  
  5.         telephonyManager.listen(phoneStateListener,  
  6.                 PhoneStateListener.LISTEN_CALL_FORWARDING_INDICATOR |  
  7.                 PhoneStateListener.LISTEN_CALL_STATE |  
  8.                 PhoneStateListener.LISTEN_CELL_LOCATION |  
  9.                 PhoneStateListener.LISTEN_DATA_ACTIVITY |  
  10.                 PhoneStateListener.LISTEN_DATA_CONNECTION_STATE |  
  11.                 PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR |  
  12.                 PhoneStateListener.LISTEN_SERVICE_STATE |  
  13.                 PhoneStateListener.LISTEN_SIGNAL_STRENGTH);  

抱歉!评论已关闭.