Android中级篇之简单的来电监视器

本文实现的是一个简单的来电监视器,用Toast来提示电话来电的不同状态;

看图 :

Android中级篇之简单的来电监视器

主要代码 :

package com.yin.telephony;import android.app.Activity;import android.os.Bundle;import android.telephony.PhoneStateListener;import android.telephony.TelephonyManager;import android.util.Log;import android.widget.Toast;public class MainActivity extends Activity { private static final String TAG = "com.yin.telephony"; TelephonyManager myManager; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); myManager.listen(new myManagerListener(), PhoneStateListener.LISTEN_CALL_STATE); } private class myManagerListener extends PhoneStateListener{ public void onCallStateChanged(int state, String incomingNumber) { switch(state){ case TelephonyManager.CALL_STATE_IDLE : Toast.makeText(getApplicationContext(), "电话中断", Toast.LENGTH_LONG).show(); Log.e(TAG,"CALL_STATE_IDLE"); break; case TelephonyManager.CALL_STATE_OFFHOOK : Toast.makeText(getApplicationContext(), "电话挂起", Toast.LENGTH_LONG).show(); Log.e(TAG,"CALL_STATE_OFFHOOK"); break; case TelephonyManager.CALL_STATE_RINGING : Toast.makeText(getApplicationContext(), "来电号码 :"+incomingNumber, Toast.LENGTH_LONG).show(); Log.e(TAG,"CALL_STATE_RINGING"); break; default : break; } super.onCallStateChanged(state, incomingNumber); } }}

注意添加相应权限 :

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>