android - I want to make my app able to call a specific number via a button but all solutions i find are for java not kotlin and

admin2025-04-15  2

i want to be able to call a specific preset number using a button in my app Here is my code but when I run the app the button does do anything

val button3 = findViewById<Button>(R.id.button3)

button3.setOnClickListener {  
  val number = "*#0*#"  
  val intent = Intent(Intent.ACTION_DIAL)  
  intent.setData(Uri.parse("tel:" + "*#0*#"))  
  startActivity(intent)
}

I also did put the permission

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

in the manifest.

all the forums online i could find did not work

i want to be able to call a specific preset number using a button in my app Here is my code but when I run the app the button does do anything

val button3 = findViewById<Button>(R.id.button3)

button3.setOnClickListener {  
  val number = "*#0*#"  
  val intent = Intent(Intent.ACTION_DIAL)  
  intent.setData(Uri.parse("tel:" + "*#0*#"))  
  startActivity(intent)
}

I also did put the permission

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

in the manifest.

all the forums online i could find did not work

Share Improve this question asked Feb 4 at 10:44 Jonah CameronJonah Cameron 13 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Try this

button3.setOnClickListener {  
 val phoneNumber = "*#0*#"  
 val intent = Intent(Intent.ACTION_DIAL).apply {
    data = Uri.parse("tel:$phoneNumber")
 }
 if (intent.resolveActivity(packageManager) != null) {
    startActivity(intent)
 }
}

The Phone app's dialer is good at normalizing schemes, such as telephone numbers. So the scheme described isn't strictly required in the

Uri.parse()

method. However, if you haven't tried a scheme or are unsure whether it can be handled, use the

Uri.fromParts()

method instead

fore more details refer Initiate a phone call

转载请注明原文地址:http://www.anycun.com/QandA/1744726092a86766.html