Requirement:
Block incoming and out going calls.
Steps:
Register a broadcast receiver to monitor calls.
In AndroidManifest.xml file write:
<receiver android:name="MyPhoneReceiver">
<intent-filter android:priority="100">
<action android:name="android.intent.action.PHONE_STATE"/>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
Create a broadcast Receiver to catch the "call" related broadcast.
public class ProcessCall extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Create object of Telephony Manager class.
TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//Assign a phone state listener.
CustomPhoneStateListener customPhoneListener = new CustomPhoneStateListener (context);
telephony.listen(customPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
Create a custom phone state listener.
import java.lang.reflect.Method;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import com.CallLogApp.helper.BlockNumberHelper;
import com.CallLogApp.util.UDF;
import com.android.internal.telephony.ITelephony;
public class CustomPhoneStateListener extends PhoneStateListener {
Context context;
public CustomPhoneStateListener(Context context) {
super();
this.context = context;
}
@Override
public void onCallStateChanged(int state, String callingNumber)
{
super.onCallStateChanged(state, callingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//handle out going call
endCallIfBlocked(callingNumber);
break;
case TelephonyManager.CALL_STATE_RINGING:
//handle in coming call
endCallIfBlocked(callingNumber);
break;
default:
break;
}
}
private void endCallIfBlocked(String callingNumber) {
try {
// Java reflection to gain access to TelephonyManager's
// ITelephony getter
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
c = Class.forName(tm.getClass().getName());
Method m = c.getDeclaredMethod("getITelephony");
m.setAccessible(true);
com.android.internal.telephony.ITelephony telephonyService = (ITelephony) m.invoke(tm);
telephonyService = (ITelephony) m.invoke(tm);
//
telephonyService.silenceRinger();
telephonyService.endCall();
} catch (Exception e) {
e.printStackTrace();
}
}
}