如何在Android中执行chmod - API 8?

fra*_*lbo 2 linux android chmod media-player

在Android 2.3上运行我的应用程序播放mp3时遇到问题.这些mp3从远程服务器下载到/data/data/com.my.package.name/,默认文件权限为-rw -------.

与后期HONEYCOMB设备不同(根据我的测试),如果媒体播放器的文件权限不是-rw-rw-rw-,则媒体播放器拒绝读取mp3.

我很明显地证实,如果我使用adb shell将文件权限设置为666,那么媒体播放器就会成功读取它.

所以,经过网上的一些研究,我试着在写完文件之后实现以下代码:

String chmodString = "chmod 666 " + getActivity().getApplicationContext().getFilesDir().getParentFile().getPath() +"/" + fileName;
Process sh = Runtime.getRuntime().exec("su", null, new File("/system/bin/"));
OutputStream osChgPerms = sh.getOutputStream();
try {
    osChgPerms.write((chmodString).getBytes("ASCII"));
    osChgPerms.flush();
    osChgPerms.close();
    sh.waitFor();
} catch (InterruptedException e) {
    Log.d("2ndGuide", "InterruptedException." + e);
} catch(IOException e) {
    Log.d("2ndGuide", "IO Exception." + e);
}
Run Code Online (Sandbox Code Playgroud)

这段代码是在片段中执行的,但我认为这不会改变任何东西.

不幸的是,如果此代码适用于HONEYCOMB后设备,那么它无用,

osChgPerms.write((chmodString).getBytes("ASCII")); 
Run Code Online (Sandbox Code Playgroud)

抛出一个IOException: broken pipe on Android 2.3我真正需要它的地方.

事实上,我真的不知道问题是来自chmod还是来自执行它的方式.

任何让它工作的解决方案,或者让媒体播放器在HONEYCOMB之前工作而不改变文件权限?

Jar*_*ows 5

非常好的问题,我在这个问题上跑了一会儿!

使用Java + Android(用户必须拥有chmod):

文件夹:

Runtime.getRuntime().exec("chmod -R 777 " + FOLDERNAME);
Run Code Online (Sandbox Code Playgroud)

文件:

Runtime.getRuntime().exec("chmod 777 " + FILENAME);
Run Code Online (Sandbox Code Playgroud)

问题:如果他们没有"chmod"二进制文件怎么办?您必须下载并将其包含在您的应用程序或资产中.

使用Android NDK + JNI(用户不需要chmod但需要编译的ndk库):

/**
 * Change file permissions. Eg. chmod 777 FILE.
 * @param e Java environment.
 * @param c Java class.
 * @param file Path to file.
 * @param mode Permissions for the file.
 */
static jint executeCommand(JNIEnv *e, jclass __attribute__((__unused__))c, jstring file, jstring mode) {
    return (chmod(e->GetStringUTFChars(file, 0), strtol(e->GetStringUTFChars(mode, 0), 0, 8)));
}
Run Code Online (Sandbox Code Playgroud)

问题:确保使用APP_ABI:= all为所有设备编译NDK

对于Java(7+)+ Android API 9+(用户不需要chmod或libs):

/**
 * Change files to "0777"
 * @param path Path to file
 */
public static void changeFilePermission(final String path) {
    final File file = new File(path);
    file.setReadable(true, false);
    file.setExecutable(true, false);
    file.setWritable(true, false);
}
Run Code Online (Sandbox Code Playgroud)

问题:你的minSDK必须是9!