Percy

如何在Android中以编程方式拒绝通话

android

在我的应用程序中,我将维护一个联系人列表。

列表中联系人的所有呼叫都将被挂断。他们会在未接来电下显示,但电话不会响铃。


阅读 412

收藏
2020-12-08

共1个答案

小编典典

首先创建此接口:

  public interface ITelephony {

        boolean endCall();

        void answerRingingCall();

        void silenceRinger();

  }

然后创建扩展BroadcastReceiver的此类

public class IncomingCallReceiver extends BroadcastReceiver {
    private ITelephony telephonyService;
    private String blacklistednumber = "+458664455";

    @Override
    public void onReceive(Context context, Intent intent) {

       TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
       try {
         Class c = Class.forName(tm.getClass().getName());
         Method m = c.getDeclaredMethod("getITelephony");
         m.setAccessible(true);
         ITelephony telephonyService = (ITelephony) m.invoke(tm);
         Bundle bundle = intent.getExtras();
         String phoneNumber = bundle.getString("incoming_number");
         Log.e("INCOMING", phoneNumber);
         if ((phoneNumber != null) && phoneNumber.equals(blacklistednumber)) { 
            telephonyService.silenceRinger();
            telephonyService.endCall();
            Log.e("HANG UP", phoneNumber);
         }

       } catch (Exception e) {
         e.printStackTrace();
       }
}

这只会阻止该单个电话号码,但是您明白了。

在清单中添加以下内容:

<receiver android:name=".IncomingCallReceiver">
    <intent-filter android:priority="999">
        <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
2020-12-08