In this example we will see how to make a phone call using an Intent object in the android to invoke the default phone calls feature. In order to track changes in some telephony states on the device, we can use PhoneStateListener and TelephonyManager classes.
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:"+number));
startActivity(i);
// Below permission is required to make calls in android
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
// MainActivity.java
package com.techstackguru.phone;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
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.EditText;
public class MainActivity extends AppCompatActivity {
EditText getNo;
Button callNo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getNo=(EditText)findViewById(R.id.mobileNo);
callNo=(Button)findViewById(R.id.btCall);
callNo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number=getNo.getText().toString();
Intent i = new Intent(Intent.ACTION_CALL);
i.setData(Uri.parse("tel:"+number));
if (ActivityCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(i);
}
});
}
}
In activity_main.xml file we are adding EditText and Button to enter phone number and to make call.
// activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<EditText
android:id="@+id/mobileNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:hint="Enter Number"
android:inputType="phone"
android:maxLength="10" />
<Button
android:id="@+id/btCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:p="Make Call" />
</LinearLayout>
<uses-permission android:name="android.permission.CALL_PHONE"/>