开启关闭去电监听

2019-04-14 19:40发布

由于TelephonyManager类电话监听状态里没有对应的去电状态 public static final int CALL_STATE_IDLE = 0; public static final int CALL_STATE_RINGING = 1; public static final int CALL_STATE_OFFHOOK = 2; 所有需要通过自定义广播类来实现,然后再在服务类里调用。
去电监听广播类 package com.greysun.he.bin; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsManager; import android.util.Log; public class BRListenOut extends BroadcastReceiver { private static boolean isSend = false; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); //呼出电话 if(action.equals(Intent.ACTION_NEW_OUTGOING_CALL) && !isSend){ String outPhoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); switch(outPhoneNumber.length()){ case 11:{ System.out.println("Listen-out Long Number"); }break; default:{ System.out.println("Listen-out Short Number"); }break; } isSend = true; //this.setResultData(null);这里可以更改呼出电话号码。如果设置为null,电话就永远不会播出了. }else{ isSend = false; } } } 服务类 package com.greysun.he.service; import com.greysun.he.bin.BRListenOut; import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; public class ListenOut extends Service{ private BRListenOut brListenOut; @Override public int onStartCommand(Intent intent,int flags,int startId){ System.out.println("开启去电监听"); brListenOut = new BRListenOut(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL); registerReceiver(brListenOut,intentFilter); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onDestroy() { //注销去电监听广播 unregisterReceiver(brListenOut); System.out.println("关闭去电监听"); stopSelf(); } } 添加相应的权限 <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" /> <application> <service android:name=".service.ListenOut"/> application> 再像普通服务类一样调用即可 private Intent listenOut; /** * [开启|关闭]服务 * @param isStart 开启或关闭 * @param intent 服务 */ private void startOrStopService(boolean isStart,Intent intent){ try{ if(isStart) startService(intent); else stopService(intent); }catch(Exception e){ Log.w("[启动|关闭]-服务", e.getMessage()); } } /** * 绑定服务文件 */ private void createIntent(){ listenOut = new Intent(); listenOut.setClass(this, ListenOut.class); }