思路:APP通过Intent来实现拨号功能。
一、首先在manifest下的AndroidManifest.xml文件中进行授权:
<uses-permission android:name="android.permission.CALL_PHONE" />
演示时发现仅此操作仍不能运行,界面不能显示,报错提示如下:
错误提示:java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.CALL dat=tel:xxxxxx cmp=com.android.server.telecom/.components.UserCallActivity } from ProcessRecord{5f1635b 10632:com.example.myapp2/u0a88} (pid=10632, uid=10088) with revoked permission android.permission.CALL_PHONE
这是因为需要在虚拟机中的setting中进行设置,真机演示的方法也类似。方法如下:
1)选择设置
2)找到Apps
3) 选择App info
4) 找到我的APP
5) 选择Permissions
6)打开拨号权限
二、演示方式一运行如下,点击拨打电话即把默认的号进行拨号:
三、关键代码之MainActivity
在文件中先声明Intent对象,再使用startActivity方法启动,具体如下:
package com.example.myapp2;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.os.Bundle;
import android.widget.EditText;
//AppCompatActivity
public class MainActivity extends Activity {
private Button button;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new buttonListener());
//放在此可实现运行APP即拨号
//Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+number));
//startActivity(intent);
}
class buttonListener implements OnClickListener{
@Override
public void onClick(View v){
editText = (EditText) findViewById(R.id.edittext);
String number = editText.getText().toString();
//方式一 是直接进行呼叫的方式
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+number));
//方式二 不直接进行呼叫,而是启动 Android 系统的拨号应用程序,由用户进行拨号。不
//要任何权限的设置
//Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+number));
startActivity(intent);
}
}
}
四、关键代码之activity_main.xml
文件内容如下,当然也可把号码放进strings.xml文件里,然后通过android:text="@string/tel_x"的方式填写号码。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="555666"
android:layout_marginLeft="40dp"
android:layout_marginTop="30dp"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginTop="40dp"
android:text="拨打电话" />
</LinearLayout>