Android Q(API级别29)是Android操作系统的一个版本,它引入了许多新的隐私和安全特性。从特定目录获取图片列表涉及到文件系统的访问和权限管理。
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE = 100;
private static final String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_CODE);
} else {
getImagesFromDirectory(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getImagesFromDirectory(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
}
}
}
private void getImagesFromDirectory(File directory) {
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles((dir, name) -> name.endsWith(".jpg") || name.endsWith(".png"));
if (files != null) {
List<String> imagePaths = new ArrayList<>();
for (File file : files) {
imagePaths.add(file.getAbsolutePath());
}
// 处理图片路径列表
}
}
}
}
SecurityException
。解决方法是请求必要的权限。.jpg
、.png
)进行过滤。可以使用File.listFiles
方法的过滤器参数。通过以上步骤和代码示例,你应该能够在Android Q中从特定目录获取图片列表。
领取专属 10元无门槛券
手把手带您无忧上云