本文實現的是一個簡單的電話監聽器,用Toast來提示電話來電的不同狀態;
看圖 :
主要代碼 :
package com.yin.telephony;<br />import android.app.Activity;<br />import android.os.Bundle;<br />import android.telephony.PhoneStateListener;<br />import android.telephony.TelephonyManager;<br />import android.util.Log;<br />import android.widget.Toast;<br />public class MainActivity extends Activity {<br />private static final String TAG = "com.yin.telephony";<br />TelephonyManager myManager;<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);</p><p> myManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);</p><p> myManager.listen(new myManagerListener(), PhoneStateListener.LISTEN_CALL_STATE);<br /> }</p><p> private class myManagerListener extends PhoneStateListener{<br />public void onCallStateChanged(int state, String incomingNumber) {<br />switch(state){<br />case TelephonyManager.CALL_STATE_IDLE :<br />Toast.makeText(getApplicationContext(), "電話中斷", Toast.LENGTH_LONG).show();<br />Log.e(TAG,"CALL_STATE_IDLE");<br />break;</p><p>case TelephonyManager.CALL_STATE_OFFHOOK :<br />Toast.makeText(getApplicationContext(), "電話掛起", Toast.LENGTH_LONG).show();<br />Log.e(TAG,"CALL_STATE_OFFHOOK");<br />break;<br />case TelephonyManager.CALL_STATE_RINGING :<br />Toast.makeText(getApplicationContext(), "來電號碼 :"+incomingNumber, Toast.LENGTH_LONG).show();<br />Log.e(TAG,"CALL_STATE_RINGING");<br />break;<br />default :<br />break;<br />}</p><p>super.onCallStateChanged(state, incomingNumber);<br />}</p><p> }<br />}
注意添加相應許可權 :
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>