androidandroid-studiotelephonyincoming-call

perfectly blocking incoming calls in android


I want to block all incoming calls but get notified. For this I'm implementing this code:

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

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

But sometimes it does not work perfectly, I mean sometimes it does not response instantly, so the phone starts ringing for a very short time and then "telephonyService.endCall()" ends the call. I want to block the call instantly without providing time for ringing. Is it possible?


Solution

  • For my solution, you reject call too late. You can listen callstate like this https://stackoverflow.com/a/15564021/6000796 and https://stackoverflow.com/a/33390453/6000796. On the first ring is CallAudioManager.java receive oncallstatechanged and call state is Ring, so you can receive this event, reject call.

    case "RINGING":
                    Log.d(TAG, "State : Ringing, incoming_number : " + incoming_number);
                if((previus_state.equals("IDLE")) || (previus_state.equals("FIRST_CALL_RINGING"))){
                        current_state ="FIRST_CALL_RINGING";
                    }