Android拨打电话

本文详细介绍了在Android系统中如何获取拨打电话的权限,并通过代码实现拨打电话功能,包括跳转拨号界面和直接发起呼叫两种方式。

1、要使用Android系统中的电话拨号功能,首先必须在AndroidManifest.xml功能清单中加入允许拨打电话的权限:

      <uses-permission android:name="android.permission.CALL_PHONE" /> // 允许拨打电话权限

 2、进行拨打电话的代码:

       a、调用Android系统的拨号界面,但不发起呼叫,用户按下拨号键才会进行呼叫

 


 
  1. @Override    
  2.    public void onCreate(Bundle savedInstanceState) {    
  3.        super.onCreate(savedInstanceState);    
  4.        setContentView(R.layout.main);    
  5.            
  6.        Button callBut = (Button)findViewById(R.id.callBut);    
  7.            
  8.        callBut.setOnClickListener(new View.OnClickListener() {    
  9.             
  10.         @Override    
  11.         public void onClick(View v) { 
  12.         黄色必须有   
  13.             Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:13800138000"));    
  14.             startActivity(intent);    
  15.         }    
  16.     });    
  17. }    

       

 

   b、直接拨号发起呼叫 

 

[java]  view plain  copy
 
  1. @Override    
  2.    public void onCreate(Bundle savedInstanceState) {    
  3.        super.onCreate(savedInstanceState);    
  4.        setContentView(R.layout.main);    
  5.            
  6.        Button callBut = (Button)findViewById(R.id.callBut);    
  7.            
  8.        callBut.setOnClickListener(new View.OnClickListener() {    
  9.             
  10.         @Override    
  11.         public void onClick(View v) {    
  12.             Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel://13800138000"));    
  13.             startActivity(intent);    
  14.         }    
  15.     });    
  16. }    

 

注:其中Uri.parse("tel://13800138000")中的格式写成Uri.parse("tel:13800138000"),测试中也通过的。

 

转载于:https://www.cnblogs.com/1426837364qqcom/p/5201430.html

<think>我们参考引用[1]和引用[3]来实现拨打电话功能。步骤:1.添加拨打电话的权限(CALL_PHONE)到AndroidManifest.xml。2.在布局文件中添加一个EditText(用于输入电话号码)和一个Button(用于触发拨打电话)。3.在Activity中获取Button,并设置点击事件。在点击事件中,获取EditText中的电话号码,然后使用Intent拨打电话。注意:从Android6.0(API23)开始,需要在运行时请求危险权限(CALL_PHONE)。因此,我们需要检查权限,如果没有权限则请求权限。示例代码:1.在AndroidManifest.xml中添加权限:```xml<uses-permissionandroid:name="android.permission.CALL_PHONE"/>```2.布局文件(activity_main.xml)示例:```xml<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:padding="16dp"><EditTextandroid:id="@+id/et_phone_number"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="输入电话号码"android:inputType="phone"/><Buttonandroid:id="@+id/btn_call"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:text="拨打电话"/></LinearLayout>```3.MainActivity.kt示例:```kotlinimportandroid.content.Intentimportandroid.content.pm.PackageManagerimportandroid.net.Uriimportandroidx.appcompat.app.AppCompatActivityimportandroid.os.Bundleimportandroid.widget.Buttonimportandroid.widget.EditTextimportandroid.widget.Toastimportandroidx.core.app.ActivityCompatimportandroidx.core.content.ContextCompatclassMainActivity:AppCompatActivity(){privatelateinitvaretPhoneNumber:EditTextprivatelateinitvarbtnCall:Buttoncompanionobject{privateconstvalCALL_PHONE_REQUEST_CODE=101}overridefunonCreate(savedInstanceState:Bundle?){super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)etPhoneNumber=findViewById(R.id.et_phone_number)btnCall=findViewById(R.id.btn_call)btnCall.setOnClickListener{valphoneNumber=etPhoneNumber.text.toString().trim()if(phoneNumber.isNotEmpty()){//检查权限if(ContextCompat.checkSelfPermission(this,android.Manifest.permission.CALL_PHONE)==PackageManager.PERMISSION_GRANTED){callPhone(phoneNumber)}else{//请求权限ActivityCompat.requestPermissions(this,arrayOf(android.Manifest.permission.CALL_PHONE),CALL_PHONE_REQUEST_CODE)}}else{Toast.makeText(this,"请输入电话号码",Toast.LENGTH_SHORT).show()}}}privatefuncallPhone(phoneNumber:String){valintent=Intent(Intent.ACTION_CALL).apply{data=Uri.parse("tel:$phoneNumber")}startActivity(intent)}overridefunonRequestPermissionsResult(requestCode:Int,permissions:Array<outString>,grantResults:IntArray){super.onRequestPermissionsResult(requestCode,permissions,grantResults)when(requestCode){CALL_PHONE_REQUEST_CODE->{if(grantResults.isNotEmpty()&&grantResults[0]==PackageManager.PERMISSION_GRANTED){valphoneNumber=etPhoneNumber.text.toString().trim()if(phoneNumber.isNotEmpty()){callPhone(phoneNumber)}}else{Toast.makeText(this,"权限被拒绝,无法拨打电话",Toast.LENGTH_SHORT).show()}}}}}```注意:-我们使用了`Intent.ACTION_CALL`来直接拨打电话,这会直接拨打而不需要用户再次确认。如果需要用户确认,可以使用`Intent.ACTION_DIAL`,这样会打开拨号界面并显示号码,由用户点击拨打。-使用`Intent.ACTION_CALL`需要`CALL_PHONE`权限,而`Intent.ACTION_DIAL`不需要权限。如果使用`Intent.ACTION_DIAL`,则不需要请求权限,代码可以简化为:```kotlinprivatefundialPhone(phoneNumber:String){valintent=Intent(Intent.ACTION_DIAL).apply{data=Uri.parse("tel:$phoneNumber")}startActivity(intent)}```因此,如果不需要直接拨打,而是跳转到拨号界面,则不需要请求权限,也不需要声明`CALL_PHONE`权限。根据需求选择使用哪种方式。引用说明:我们在实现拨打电话功能时,参考了引用[1]和引用[3]中关于拨打电话的基本实现和权限处理[^1][^3]。§§相关问题§§1.如何实现电话录音功能?2.在Android中,如何检测电话状态(如响铃、接听、挂断)?3.Android9及以上版本对电话录音有哪些限制?如何解决?</think>### Android 实现拨打电话功能示例代码 在 Android 中实现拨打电话功能需要以下步骤: #### 1. 添加拨号权限 在 `AndroidManifest.xml` 中添加权限声明: ```xml <uses-permission android:name="android.permission.CALL_PHONE" /> ``` #### 2. 布局文件 (activity_main.xml) ```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/phoneNumberEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入电话号码" android:inputType="phone"/> <Button android:id="@+id/callButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="拨打电话" android:layout_marginTop="16dp"/> </LinearLayout> ``` #### 3. 实现拨号功能 (MainActivity.kt) ```kotlin import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { private lateinit var phoneNumberEditText: EditText private lateinit var callButton: Button // 权限请求码 companion object { private const val CALL_PHONE_PERMISSION_REQUEST_CODE = 100 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) phoneNumberEditText = findViewById(R.id.phoneNumberEditText) callButton = findViewById(R.id.callButton) callButton.setOnClickListener { val phoneNumber = phoneNumberEditText.text.toString().trim() if (phoneNumber.isNotEmpty()) { makePhoneCall(phoneNumber) } else { Toast.makeText(this, "请输入电话号码", Toast.LENGTH_SHORT).show() } } } private fun makePhoneCall(phoneNumber: String) { // 检查权限 if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.CALL_PHONE ) != PackageManager.PERMISSION_GRANTED ) { // 请求权限 ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.CALL_PHONE), CALL_PHONE_PERMISSION_REQUEST_CODE ) } else { // 已有权限,直接拨号 startCall(phoneNumber) } } private fun startCall(phoneNumber: String) { try { val intent = Intent(Intent.ACTION_CALL).apply { data = Uri.parse("tel:$phoneNumber") } startActivity(intent) } catch (e: SecurityException) { Toast.makeText(this, "拨号权限被拒绝", Toast.LENGTH_SHORT).show() } } // 处理权限请求结果 override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == CALL_PHONE_PERMISSION_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { val phoneNumber = phoneNumberEditText.text.toString().trim() if (phoneNumber.isNotEmpty()) { startCall(phoneNumber) } } else { Toast.makeText(this, "拨号权限被拒绝,无法拨打电话", Toast.LENGTH_SHORT).show() } } } } ``` ### 关键说明 1. **权限处理**: - Android 6.0+ 需要动态请求 `CALL_PHONE` 权限 - 使用 `ContextCompat.checkSelfPermission()` 检查权限 - 使用 `ActivityCompat.requestPermissions()` 请求权限 2. **两种拨号方式**: - `ACTION_CALL`:直接拨打电话(需要 `CALL_PHONE` 权限) - `ACTION_DIAL`:打开拨号界面(不需要权限),替换为: ```kotlin val intent = Intent(Intent.ACTION_DIAL).apply { data = Uri.parse("tel:$phoneNumber") } ``` 3. **电话号码格式**: - 使用 `Uri.parse("tel:$phoneNumber")` 确保正确格式 - 号码可包含国际区号(如 `+8613800138000`) 4. **错误处理**: - 捕获 `SecurityException` 处理权限异常 - 检查空号码输入 ### 注意事项 1. 在 Android 10+ 设备上,需要在 `AndroidManifest.xml` 中添加电话权限声明: ```xml <queries> <intent> <action android:name="android.intent.action.DIAL" /> </intent> </queries> ``` 2. 对于直接拨号(`ACTION_CALL`),需要确保用户已授予权限,否则会抛出安全异常[^1][^3]。 3. 如果只需要打开拨号界面,使用 `ACTION_DIAL` 可避免权限请求流程。 4. 在真实设备上测试时,确保 SIM 卡可用且设备支持通话功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值