如何在 Android 上拨打电话


此示例演示了如何在 Android 上拨打电话。

步骤 1 - 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。

步骤 2 - 将以下代码添加到 res/layout/activity_main.xml 中。

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent">
   <ListView
      android:id = "@+id/list"
      android:layout_width = "wrap_content"
      android:textSize = "30sp"
      android:layout_height = "wrap_content"
      android:text = "Click"/>
</LinearLayout>

在上面的代码中,我们使用了列表视图。

步骤 3 - 将以下代码添加到 src/MainActivity.java 中。

package com.example.myapplication;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
   public static final int REQUEST_READ_CONTACTS = 79;
   private static final int REQUEST = 112;
   ListView list;
   ArrayList mobileArray;
   ArrayList numberArray;
   String number;
   @TargetApi(Build.VERSION_CODES.LOLLIPOP)
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      numberArray = new ArrayList();
      if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS)
         == PackageManager.PERMISSION_GRANTED) {
         mobileArray = getAllContacts();
      } else {
         requestPermission();
      }
      list = findViewById(R.id.list);
      ArrayAdapter adapter = new ArrayAdapter<String>(this,
      android.R.layout.simple_list_item_1, android.R.id.text1, mobileArray);
      list.setAdapter(adapter);
      list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            number = (String) numberArray.get(position);
            if (Build.VERSION.SDK_INT >= 23) {
               String[] PERMISSIONS = {android.Manifest.permission.CALL_PHONE};
               if (!hasPermissions(MainActivity.this, PERMISSIONS)) {
                  ActivityCompat.requestPermissions((Activity) MainActivity.this, PERMISSIONS, REQUEST );
               } else {
                  makeCall(number);
               }
            } else {
               makeCall(number);
            }
         }
      });
   }
   private static boolean hasPermissions(Context context, String... permissions) {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context ! = null && permissions ! = null) {
         for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) ! = PackageManager.PERMISSION_GRANTED) {
               return false;
            }
         }
      }
      return true;
   }
   private void makeCall(String number) {
      Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
      phoneCallIntent.setData(Uri.parse("tel:"+number));
      startActivity(phoneCallIntent);
   }
   private void requestPermission() {
      if (ActivityCompat.shouldShowRequestPermissionRationale(this,
      android.Manifest.permission.READ_CONTACTS)) {
         // show UI part if you want here to show some rationale !!!
      } else {
         ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS},
         REQUEST_READ_CONTACTS);
      }
      if (ActivityCompat.shouldShowRequestPermissionRationale(this,
         android.Manifest.permission.READ_CONTACTS)) {
      } else {
         ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS},
         REQUEST_READ_CONTACTS);
      }
   }
   @Override
   public void onRequestPermissionsResult(int requestCode,
   String permissions[], int[] grantResults) {
      switch (requestCode) {
         case REQUEST_READ_CONTACTS: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               mobileArray = getAllContacts();
            } else {
               // permission denied,Disable the
               // functionality that depends on this permission.
            }
            return;
         }
         case REQUEST: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               makeCall(number);
            } else {
               Toast.makeText(MainActivity.this, "The app was not allowed to call.", Toast.LENGTH_LONG).show();
            }
         }
      }
   }
   private ArrayList getAllContacts() {
      ArrayList<String> nameList = new ArrayList<>();
      ContentResolver cr = getContentResolver();
      Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
      null, null, null, null);
      if ((cur ! = null ? cur.getCount() : 0) > 0) {
         while (cur ! = null && cur.moveToNext()) {
            String id = cur.getString(
            cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(
            ContactsContract.Contacts.DISPLAY_NAME));
            nameList.add(name);
            if (cur.getInt(cur.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
               Cursor pCur = cr.query(
               ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
               null,
               ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
               new String[]{id}, null);
               while (pCur.moveToNext()) {
                  String phoneNo = pCur.getString(pCur.getColumnIndex(
                  ContactsContract.CommonDataKinds.Phone.NUMBER));
                  numberArray.add(phoneNo);
               }
               pCur.close();
            }
         }
      }
      if (cur ! = null) {
         cur.close();
      }
      return nameList;
   }
}

步骤 4 - 将以下代码添加到 AndroidManifest.xml 中。

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.myapplication">
   <uses-permission android:name = "android.permission.READ_CONTACTS" />
   <uses-permission android:name = "android.permission.CALL_PHONE" />
   <application
      android:allowBackup = "true"
      android:theme = "@style/AppTheme.NoActionBar"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true">
      <activity
         android:name = ".MainActivity"
         android:configChanges = "keyboardHidden|orientation|screenSize">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <action android:name = "android.intent.action.CREATE_SHORTCUT" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的电脑。要从 Android Studio 运行应用程序,请打开您的一个项目活动文件,然后单击工具栏中的运行  图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕 -

现在点击 TextView 进行通话,如下所示 -

更新于: 2019-07-30

219 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告