Monday, June 6, 2016

How to make a phone call in Android

1 Android Layout Files

Simpel layout file, to display a button.
File : res/layout/main.xml
Markup
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonCall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="call 0377778888" />
            
</LinearLayout>
2. ActivityUse below code snippet to make a phone call in Android.
Java
 Intent callIntent = new Intent(Intent.ACTION_CALL);
 callIntent.setData(Uri.parse("tel:0377778888"));
 startActivity(callIntent);
File : MainActivity.java – When the button is call, make a phone to 0377778888.
Java
package com.mkyong.android;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

 private Button button;

 public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  button = (Button) findViewById(R.id.buttonCall);

  // add button listener
  button.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View arg0) {

    Intent callIntent = new Intent(Intent.ACTION_CALL);
    callIntent.setData(Uri.parse("tel:0377778888"));
    startActivity(callIntent);

   }

  });

 }

}
3 Android ManifestTo make a phone call, Android need CALL_PHONE permission.
Markup
<uses-permission android:name="android.permission.CALL_PHONE" />
File : AndroidManifest.xml
Markup
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mkyong.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

 <uses-permission android:name="android.permission.CALL_PHONE" />
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
  
        <activity
            android:label="@string/app_name"
            android:name=".MainActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

No comments:

Post a Comment