Phone Call Example in Android

Phone Call Example in Android

In this tutorial we will learn how to implement phone call in an Android app with the help of Intent in Android Studio. We will hard code a number and while we press a call button in this example. In the next tutorial we will call from selecting from contacts list.

Example:
  • Create a new project in Android Studio and name it as PhoneCall.
  • In a activity_main.xml paste the following code.
File: activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context="hss_24.example.com.phonecall.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dp"
        android:gravity="center_horizontal"
        android:text="Android Lovers"
        android:textSize="20dp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_call"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call" />

</LinearLayout>
  • Now paste the following code in MainActivity.java. Here we are calling a hard coded number with the help of ACTON_DIAL.
File: MainActivity.java:

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button call;

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

        call = (Button) findViewById(R.id.btn_call);
        call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // set intent and call
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:1212121212"));
                startActivity(intent);
            }
        });

    }
}
  • Now run the App and enjoy the output.
Output:





Comments