Reputation: 1
Why i get an error on intent? I want to call a number when a clicking on a floating button.
ContextCompat.startActivity(intent), here a get the error (intent)
Type mismatch. Required:Context Found:Intent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
Snackbar.make(view, "Secretariaat wordt gebeld",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
makePhoneCall("0123456")
}
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
}
fun makePhoneCall(number: String) : Boolean {
try {
val intent = Intent(Intent.ACTION_CALL)
intent.setData(Uri.parse("tel:$number"))
ContextCompat.startActivity(intent)
return true
} catch (e: Exception) {
e.printStackTrace()
return false
}
}
Upvotes: 0
Views: 461
Reputation: 5011
ContextCompat.startActivity(intent)
use only startActivity(intent)
as you are already in an ActivityIntent.ACTION_CALL
you need call permission in manifest.
<uses-permission android:name="android.permission.CALL_PHONE"/>
There is another solution which I prefer. Use Intent.ACTION_DIAL
instead of Intent.ACTION_CALL
which doesn't require permission.
Your code would be:
fun makePhoneCall(number: String) : Boolean {
try {
val intent = Intent(Intent.ACTION_DIAL)
intent.setData(Uri.parse("tel:$number"))
startActivity(intent)
return true
} catch (e: Exception) {
e.printStackTrace()
return false
}
}
Upvotes: 0
Reputation: 559
If you need to invoke method startActivity()
, you can do it without ContextCompat
class. If you call this method inside Activity
class. In that case your code will be like:
fun makePhoneCall(number: String) : Boolean {
try {
val intent = Intent(Intent.ACTION_CALL)
intent.setData(Uri.parse("tel:$number"))
startActivity(intent)
return true
} catch (e: Exception) {
e.printStackTrace()
return false
}
}
Upvotes: 0
Reputation: 3045
That's because ContextCompat.startActivity
takes three arguments, Context
, Intent
and a Bundle
as extra options (can be null)
ContextCompat.startActivity(this, intent, null)
Upvotes: 1