-2
私はアンドロイドを初めて使っています。私は保管許可を取得しようとしています。 onRequestPermissionsResultメソッドのグローバルブール変数を変更することはできません。私はpermissionIsGranted = trueにすることはできません。それで、私を助けることができる人がいますか?私は何をすべきか?Androidスタジオでグローバル変数を変更できません
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;
}
}
}
コンパイル時にエラーが発生していませんか? –