Android实现简单拨打电话功能

手机打电话是最常用的功能了,再Android手机开发当中打电话的功能是怎样实现的呢?我来看下简单的拨打电话的代码实例:

   步骤一::新建一个Android工程,命名随意.

 步骤二:设计布局文件,打开activity_main.xml把内容修改如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.wainapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.wainapp.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>

    <uses-permission android:name="android.permission.CALL_PHONE">

  </uses-permission>
    
</manifest>

 在上面的文件中,开放了拨出电话的权限:

<uses-permission android:name="android.permission.CALL_PHONE">

  </uses-permission>

步骤三:写主程序:

package com.example.wainapp;

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

public class MainActivity extends Activity {
	private Button bt;
	private EditText et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_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);

				}else{//否则Toast提示一下
					Toast.makeText(MainActivity.this, "不能输入为空", Toast.LENGTH_LONG);
			}

			}
			
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

相关推荐