我不需要拨打电话号码,我只需要打开拨号器并显示该电话号码。我应该使用什么Intent
来实现这个功能?
我不需要拨打电话号码,我只需要打开拨号器并显示该电话号码。我应该使用什么Intent
来实现这个功能?
有两种实现方式。
1) 通过代码启动拨号器,无需用户交互。
您需要使用 Action_Dial
,
使用下面的代码,将会打开拨号器并指定号码。
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
如果不加上“tel:”前缀,会抛出以下异常:java.lang.IllegalStateException: Could not execute method of the activity.
Action_Dial不需要任何权限。
如果想直接启动电话拨号而不需要用户交互,可以使用Intent.ACTION_CALL
操作。在这种情况下,必须在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.CALL_PHONE" />
2) 需要用户点击 "Phone_Number" 字符串来发起电话呼叫。
android:autoLink="phone"
您需要使用带有以下属性的TextView。
android:autoLink="phone" android:linksClickable="true" 是TextView的属性
您不需要使用intent或通过此方式获取权限。
虽然答案有些迟,但如果您有一个显示电话号码的 TextView
,则根本不需要处理意图,只需使用 XML 属性 android:autoLink="phone"
,操作系统将自动启动 ACTION_DIAL
意图。
好的,对于这个问题来说,我的回答可能会迟到得很久。但是,如果你想用Kotlin来完成它,这里只提供一个示例。
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:<number>")
startActivity(intent)
想必对某些人会有所帮助。
String number = "0123456789";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + number));
startActivity(intent);
<TextView
android:id="@+id/phoneNumber"
android:autoLink="phone"
android:linksClickable="true"
android:text="+91 22 2222 2222"
/>
android:autoLink="phone"
也是一个不错的解决方案。但这个选项有一个缺点,它不能处理所有长度的电话号码。例如,11位数的电话号码将无法使用此选项。解决方法是在电话号码前加上国家代码。08034448845
将无法使用+2348034448845
可以。一个为使用 Kotlin 的人编写的辅助函数:
fun openDialPad(context: Context, phoneNum: String) {
val intent = Intent(Intent.ACTION_DIAL)
intent.setData(Uri.parse("tel:$phoneNum"))
context.startActivity(intent)
}