android请求权限不适用于单击按钮

时间:2018-12-24 05:07:48

标签: android permissions retrofit2 android-external-storage

第一次

android请求权限不适用于按钮单击。再次单击按钮,它不会在外部存储中创建文件夹。我从应用程序退出,然后返回到应用程序,在单击按钮并在外部创建文件夹后,它可以工作。第一次Log name and name_ = null。回到应用Log name = null & name_ = william

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String name = xxxx; // select name from External Storage
    if (name != null) {
        Log.e("name", name);
    } else {
        Log.e("name", "name_null");
    }

    findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           if (isPermissionGranted()) {
               action();
           }
        }
    });

}

public boolean isPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.e("TAG", "Permission is granted");
            return true;
        } else {
            Log.e("TAG", "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            return false;
        }
    } else {
        Log.e("TAG", "Permission is granted");
        return true;
    }
}


@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                action();
            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
    }
}


private void action() {
        // retorfit api here
        @Override
        public void onResponse(@NonNull Call<User> call, @NonNull Response<User> response) {
            if (response.body() != null && response.isSuccessful()) {

                // save name into External Storage (response.body().getName())                    
                // after save, when i log
                String name = xxxx; // select name from External Storage
                if (name != null) {
                    Log.e("name_", name);
                } else {
                    Log.e("name_", "name_null");
                }
            }
        }
}

}

0 个答案:

没有答案