要在同一应用程序的服务之间共享文件,可以使用共享首选项或外部存储。
使用共享首选项:
SharedPreferences.Editor editor = getSharedPreferences("shared_prefs", MODE_PRIVATE).edit(); editor.putString("key", "value"); editor.apply();
SharedPreferences prefs = getSharedPreferences("shared_prefs", MODE_PRIVATE); String value = prefs.getString("key", "");
使用外部存储:
File file = new File(getExternalFilesDir(null), "file.txt"); FileOutputStream outputStream = new FileOutputStream(file); outputStream.write("data".getBytes()); outputStream.close();
File file = new File(getExternalFilesDir(null), "file.txt"); FileInputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[(int) file.length()]; inputStream.read(bytes); inputStream.close(); String data = new String(bytes);
在使用外部存储时,要确保已请求WRITE_EXTERNAL_STORAGE权限。