在android(Marshmallow)中自动接听电话

时间:2017-05-16 11:48:56

标签: android

在我的项目中,我必须在棉花糖中自动接听电话。我提到互联网,但我还没有得到解决方案

以下是代码:

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

清单中的权限:

我也为marshmallow做过运行时许可。

我在哪里做错了?

2 个答案:

答案 0 :(得分:0)

首先,在做任何事情之前,请求call_phone的许可。为了安全起见。 (不要忘记将此权限放入清单中)

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

和用于检查的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);
        }

答案 1 :(得分:0)

您需要使用电话管理员收听来电,您可以从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);