Android - create symbolic link in the app

前端 未结 1 823
再見小時候
再見小時候 2021-01-13 03:53

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 = ...;
         


        
1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 04:30

    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
        }
    }
    

    0 讨论(0)
提交回复
热议问题