在 Android 中要進行電話撥號,可以透過設定 ACTION_CALL 或 ACTION_DIAL 來達成。兩者的差異在於:
(1)ACTION_CALL:直接撥出號碼;
(2)ACTION_DIAL:開啟撥號程式,由使用者手動按下通話鍵。
一、設計介面
1. MainActivity 版面配置
開啟 res/layout/activity_main.xml,加入號碼輸入框與呼叫按鈕:
[html] view plain copy
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/tel"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="請輸入電話號碼:" />
-
- <EditText
- android:id="@+id/telphone"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:ems="10" >
-
- <requestFocus />
- </EditText>
-
- <Button
- android:id="@+id/call"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="呼叫" />
-
- </LinearLayout>
二、程式碼實作
開啟 src/com.genwoxue.intenttel/MainActivity.java,加入以下程式碼:
[java] view plain copy
- package com.genwoxue.intenttel;
-
-
- import android.net.Uri;
- import android.os.Bundle;
- import android.app.Activity;
- import android.content.Intent;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.TextView;
-
- public class MainActivity extends Activity {
-
- private TextView tvTelphone=null;
- private Button btnCall=null;
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- tvTelphone=(TextView)super.findViewById(R.id.telphone);
- btnCall=(Button)super.findViewById(R.id.call);
- btnCall.setOnClickListener(new OnClickListener(){
- public void onClick(View v)
- {
- String Telphone=tvTelphone.getText().toString();
- Uri uri=Uri.parse("tel:"+Telphone);
- Intent intent=new Intent();
- intent.setAction(Intent.ACTION_CALL);
- intent.setData(uri);
- MainActivity.this.startActivity(intent);
- }
- });
- }
-
- }
三、設定檔
開啟 AndroidManifest.xml,加入撥號權限:
[html] view plain copy
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="https://schemas.android.com/apk/res/android"
- package="com.genwoxue.intenttel"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="15" />
-
- <span style="color:#ff0000;"><strong><uses-permission android:name="android.permission.CALL_PHONE"/></strong>
- </span>
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.genwoxue.intenttel.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-
- </manifest>
四、執行結果