Tip/Android2023. 8. 22. 23:34

AndroidManifest.xml에 아래와 같이 권한을 추가 한다

    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />

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

 MainActivity안에 아래와 같이 버튼에 이벤트를 연결한다.

    private fun init() {
        val callButton : Button = findViewById(R.id.callButton)
        callButton.setOnClickListener( View.OnClickListener { _ -> runCall() })
    }

    private fun runCall() {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:01234561492"))
        val status = ActivityCompat.checkSelfPermission(this, 
            android.Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED
        if (status) {
            startActivity(intent)
        } else {
            Log.i("TAG", "Unable to launch call");
            ActivityCompat.requestPermissions(this, 
                arrayOf<String>(android.Manifest.permission.CALL_PHONE), CALL_REQUEST)
        }
    }

아래와 같이 onRequestPermissionsReseult()를 오버라이딩 해주면, 권한 컨펌 즉시 콜이 걸리게 된다.

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            CALL_REQUEST -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "통화가 가능 합니다", Toast.LENGTH_LONG).show()
                    runCall()
                } else {
                    Toast.makeText(this, "통화가 거절 되었습니다", Toast.LENGTH_LONG).show()
                }
            }
        }
    }
Posted by chobocho