본문 바로가기

Android

Android : 권한받기

권한받기


AndroidManifest.xml

1
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
cs


MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intro);
 
        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(IntroActivity.this,
                Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
 
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(IntroActivity.this,
                    Manifest.permission.READ_PHONE_STATE)) {
 
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
 
            } else {
 
                // No explanation needed, we can request the permission.
 
                ActivityCompat.requestPermissions(IntroActivity.this,
                        new String[]{Manifest.permission.READ_PHONE_STATE},
                        1);
 
                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }else{
            
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0== PackageManager.PERMISSION_GRANTED) {
 
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
 
                } else {
 
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
 
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
cs


주의: 권한을 받을 때 권한획득창과 동시에 Toast 등의 다른 창을 띄우면 마시멜로 이하 버전에서 오버레이 문제가 생길 수 있다.