Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Passing arguments when asking for permissions (Android 6)

Tags:

android

in my Android app i need to ask for permissions to write on external storage. Since Android 6, you have to ask for the permissions at run-time.

My problem is, I don't know how to resume my origin task after asking for the permissions because my function got passed an argument (soundId) which is "lost" after asking for the permissions. How to pass arguments when asking for permissions ?

My code looks like this:

MainActivity.java

static final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;

public static void sharesound(int soundId, final Context context){
if (ActivityCompat.checkSelfPermission(context,    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
{
  CopyRAWtoSDCard(soundId, soundpath,context);
} 

else 
{
  ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
}
}



@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED )
    {
      sharesound(soundId,getApplicationContext()); **I cannot access soundId from here !** 
    }
}
like image 888
computerjulian Avatar asked Dec 18 '16 19:12

computerjulian


1 Answers

EDIT:// This is outdated, better use ContentProvider or Fileprovider as no permissions are required for them!

I have found the solution by myself now:

first, we need a global variable:

 int lastsharedsound;

Then, the sharesound function saves the last shared sound into that variable.

public static void sharesound(int soundId)
{
    lastsharedsound=soundId;
    if (ActivityCompat.checkSelfPermission(context,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
    {
      CopyRAWtoSDCard(soundId, soundpath,context);
      ***do the intent sharing stuff here***
    } 

    else 
    {
      ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},     5);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
{
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == 5 && grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED )
    {
       sharesound(lastsharedsound); ***Here we call our function again*** 
    }
}
like image 69
computerjulian Avatar answered Sep 27 '22 17:09

computerjulian