监听电话状态的模板代码

package com.example.calling;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneStatusService extends Service {
   private TelephonyManager tm;
   private MyPhoneStatusListener  mPhoneStatusListener;
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }
   @Override
   public void onCreate() {
      super.onCreate();
      // 1. 获取手机管理器
      tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
      // 2. 设置监听
      mPhoneStatusListener = new MyPhoneStatusListener();
      tm.listen(mPhoneStatusListener, PhoneStateListener.LISTEN_CALL_STATE);
   }

   /**
    * 3. 用内部类实现监听
    * 手机状态监听
    */
   private class MyPhoneStatusListener extends PhoneStateListener {
      //当手机通话状态变化时,回调
      //state  :通话的3中状态
      //incomingNumber:来电号码
      @Override
      public void onCallStateChanged(int state, String incomingNumber) {
         super.onCallStateChanged(state, incomingNumber);
         System.out.println("来电号码:"+incomingNumber);      
         switch (state) {
            case TelephonyManager.CALL_STATE_IDLE://空闲
                System.out.println("空闲");
                break;
            case TelephonyManager.CALL_STATE_RINGING://响铃
                System.out.println("响铃");
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK://通话
                System.out.println("通话");
                break;
            default:
                break;
         }
      }
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      //4. 注销监听
      tm.listen(mPhoneStatusListener, PhoneStateListener.LISTEN_NONE);
   }
}

 

posted on 2017-02-19 16:35  LoaderMan  阅读(441)  评论(0编辑  收藏  举报

导航