Android实现拨打电话功能

添加权限:

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

实现:

package com.example.call_person;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_callOne;
    private Button btn_callTwo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        btn_callOne = (Button) findViewById(R.id.btn_callOne);
        btn_callTwo = (Button) findViewById(R.id.btn_callTwo);

        btn_callOne.setOnClickListener(this);
        btn_callTwo.setOnClickListener(this);
    }

    /**
     * 调用拨号界面
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 调用拨号功能
     * @param phone 电话号码
     */
    @SuppressLint("MissingPermission")
    private void call2(String phone) {
        Intent intent2=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+phone));
        startActivity(intent2);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_callOne:

                call("10086");

                break;
            case R.id.btn_callTwo:

                call2("10086");

                break;
        }
    }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.call_person.MainActivity">

    <Button
        android:id="@+id/btn_callOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="只调用拨号界面,不拨出电话" />

    <Button
        android:id="@+id/btn_callTwo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="跳过拨号界面,直接拨打电话" />

</LinearLayout>

俩种方式的区别:

1.调用拨号界面:去到了拨号界面,但是实际的拨号是由用户点击实现的

2.调用拨号功能:直接拨打了你所输入的号码,所以这种方式对于用户没有直接的提示效果,Android推荐使用第一种方式,如果是第二种的话,建议在之前加一个提示,是否拨打号码,然后确定后再拨打

猜你喜欢

转载自my.oschina.net/u/3705875/blog/1632403