package org.zrf.demo;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;
import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.os.Binder; import android.os.IBinder; import android.os.RemoteException; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager;
import com.android.internal.telephony.ITelephony;
public class PhoneService extends Service { private TelephonyManager telephony = null; // 电话管理器 private AudioManager audio = null ; // 音频管理 private String phoneNumber = null ; // 要过滤的电话 private IBinder myBinder = new BinderImpl() ; // 定义IBinder class BinderImpl extends Binder implements IService { @Override public String getInterfaceDescriptor() { // 取得接口描述信息 return "过滤电话“" + PhoneService.this.phoneNumber + "”设置成功!"; // 返回Service类的名称 } } @Override public IBinder onBind(Intent intent) { this.phoneNumber = intent.getStringExtra("phonenumber"); // 取得电话号码 this.telephony = (TelephonyManager) super .getSystemService(Context.TELEPHONY_SERVICE); // 取得服务 this.audio = (AudioManager) super .getSystemService(Context.AUDIO_SERVICE); // 取得服务 this.telephony.listen(new PhoneStateListenerImpl(), PhoneStateListener.LISTEN_CALL_STATE); // 设置电话监听 return this.myBinder; // 返回IBinder对象 }
private class PhoneStateListenerImpl extends PhoneStateListener { // 电话监听 @Override public void onCallStateChanged(int state, String incomingNumber) { // 改变呼叫状态 switch (state) { // 判断状态 case TelephonyManager.CALL_STATE_IDLE: // 没有拨入或拨出 PhoneService.this.audio .setRingerMode(AudioManager.RINGER_MODE_NORMAL);// 正常响铃 break; case TelephonyManager.CALL_STATE_RINGING: // 有电话进入 if (incomingNumber.equals(PhoneService.this.phoneNumber)) { // 为过滤号码 ITelephony iTelephony=getITelephony(); if(iTelephony!=null){ try { iTelephony.endCall();//挂断电话 } catch (RemoteException e) { e.printStackTrace(); } } } break; } } } private ITelephony getITelephony(){ ITelephony iTelephony=null; Class<TelephonyManager>cls=TelephonyManager.class; Method getITelephonyMethod=null; try { getITelephonyMethod=cls.getDeclaredMethod("getITelephony"); getITelephonyMethod.setAccessible(true);//取消封装 } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } try { iTelephony=(ITelephony)getITelephonyMethod.invoke(this.telephony); return iTelephony; } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return iTelephony; } }
|