-2
我是android新手。我正在嘗試獲取存儲權限。但不能在onRequestPermissionsResult方法中更改全局布爾變量。我無法使permissionIsGranted = true。那麼,有沒有人可以幫助我。我該怎麼辦?無法更改Android Studio中的全局變量
package com.plutianclub.musicappv1;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.jar.Manifest;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSION_REQUEST_STORAGE_READ = 101;
private boolean permissionIsGranted = false;
ListView lv;
String items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lvPlaylist);
requestStoragePermission();
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
if (permissionIsGranted) {
Toast.makeText(getApplicationContext(), "wow", Toast.LENGTH_SHORT).show();
ArrayList<File> mySongs = findSongs(Environment.getExternalStorageDirectory());
for (int i = 0; i < mySongs.size(); i++) {
toast(mySongs.get(i).getName());
}
}
}
private void requestStoragePermission() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST_STORAGE_READ);
}
}
}
public ArrayList<File> findSongs (File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles();
for (File singleFile : files){
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
}else {
if (singleFile.getName().endsWith(".mp3")){
al.add(singleFile);
}
}
}
return al;
}
public void toast(String text){
Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case MY_PERMISSION_REQUEST_STORAGE_READ:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted
permissionIsGranted = true;
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
}else {
//permission denied
permissionIsGranted = false;
Toast.makeText(getApplicationContext(), "This application needs Storage permission", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
你確定你沒有得到任何編譯時錯誤嗎? –