티스토리 뷰
1. 필요한 권한을 요청한다.
ContestCompat.checkSelfPermissions 를 이용해서 권한이 있는지 확인하고, 권한이 없는 경우에는 리스트에 추가한다.
필요한 권한을 리스트에 추가한 뒤 ActivityCompat.requestPermissions 를 이용해서 권한을 요청한다.
private static final int PERMISSION_REQUEST_CODE = 1;
private void checkPermissions(){
List<String> permissionList = new ArrayList<>();
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.BLUETOOTH) !=
PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.BLUETOOTH);
}
if (ContextCompat.checkSelfPermission(
this, Manifest.permission.BLUETOOTH_ADMIN) !=
PackageManager.PERMISSION_GRANTED) {
permissionList.add(Manifest.permission.BLUETOOTH_ADMIN);
}
if(permissionList.size() == 0){
return;
}
String[] requestPermissions = permissionList.toArray(new String[permissionList.size()]);
// You can directly ask for the permission.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this, requestPermissions, PERMISSION_REQUEST_CODE);
}
}
2. 권한 획득 결과를 받을 콜백 구현
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted. Continue the action or workflow
// in your app.
} else {
// Explain to the user that the feature is unavailable because
// the features requires a permission that the user has denied.
// At the same time, respect the user's decision. Don't link to
// system settings in an effort to convince the user to change
// their decision.
}
return;
}
// Other 'case' lines to check for other
// permissions this app might request.
}
'SW development > Android App' 카테고리의 다른 글
안드로이드 스튜디오 단축키 (0) | 2021.01.16 |
---|---|
AndroidX로 마이그레이션 하기 (0) | 2020.07.28 |
안드로이드 스튜디오 설치하기 (0) | 2020.02.16 |