要进行 Android Scoped Storage 测试,可以按照以下步骤进行:
在 AndroidManifest.xml
文件中添加以下权限:
在 MainActivity.java
文件中添加以下代码示例:
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_PERMISSION = 101;
private Button btnWriteFile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnWriteFile = findViewById(R.id.btn_write_file);
btnWriteFile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkPermissionsAndSaveFile();
}
});
}
private void checkPermissionsAndSaveFile() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
return;
}
}
saveFile();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
saveFile();
} else {
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void saveFile() {
File directory = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
File file = new File(directory, "test.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write("Hello, Scoped Storage!".getBytes());
fos.close();
Toast.makeText(MainActivity.this, "File saved successfully", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Error saving file", Toast.LENGTH_SHORT).show();
}
}
}
在 activity_main.xml
文件中添加一个按钮:
这样,当用户点击 "Write File" 按钮时,会检查是否有写入外部存储的权限。如果没有权限,则会请求权限。如果有权限,则会保存文件到外部存储的 Documents 目录下,并显示保存成功的 Toast 消息。