Skip to content

Instantly share code, notes, and snippets.

@flipmedia
Created March 31, 2017 09:24
Show Gist options
  • Save flipmedia/91b0b6c440efa210f0a7e9aa78a60ef1 to your computer and use it in GitHub Desktop.
Save flipmedia/91b0b6c440efa210f0a7e9aa78a60ef1 to your computer and use it in GitHub Desktop.
package net.learn2develop.autocalls;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.widget.Toast;
import java.lang.reflect.Method;
import static android.content.Context.TELEPHONY_SERVICE;
public class IncomingCallsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals("android.intent.action.PHONE_STATE")) return;
String extraState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (extraState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String incomingNumber =
intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(context, incomingNumber,
Toast.LENGTH_LONG).show();
answerPhoneHeadsethook(context, intent);
}
return;
}
private void answerPhoneHeadsethook(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
try {
context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
}
catch (Exception e) {
}
Intent headSetUnPluggedintent = new Intent(Intent.ACTION_HEADSET_PLUG);
headSetUnPluggedintent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
headSetUnPluggedintent.putExtra("state", 1); // 0 = unplugged 1 = Headset with microphone 2 = Headset without microphone
headSetUnPluggedintent.putExtra("name", "Headset");
// TODO: Should we require a permission?
try {
context.sendOrderedBroadcast(headSetUnPluggedintent, null);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment