简体   繁体   中英

Answer the call automatically in android (Marshmallow)

In my project I have to receive the call automatically in marshmallow. I referred internet but still i haven't got the solution

Here is the code:

public void acceptCall() {
    Toast.makeText(context,"inside accept call",Toast.LENGTH_LONG).show();
    Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
    buttonUp.putExtra(Intent.EXTRA_KEY_EVENT,
            new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
    context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
}

Permission in manifest:

I also have done runtime permission for marshmallow.

Where am I doing it wrong?

First of all, make a request for permission of call_phone before doing any thing. To be in the safe side. (Don't forget to put this permission in manifest)

<uses-permission android:name="android.permission.CALL_PHONE" />

and java code for checking will be like this:

int checkPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.CALL_PHONE},
                    REQUEST_CALL_PHONE);
        } else {
            customDialog(CallChoosyActivity.this);
        }

you need to use telephone manager to listen for incoming calls, you can read more about it from here

    public void onReceive(final Context context, Intent intent) 
    {
        TelephonyManager telephonyManager = null;
        PhoneStateListener listener = new PhoneStateListener() 
        {
            public void onCallStateChanged(int state, String incomingNumber) 
            {
                switch (state) 
                {
                case TelephonyManager.CALL_STATE_IDLE:
               // call ended
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                  // call picked
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                   // call is ringing now
try {
telephonyManager.getClass().getMethod("answerRingingCall").invoke(telephonyManager);
} catch (Exception e) { 

}
                    break;
                }
            }
        };
        // Register the listener with the telephony manager
        telephonyManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM