Android基础——拨打电话

来源:互联网 发布:js文件怎么写 编辑:程序博客网 时间:2024/05/21 15:44

    本例将通过Intent(意图)调用系统拨号器实现拨打电话的功能。

1.布局文件

    android:hint="@string/phoneHint":表示隐藏的提示信息

    android:inputType="phone":表示输入类型为电话号码

<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=".MainActivity" >    <EditText        android:id="@+id/etPhone"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="@string/phoneHint"        android:ems="10"        android:inputType="phone" >        <requestFocus />    </EditText>    <Button        android:id="@+id/btnCall"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignLeft="@+id/etPhone"        android:layout_below="@+id/etPhone"        android:text="@string/call" /></RelativeLayout>

2.MainActivity

    设置按钮监听事件

intent.setData(Uri.parse("tel:" + phoneNumber)):设置要传递的数据,Uri类型,电话号码要加前缀“tel:”

intent.setAction(Intent.ACTION_CALL):设置Intent的动作为打电话

    在Windows系统中也有类似的功能,在命令行输入:start http://www.baidu.com,将用默认浏览器打开。



public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);((Button)findViewById(R.id.btnCall)).setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String phoneNumber = ((EditText) findViewById(R.id.etPhone)).getText().toString();//意图:想干什么事Intent intent = new Intent();intent.setAction(Intent.ACTION_CALL);//url:统一资源定位符//uri:统一资源标示符(更广)intent.setData(Uri.parse("tel:" + phoneNumber));//开启系统拨号器startActivity(intent);}});}}

3.报错,没有权限

    运行时发现错误,到LogCat中一看,发现如下错误:

03-22 16:58:47.263: E/AndroidRuntime(26347): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxx cmp=com.android.phone/.OutgoingCallBroadcaster } from ProcessRecord{41eec660 26347:com.example.call/u0a77} (pid=26347, uid=10077) requires android.permission.CALL_PHONE

    在AndroidManifest.xml中添加android.permission.CALL_PHONE权限即可

    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="19" />    <uses-permission android:name="android.permission.CALL_PHONE" android:maxSdkVersion="19"/>        <application

运行效果:

                                               


2 0
原创粉丝点击