简体   繁体   English

在Android(棉花糖)中自动接听电话

[英]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. 首先,在执行任何操作之前,请请求call_phone的许可。 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: 和用于检查的Java代码将如下所示:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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