当有人接听我们的电话时如何创建Toast

时间:2019-01-30 06:56:55

标签: java android

这是我的清单文件:

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

这是我的Java代码:

  switch (state){
            case TelephonyManager.CALL_STATE_RINGING:
                Toast.makeText(getApplicationContext(),"Ringing....",Toast.LENGTH_LONG).show();
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                Toast.makeText(getApplicationContext(),"onCall....",Toast.LENGTH_LONG).show();
                onCall= true;
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                if(onCall == true){
                    Toast.makeText(getApplicationContext(),"Restarting app",Toast.LENGTH_LONG).show();
                    //restarting application
                    Intent restart = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
                    restart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(restart);
                    onCall= false;
                }
                break;
            default:
                break;
        }

如何识别有人接听我们的电话以及如何接听电话?

1 个答案:

答案 0 :(得分:0)

您需要创建广播接收器以检测呼叫。

 public class PhoneStatReceiver extends BroadcastReceiver{
    @Override

    public void onReceive(Context context, Intent intent) {
        TelephonyManager tm =  (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);

        if(tm.getCallState()==TelephonyManager.CALL_STATE_OFFHOOK)
        {
            Toast.makeText(context,"Accepted",Toast.LENGTH_SHORT).show();
        }

    } }