android 使用意图(Intent)实现一键拨号实例

来源:互联网 发布:子域名怎么看 编辑:程序博客网 时间:2024/05/16 04:37

本文打算实现具有一个一键拨号功能的 APP

1.布局文件activity_main.xml

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="cn.sehzh.intenttester.MainActivity" >    <Button        android:id="@+id/mCallButton"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:layout_marginTop="26dp"        android:text="Call" /></RelativeLayout>
2.MainActivity

package cn.sehzh.intenttester;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 mBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mBtn = (Button) findViewById(R.id.mCallButton);mBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {dialPhoneNumber("110");}});}private void dialPhoneNumber(String phoneNumber) {Intent intent = new Intent(Intent.ACTION_CALL);intent.setData(Uri.parse("tel:" + phoneNumber));if (intent.resolveActivity(getPackageManager()) != null) {startActivity(intent);}}}
3.运行效果



4.注意

Intent intent = new Intent(Intent.ACTION_CALL);
中的ACTION_CALL如果写为ACTION_DIAL则会跳出带键盘拨号界面,而不是直接拨打电话;

需要以下权限

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





1 0
原创粉丝点击