前置代码
val phoneNumber = findViewById<EditText>(R.id.text_phone_number).text.toString()
val uri = Uri.parse("tel:$phoneNumber")
直接拨打电话
Log.i(localClassName, "###直接拨打电话")
val intent = Intent(Intent.ACTION_CALL, uri)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
intent.action = Intent.ACTION_CALL
intent.data = uri
startActivity(intent)
} else {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE), 1)
}
跳转页面拨打电话
Log.i(localClassName, "###跳转拨打电话")
val intent = Intent(Intent.ACTION_DIAL, uri)
startActivity(intent)
反射方式拨打电话
Log.i(localClassName, "###反射方式拨打电话")
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
Toast.makeText(this, "该方法不支持Android9(sdk28)以上版本", Toast.LENGTH_LONG).show()
return
}
try {
val telManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
val method: Method = telManager.javaClass.getDeclaredMethod("getITelephony")
method.isAccessible = true
val obj = method.invoke(telManager)
val mt = obj.javaClass.getMethod("call", String().javaClass, String().javaClass)
mt.isAccessible = true
mt.invoke(obj, packageName + "", phoneNumber)
Log.i(localClassName, "###反射方式拨打电话成功")
} catch (e: Exception) {
Log.i(localClassName, "###反射方式拨打电话失败")
e.printStackTrace();
}