如何在Android的编程拒接来电如何在、Android

2023-09-13 00:55:54 作者:℡昔年、作别旧梦。

在我的应用程序,我会保持一个联系人列表。

In my app I will maintain a list of contacts.

从列表中的联系人的任何通话将被丢弃。他们将在未接来电显示,但手机不会响。

Any calls from contacts in the list will be dropped. They will show under missed calls but the phone will not ring.

推荐答案

首先,创建这个接口:

  public interface ITelephony {

        boolean endCall();

        void answerRingingCall();

        void silenceRinger();

  }

然后建立这个类,扩展的BroadcastReceiver

Then Create this class that extends 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();
       }
}

这只会阻止单个联系号码,但你明白了吧。

This will only block that single phonenumber, but you get the point.

在你的清单中补充一点:

In your manifest add this:

<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" />