I want create programmatically symbolic link in my app. Is it possible in Android (4.4+)?
In Java we can use:
Path newLink = ...;
Path target = ...;
Here's a solution that worked for me, which returns true iff succeeded :
public static boolean createSymLink(String symLinkFilePath, String originalFilePath) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
Os.symlink(originalFilePath, symLinkFilePath);
return true;
}
final Class> libcore = Class.forName("libcore.io.Libcore");
final java.lang.reflect.Field fOs = libcore.getDeclaredField("os");
fOs.setAccessible(true);
final Object os = fOs.get(null);
final java.lang.reflect.Method method = os.getClass().getMethod("symlink", String.class, String.class);
method.invoke(os, originalFilePath, symLinkFilePath);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Or in Kotlin:
companion object {
@JvmStatic
fun createSymLink(symLinkFilePath: String, originalFilePath: String): Boolean {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Os.symlink(originalFilePath, symLinkFilePath)
return true
}
val libcore = Class.forName("libcore.io.Libcore")
val fOs = libcore.getDeclaredField("os")
fOs.isAccessible = true
val os = fOs.get(null)
val method = os.javaClass.getMethod("symlink", String::class.java, String::class.java)
method.invoke(os, originalFilePath, symLinkFilePath)
return true
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
}