Android 6.0 동적 권한 신청 강좌
프로젝트 주소:https://github.com/why168/AndroidProjects/tree/master/PermissionManage
소개 하 다.
장치 가 Android 6.0(API 레벨 23)또는 더 높 은 버 전 으로 실행 되 고 있 으 며,targetSdkVersion 이 23 또는 더 높 은 버 전이 적용 되 고 있 으 면 실행 중 사용자 에 게 권한 을 요청 합 니 다.
장치 가 Android 5.1(API 레벨 22)또는 더 낮은 버 전 으로 실행 되 고 targetSdkVersion 이 22 또는 더 낮은 버 전이 적용 되면 시스템 은 사용자 가 앱 을 설치 할 때 권한 을 부여 하도록 요구 합 니 다.
참고 자료
https://developer.android.google.cn/guide/topics/security/permissions.html
https://github.com/lovedise/PermissionGen
https://github.com/tbruyelle/RxPermissions
다음은 단독 신청 권한 이 필요 합 니 다.모두 9 조로 나 뉘 어 있 습 니 다.각 조 에 하나의 권한 만 있 으 면 전체 권한 을 기본 으로 사용 할 수 있 습 니 다.
group:android.permission-group.CONTACTS
permission:android.permission.WRITE_CONTACTS
permission:android.permission.GET_ACCOUNTS
permission:android.permission.READ_CONTACTS
group:android.permission-group.PHONE
permission:android.permission.READ_CALL_LOG
permission:android.permission.READ_PHONE_STATE
permission:android.permission.CALL_PHONE
permission:android.permission.WRITE_CALL_LOG
permission:android.permission.USE_SIP
permission:android.permission.PROCESS_OUTGOING_CALLS
permission:com.android.voicemail.permission.ADD_VOICEMAIL
group:android.permission-group.CALENDAR
permission:android.permission.READ_CALENDAR
permission:android.permission.WRITE_CALENDAR
group:android.permission-group.CAMERA
permission:android.permission.CAMERA
group:android.permission-group.SENSORS
permission:android.permission.BODY_SENSORS
group:android.permission-group.LOCATION
permission:android.permission.ACCESS_FINE_LOCATION
permission:android.permission.ACCESS_COARSE_LOCATION
group:android.permission-group.STORAGE
permission:android.permission.READ_EXTERNAL_STORAGE
permission:android.permission.WRITE_EXTERNAL_STORAGE
group:android.permission-group.MICROPHONE
permission:android.permission.RECORD_AUDIO
group:android.permission-group.SMS
permission:android.permission.READ_SMS
permission:android.permission.RECEIVE_WAP_PUSH
permission:android.permission.RECEIVE_MMS
permission:android.permission.RECEIVE_SMS
permission:android.permission.SEND_SMS
permission:android.permission.READ_CELL_BROADCASTS
다음은 일반 권한 으로 AndroidManifest.xml 에서 신청 하면 됩 니 다.
android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_NOTIFICATION_POLICY
android.permission.ACCESS_WIFI_STATE
android.permission.ACCESS_WIMAX_STATE
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN
android.permission.BROADCAST_STICKY
android.permission.CHANGE_NETWORK_STATE
android.permission.CHANGE_WIFI_MULTICAST_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.CHANGE_WIMAX_STATE
android.permission.DISABLE_KEYGUARD
android.permission.EXPAND_STATUS_BAR
android.permission.FLASHLIGHT
android.permission.GET_ACCOUNTS
android.permission.GET_PACKAGE_SIZE
android.permission.INTERNET
android.permission.KILL_BACKGROUND_PROCESSES
android.permission.MODIFY_AUDIO_SETTINGS
android.permission.NFC
android.permission.READ_SYNC_SETTINGS
android.permission.READ_SYNC_STATS
android.permission.RECEIVE_BOOT_COMPLETED
android.permission.REORDER_TASKS
android.permission.REQUEST_INSTALL_PACKAGES
android.permission.SET_TIME_ZONE
android.permission.SET_WALLPAPER
android.permission.SET_WALLPAPER_HINTS
android.permission.SUBSCRIBED_FEEDS_READ
android.permission.TRANSMIT_IR
android.permission.USE_FINGERPRINT
android.permission.VIBRATE
android.permission.WAKE_LOCK
android.permission.WRITE_SYNC_SETTINGS
com.android.alarm.permission.SET_ALARM
com.android.launcher.permission.INSTALL_SHORTCUT
com.android.launcher.permission.UNINSTALL_SHORTCUT
예제 코드
/**
* BaseActivity
*
* @author Edwin.Wu
* @version 2017/3/17$ 14:12$
* @since JDK1.8
*/
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
*
*
* @param permissions
* @return
*/
public boolean hasPermission(String... permissions) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(this, permission)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
/**
*
*
* @param requestCode
* @param permissions
*/
public void requestPermission(int requestCode, String... permissions) {
ActivityCompat.requestPermissions(this, permissions, requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PermissionsConstans.WRITE_STORAGE_CODE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doSDCardPermission();
} else {
//TODO
Toast.makeText(BaseActivity.this, "WRITE_EXTERNAL_STORAGE ", Toast.LENGTH_SHORT).show();
}
break;
case PermissionsConstans.CALL_PHONE_CODE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doCallPhone();
} else {
//TODO
Toast.makeText(BaseActivity.this, "ACTION_CALL ", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
/**
* SD
*/
protected void doSDCardPermission() {
//TODO
}
/**
*
*/
protected void doCallPhone() {
//TODO
}
}
/**
* BaseActivity
*
* @author Edwin.Wu
* @version 2017/3/17 11:59
* @since JDK1.8
*/
public class PermissionActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission);
}
public void callPhone(View view) {
if (hasPermission(android.Manifest.permission.CALL_PHONE)) {
doCallPhone();
} else {
requestPermission(PermissionsConstans.CALL_PHONE_CODE, android.Manifest.permission.CALL_PHONE);
}
}
public void sdCardPermission(View view) {
if (hasPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
doSDCardPermission();
} else {
requestPermission(PermissionsConstans.WRITE_STORAGE_CODE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
}
@Override
protected void doCallPhone() {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + "10000"));
startActivity(intent);
}
@Override
protected void doSDCardPermission() {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request
.Builder()
.url("http://img.mmjpg.com/2015/350/3.jpg")
.get()
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
InputStream is = body.byteStream();
int len = 0;
byte[] bytes = new byte[2048];
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + System.currentTimeMillis() + ".jpg";
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
while ((len = is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
fos.flush();
}
Toast.makeText(PermissionActivity.this, "SDCard ", Toast.LENGTH_SHORT).show();
Log.e("Edwin", "SDCard ");
}
});
}
}
/**
* PermissionGen
*
* @author Edwin.Wu
* @version 2017/3/17 23:19
* @since JDK1.8
*/
public class PermissionGenActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission_gen);
}
public void openCamera(View view) {
PermissionGen.needPermission(this, 200, Manifest.permission.CAMERA);
}
public void openGroup(View view) {
PermissionGen
.with(this)
.addRequestCode(100)
.permissions(
Manifest.permission.READ_CONTACTS,
Manifest.permission.RECEIVE_SMS,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_CONTACTS)
.request();
}
@PermissionSuccess(requestCode = 100)
public void openGroupSuccess() {
Toast.makeText(this, "Group Permission Success", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, ContactActivity.class));
}
@PermissionFail(requestCode = 100)
private void openGroupFail() {
Toast.makeText(this, "Group permission is not granted", Toast.LENGTH_SHORT).show();
}
@PermissionSuccess(requestCode = 200)
public void openCameraSuccess() {
Toast.makeText(this, "Camera permission Success", Toast.LENGTH_SHORT).show();
}
@PermissionFail(requestCode = 200)
public void openCameraFail() {
Toast.makeText(this, "Camera permission is not granted", Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
}
}
/**
* RxPermissionGen
*
* @author Edwin.Wu
* @version 2017/3/19 14:17
* @since JDK1.8
*/
public class RxPermissionActivity extends AppCompatActivity {
private static final String TAG = "RxPermissionsSample";
private Camera camera;
private SurfaceView surfaceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions.setLogging(true);
setContentView(R.layout.activity_rx_permission);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
RxView.clicks(findViewById(R.id.enableCamera))
// Ask for permissions when button is clicked
.compose(rxPermissions.ensureEach(Manifest.permission.CAMERA))
.subscribe(new Action1<Permission>() {
@Override
public void call(Permission permission) {
Log.i(TAG, "Permission result " + permission);
if (permission.granted) {
releaseCamera();
camera = Camera.open(0);
try {
camera.setPreviewDisplay(surfaceView.getHolder());
camera.startPreview();
} catch (IOException e) {
Log.e(TAG, "Error while trying to display the camera preview", e);
}
} else if (permission.shouldShowRequestPermissionRationale) {
// Denied permission without ask never again
Toast.makeText(RxPermissionActivity.this, "Denied permission without ask never again", Toast.LENGTH_SHORT).show();
} else {
// Denied permission with ask never again
// Need to go to the settings
Toast.makeText(RxPermissionActivity.this, "Permission denied, can't enable the camera", Toast.LENGTH_SHORT).show();
}
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable t) {
Log.e(TAG, "onError", t);
}
},
new Action0() {
@Override
public void call() {
Log.i(TAG, "OnComplete");
}
});
}
@Override
protected void onStop() {
super.onStop();
releaseCamera();
}
private void releaseCamera() {
if (camera != null) {
camera.release();
camera = null;
}
}
}
이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.