Android基础-拨打电话程序
1. 布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello_world" /> <EditText android:id="@+id/phoneNumber" android:layout_width="fill_parent" android:layout_height="wrap_content" android:phoneNumber="true" /> <Button android:id="@+id/BtnCall" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/call" /> </LinearLayout>
2. 拨打电话的程序
package com.example.phonecalldemo; 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 MainActivity extends Activity { public Button call; public EditText phoneNumber; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); call = (Button) findViewById(R.id.BtnCall); phoneNumber = (EditText)findViewById(R.id.phoneNumber); call.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub String hm = phoneNumber.getText().toString(); if(hm.trim().length()!=0) { Intent intent = new Intent("android.intent.action.CALL",Uri.parse("tel:"+hm)); //start startActivity(intent); }else{ Toast.makeText(MainActivity.this, "电话号码不能为空", Toast.LENGTH_LONG).show(); } } }); } }
3. AndroidManifest.xml文件,申请打电话的权限。
<!-- 添加拨出电话的权限 --> <uses-permission android:name="android.permission.CALL_PHONE"> </uses-permission>
运行效果如下: