i want to download image from remote url , and i need to get user persmission to save image, but i am unable to do that in GridAdapter.java file , this is not working in adapter:
requestPermissions((Activity) context,new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},DOWNLOAD_REQUEST_CODE);
i have tried many methods which are available on internet, but nothing seems to work,
like ActivityCompat.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);
in GridActivity class create an interface and implements it in GridAdapter class
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);
}
}
}
and in Grid Adapter you have to write these methods
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
*/
}
}