当前位置 : 主页 > 编程语言 > c++ >

Base activity for permission logic.

来源:互联网 收集:自由互联 发布时间:2021-07-03
BasePermissionActivity package com.hf.common.activity;import android.Manifest;import android.content.pm.PackageManager;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v4.content.
BasePermissionActivity
package com.hf.common.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;

/**
 * Base activity for permission
 */
public abstract class BasePermissionActivity extends AppCompatActivity {
    private void checkPermission() {
        boolean needRequest = false;
        String[] permissions = getPermissionList();

        // check permissions
        for (String permission : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, permission)) {
                needRequest = true;
                break;
            }
        }

        // request permission
        if (needRequest) {
            ActivityCompat.requestPermissions(this, permissions, 0);
        }
    }

    public abstract String[] getPermissionList();

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int result : grantResults) {
            if (PackageManager.PERMISSION_GRANTED != result) {
                // finish if permission is not granted
                finish();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // check permission
        checkPermission();
    }
}
网友评论