我想从远程url下载图像,我需要获得用户权限来保存图像,但我无法在GridAdapter.java文件中做到这一点,这在适配器中不起作用:
requestPermissions((Activity) context,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},DOWNLOAD_REQUEST_CODE);
我已经尝试了很多方法,这些方法都可以在网上找到,但似乎没有工作,
likeActivityCompat.requestPermissions(context,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},DOWNLOAD_REQUEST_CODE);
requestPermissions((Activity) context.getApplicationContext(),new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},DOWNLOAD_REQUEST_CODE);
在GridActivity类中创建一个接口并在GridAdapter类中实现
interface IPermissionCallback{
void askForStoragePermission();
Boolean checkSelfStoragePermission();
}
public class GridActivity extends AppCompatActivity implements
IPermissionCallback {
private static final int DOWNLOAD_REQUEST_CODE = 1001;
private GridAdapter adapter;
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable
PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
//other codes...
//initialize GridAdapter here and then call setPermissionCallback()
//method as shown below
adapter.setPermissionCallback(this);
}
@Override
public void askForStoragePermission() {
requestPermissions(new String[]
{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
DOWNLOAD_REQUEST_CODE);
}
@Override
public Boolean checkSelfStoragePermission() {
if(checkCallingOrSelfPermission(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED){
return true;
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[]
permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
if (requestCode == DOWNLOAD_REQUEST_CODE
&& grantResults[0] == PackageManager.PERMISSION_GRANTED){
//permission granted update GridAdapter to do next task
adapter.onPermissionResult(true);
}else{
//permission denied update GridAdapter to do next task
adapter.onPermissionResult(false);
}
}
}
在Grid Adapter中你需要写这些方法
public class GridAdapter/**extends needed classes etc.*/{
private IPermissionCallback callback;
public void yourMethodWhereYouDownloadingImg(){
if (callback != null && callback.checkSelfStoragePermission()){
//already permission is granted
}else{
callback.askForStoragePermission();
}
}
public void setPermissionCallback(IPermissionCallback c){
this.callback = c;
}
public void onPermissionResult(Boolean permissionGranted){
/**
* if @permissionGranted is true download image else inform user
that permission is denied
*/
}
}