2학년 모바일프로그래밍 10주차

서지현·2021년 12월 11일
0

모바일프로그래밍

목록 보기
1/4

Permission

  • Android에서는 사용자가 다른 앱 권한을 부여하거나 거부할 수 있습니다.

  • 이러한 권한은 다음에 대한 액세스를 보호합니다.

    1. 시스템 상태 및 사용자의 연락처 정보와 같은 제한된 데이터
    2. 페어링된 기기에 연결하고 오디오를 녹음하는 등 제한된 작업
  • Install-time permissions

    • 시스템은 사용자가 앱을 설치하면 자동으로 앱에 일부 권한을 부여합니다.
    • 일반 권한이라고 함
    • 앱 스토어는 사용자가 다음과 같은 경우 설치 시간 권한 알림을 표시합니다.
      -앱의 세부 정보 페이지를 봅니다.

  • Runtime permissions
    • 시스템은 앱이 런타임에 다른 권한을 요청하도록 요구합니다.
    • 위험한 권한으로 알려짐
    • 많은 런타임 권한이 앱에 특수한 유형의 제한된 데이터(개인 사용자 데이터)에 대한 액세스 권한을 부여합니다. 예: 위치, 연락처 정보.
    • 시스템은 앱이 런타임 권한을 요청할 때 사용자에게 런타임 권한 프롬프트를 표시합니다.

  • Permissions : Workflow

  • Get the CAMERA permission from user

  1. Declare the permission
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.seo.permissioncamera">

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


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.PermissionCamera">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

모든 권한은 Manifest.permission에 정의되어 있다
https://developer.android.com/reference/kotlin/android/Manifest.permission

  • camera permission
<uses-permission android:name="android.permission.CAMERA"/>
  1. Design app UX
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="356dp"
        android:layout_marginBottom="100dp"
        android:text="Dangerous Permission"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:layout_marginBottom="212dp"
        android:text="camera"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/textView2"
        app:layout_constraintHorizontal_bias="0.511"
        app:layout_constraintStart_toStartOf="@+id/textView2"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

</androidx.constraintlayout.widget.ConstraintLayout>
  1. Wait for the user to click “CAMERA” button
 val btnCamera = findViewById<Button>(R.id.button)
 btnCamera.setOnClickListener {
     Log.d("DKMobile", "CAMERA button pressed.")
  1. (Check) Permission already granted
val btnCamera = findViewById<Button>(R.id.button)
btnCamera.setOnClickListener {
    Log.d("DKMobile", "CAMERA button pressed.")
    val cameraPermission =
        ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
  1. Request the permission
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btnCamera = findViewById<Button>(R.id.button)
        btnCamera.setOnClickListener {
            Log.d("DKMobile", "CAMERA button pressed.")
            val cameraPermission =
                ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            if (cameraPermission == PackageManager.PERMISSION_GRANTED) {
                Log.d("DKMOBILE", "CAMERA permission already granted")
                var permitTxt = findViewById<TextView>(R.id.textView2)
                permitTxt.text = "CAMERA permission granted now"
            } else {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), 99)
                var permitTxt = findViewById<TextView>(R.id.textView2)
                permitTxt.text = "CAMERA permission not granted"
            }
        }
    }

99 : 개발자 -> 안드로이드 시스템에게 요청한 것을 확인하기 위해 작성 -> client가 안드로이드 시스템에게 요청하는 것과 분리하기 위함

  1. Permission already granted
 val btnCamera = findViewById<Button>(R.id.button)
        btnCamera.setOnClickListener {
            Log.d("DKMobile", "CAMERA button pressed.")
            val cameraPermission =
                ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            if (cameraPermission == PackageManager.PERMISSION_GRANTED) {
                Log.d("DKMOBILE", "CAMERA permission already granted")
                var permitTxt = findViewById<TextView>(R.id.textView2)
                permitTxt.text = "CAMERA permission granted now"
            } else {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), 99)
                var permitTxt = findViewById<TextView>(R.id.textView2)
                permitTxt.text = "CAMERA permission not granted"
            }
        }
  1. Process user selection
 override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var permitTxt = findViewById<TextView>(R.id.textView2)

        when (requestCode) {
            99 -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("DKMOBILE", "CAMERA permission granted now")
                    permitTxt.text = "CAMERA permission granted now"
                } else {
                    Log.d("DKMOBILE", "CAMERA permission not granted")
                    permitTxt.text = "CAMERA permission not granted"
                }
            }
        }
    }
  • 앱 설정환경

File I/O

  • Android는 디스크 기반 파일 시스템과 유사한 파일 시스템을 사용합니다.
  • 이 시스템은 앱 데이터를 저장할 수 있는 몇 가지 옵션을 제공합니다.
    1. 앱 전용 저장소 : 앱 전용 데이터를 저장하기 위한 저장소입니다.
    2. 공유 저장소 : 앱이 미디어 및 문서 파일과 같은 다른 앱과 공유하려는 파일을 저장합니다.
    3. 기본 설정 : 키-값 쌍에 비공개 원시 데이터 저장
    4. 데이터베이스 : Room 지속성 라이브러리를 사용하여 구조화된 데이터를 개인 데이터베이스에 저장
  • 앱은 다른 앱이 접근할 필요가 없거나 접근해서는 안 되는 파일을 생성합니다.
  • 앱별 파일 저장 위치:
    • 내부 저장소 디렉토리 : 다른 앱("파일 관리자")은 파일에 접근할 수 없습니다. 이 위치는 앱 자체에서만 액세스할 수 있는 민감한 데이터를 저장하기에 좋은 장소입니다. 앱이 제거되면 이 위치의 파일이 삭제됩니다.(시스템 수준 디렉터리라고 함)
    • 외부 저장소 디렉터리: 해당 앱에 적절한 권한이 있는 경우 다른 앱이 이 디렉터리에 액세스할 수 있습니다. 이 디렉터리에 저장된 파일은 앱에서만 사용하기 위한 것입니다.
      다른 앱이 액세스할 수 있어야 하는 파일을 특별히 만들려는 경우 앱은 이러한 파일을 대신 외부 저장소의 공유 저장소 부분에 저장해야 합니다.
 var content = findViewById<TextView>(R.id.textview)
        
        val fileName = "internal.txt"
        val fileBody = "File for testing"
        val buffo = applicationContext.openFileOutput(fileName, Context.MODE_PRIVATE)
        buffo.write(fileBody.toByteArray())
        content.text = fileBody
        buffo.close()

  • log값 남기기 + textview 남기기
   val buffi = applicationContext.openFileInput(fileName)
        val buffr = buffi.bufferedReader()
        var txt = buffr.readLine()
        content.text = fileBody
        buffr.close()
        Log.d("FILETEST", "---> $txt")
profile
안녕하세요

0개의 댓글

관련 채용 정보