眾所周知,對於一個手機,能撥打到電話是其最重要也是最常用的一個功能.而在Android裡是怎麼樣實現撥打到電話的程式呢?我在這裡寫了一個簡單的撥打到電話的Demo,供大家參考.一共分為5個步驟.
Step 1:建立一個Android工程,命名為phoneCallDemo.
Step 2:設計程式的介面,開啟main.xml把內容修改如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Please input the phoneNumer:"
/>
<EditText
android:id="@+id/et1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:phoneNumber="true"
/>
<Button
android:id="@+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Call Phone"
/>
</LinearLayout>
Step 3:增加撥打到電話的許可權,開啟AndroidManifest.xml,修改代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".PhoneCallDemo"
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>
<uses-sdk android:minSdkVersion="3" />
<!-- 添加已撥電話的許可權 -->
<uses-permission android:name="android.permission.CALL_PHONE">
</uses-permission>
</manifest>
Step 4:主程式phoneCallDemo.java代碼如下:
package com.android.test;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class PhoneCallDemo extends Activity {
private Button bt;
private EditText et;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//取得資源
bt = (Button)findViewById(R.id.bt1);
et = (EditText)findViewById(R.id.et1);
//增加事件響應
bt.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
//取得輸入的電話號碼串
String inputStr = et.getText().toString();
//如果輸入不為空白建立打電話的Intent
if(inputStr.trim().length()!=0)
{
Intent phoneIntent = new Intent("android.intent.action.CALL",
Uri.parse("tel:" + inputStr));
//啟動
startActivity(phoneIntent);
}
//否則Toast提示一下
else{
Toast.makeText(PhoneCallDemo.this, "不能輸入為空白", Toast.LENGTH_LONG).show();
}
}
});
}
}
Step 5:運行代碼,效果如下: