在我的Android应用中,我需要请求在外部存储上写入的权限。 从Android 6开始,您必须在运行时请求权限。
我的问题是,我不知道如何在请求权限后恢复我的原始任务,因为我的函数传递了一个参数(soundId),该参数在请求权限后“丢失”。请求权限时如何传递参数?
我的代码如下所示:
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 !**
}
}
答案 0 :(得分:4)
编辑://这已经过时了,最好使用ContentProvider或Fileprovider,因为它们不需要任何权限!
我现在已经找到了解决方案:
首先,我们需要一个全局变量:
int lastsharedsound;
然后,sharesound函数将最后一个共享声音保存到该变量中。
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***
}
}
答案 1 :(得分:0)
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);
if(ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
sharesound(soundId, context);
}
}
}
修改强> 在再次调用方法之前,我添加了对权限的检查