Android

Android 권한 받고 유저 핸드폰 번호 가져오기(feat. Kotlin)

김한토 2024. 7. 29. 19:30
반응형
SMALL

AndroidManifest.xml

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
    <uses-permission android:name="android.permission.READ_SMS"/>

 

안드로이드 앱에서 권한을 체크하고,

필요한 경우 권한을 요청하는 기능을 제공하는 유틸리티 객체 생성.

 

Permission.kt

object Permission {

    fun checkAndRequestPermissions(activity: Activity, permissions: Array<String>, requestCode: Int): Boolean {
        val permissionNeeded = permissions.filter {
            ContextCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED
        }

        return if (permissionNeeded.isNotEmpty()) {
            ActivityCompat.requestPermissions(activity, permissionNeeded.toTypedArray(), requestCode)
            false
        } else {
            true
        }
    }
}

 

 

 

안드로이드 앱에서 전화번호를 가져오는 기능을 제공하는 유틸리티 객체 생성

전화번호를 읽기 위해 필요한 권한을 체크하고, 권한이 부여된 경우 전화번호를 로그에 기록

 

PhoneNumber.kt

object PhoneNumber {

    private const val TAG = "PhoneNumberUtils"

    fun getPhoneNumber(context: Context) {
        Log.d(TAG, "Checking permissions for getting phone number")
        val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_PHONE_NUMBERS) == PackageManager.PERMISSION_GRANTED) {
            val phoneNumber = telephonyManager.line1Number
            Log.d(TAG, "Phone number: $phoneNumber")
        } else {
            Log.d(TAG, "Permission not granted to read phone state or phone numbers")
        }
    }
}

 

mainActivity가 onCreate() 될 때, 사용자에게 필요한 권한을 요청하고, 권한이 부여된 경우 전화번호를 읽어오는 기능을 수행한다.

class MainActivity : AppCompatActivity() {

    private val PERMISSION_REQUEST_CODE = 1
    private val PERMISSIONS = arrayOf(
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.READ_SMS,
        Manifest.permission.READ_PHONE_NUMBERS
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Permission.checkAndRequestPermissions(
                this,
                PERMISSIONS,
                PERMISSION_REQUEST_CODE
            )
        ) {
            PhoneNumber.getPhoneNumber(this)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                    PhoneNumber.getPhoneNumber(this)
                } else {
                    Toast.makeText(
                        this,
                        "권한이 없습니다",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }
    }

 

 

끝.

반응형
LIST