Sunday, August 13, 2017

android - Call phone number programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    android:background="#5ca653"
    >
    <Button
        android:id="@+id/btn_do_task"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Make Phone Call"
        />
</LinearLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private LinearLayout mRootLayout;
    private Button mBtnDoTask;

    private static final int MY_PERMISSION_REQUEST_CODE = 123;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from xml layout
        mRootLayout = findViewById(R.id.root_layout);
        mBtnDoTask = findViewById(R.id.btn_do_task);

        // Set a click listener for the button
        mBtnDoTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    checkPermission();
                }else {
                    CallContact();
                }
            }
        });
    }

    // Custom method to call a phone number programmatically using dialer app
    protected void CallContact(){
        /*
            Intent
                An intent is an abstract description of an operation to be performed. It can be
                used with startActivity to launch an Activity, broadcastIntent to send it to any
                interested BroadcastReceiver components, and startService(Intent) or
                bindService(Intent, ServiceConnection, int) to communicate with a background Service.

                An Intent provides a facility for performing late runtime binding between the code
                in different applications. Its most significant use is in the launching of
                activities, where it can be thought of as the glue between activities.
                It is basically a passive data structure holding an abstract description
                of an action to be performed.
        */
        /*
            String ACTION_CALL
                Activity Action: Perform a call to someone specified by the data.

                Input: If nothing, an empty dialer is started; else getData() is URI of a phone
                number to be dialed or a tel: URI of an explicit phone number.

                Output: nothing.

                Note: there will be restrictions on which applications can initiate a
                call; most applications should use the ACTION_DIAL.

                Note: this Intent cannot be used to call emergency numbers. Applications can
                dial emergency numbers using ACTION_DIAL, however.

                Note: if you app targets M and above and declares as using the
                CALL_PHONE permission which is not granted, then attempting to use this
                action will result in a SecurityException.

                Constant Value: "android.intent.action.CALL"
        */
        // Initialize an intent to make phone call using dialer app
        // It open the dialer app and make call to the given phone number automatically
        Intent intent = new Intent(Intent.ACTION_CALL);
        // Send phone number to intent as data
        intent.setData(Uri.parse("tel:" + "+880XXXXXXXXXXXX"));
        // Start the dialer app activity to make phone call
        startActivity(intent);

    }

    protected void checkPermission(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if(checkSelfPermission(Manifest.permission.CALL_PHONE)!= PackageManager.PERMISSION_GRANTED){
                if(shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE)){
                    // show an alert dialog
                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setMessage("Call Phone permission is required.");
                    builder.setTitle("Please grant permission");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ActivityCompat.requestPermissions(
                                    mActivity,
                                    new String[]{Manifest.permission.CALL_PHONE},
                                    MY_PERMISSION_REQUEST_CODE
                            );
                        }
                    });
                    builder.setNeutralButton("Cancel",null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }else {
                    // Request permission
                    ActivityCompat.requestPermissions(
                            mActivity,
                            new String[]{Manifest.permission.CALL_PHONE},
                            MY_PERMISSION_REQUEST_CODE
                    );
                }
            }else {
                // Permission already granted
                CallContact();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        switch(requestCode){
            case MY_PERMISSION_REQUEST_CODE:{
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    // Permission granted
                    CallContact();
                }else {
                    // Permission denied
                }
            }
        }
    }
}
AndroidManifest.xml [Permission]

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