안드로이드 스튜디오 ( 오레오 ) MEMO

● Dangerous Permission (권한) 받기

1. manifest > AndroidManifest.xml

사용할 권한을 다음의 형식으로 상단에 작성

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

 

2. PermissionActivity


import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import kr.co.wobstudio.samplea2_20180611.R;

public class PermissionActivity extends AppCompatActivity {
    Button btn_check;//레이아웃에서 버튼 생성

    String[] PERMISSION = {Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);

        btn_check = findViewById(R.id.btn_check);

        btn_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
                //최초 1회 false 가 리턴, 두번째부터는 true 가 리턴
                if (shouldShowRequestPermissionRationale(PERMISSION[0]) || shouldShowRequestPermissionRationale(PERMISSION[1])) {
                    
                    requestPermissions(PERMISSION,0);   //팝업
                } else {
                    requestPermissions(PERMISSION,0);   //팝업
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == 0) {
            for (int i = 0 ; i < permissions.length ; i++) {
                if (permissions[i].equals(Manifest.permission.READ_SMS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(PermissionActivity.this,"READ_SMS 허용",Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(PermissionActivity.this,"READ_SMS 거부",Toast.LENGTH_LONG).show();
                    }
                } else if (permissions[i].equals(Manifest.permission.RECEIVE_SMS)) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(PermissionActivity.this,"RECEIVE_SMS 허용",Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(PermissionActivity.this,"RECEIVE_SMS 거부",Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }
}

 

댓글

댓글 본문
작성자
비밀번호
버전 관리
gamza
현재 버전
선택 버전
graphittie 자세히 보기