Search code examples
androidphone-call

Make a call on click but with confirmation


I want to click on a TextView and make a call to a telephone number but not directly, with the confirmation of the user. My code is this but it makes the call directly when I click

txt_ocho.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        try {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:" + txt_ocho.getText().toString().trim()));
            startActivity(callIntent);
        } catch (ActivityNotFoundException activityException) {
            Log.d("Calling a Phone Number", "Call failed" + activityException);
        }
    }
});

Can Somebody help me? Thank you


Solution

  • Well, in your onClick block, display an alertDialog with 2 buttons (cancel and confirm).

    txt_ocho.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Confirm call")
            .setMessage("Are you sure you want to make the phone call?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                     Intent callIntent = new Intent(Intent.ACTION_CALL);
                     callIntent.setData(Uri.parse("tel:" + txt_ocho.getText().toString().trim()));
                     startActivity(callIntent);
                } catch (ActivityNotFoundException activityException) {
                     Log.d("Calling a Phone Number", "Call failed" + activityException);
                }   
            }
    
        })
        .setNegativeButton("Cancel", null)
        .show();
     }    
    });