Matthew Parker Matthew Parker - 10 months ago 162
Android Question

How do I refresh the android Gallery using Unity?

Tons of people asking this, and I've been through the first few pages of google search results and tried every solution I've found - None seem to work.

Seems to be because things have changed with different versions etc...

I have bought an asset from Unity Asset store, but the asset doesn't do this itself either. (I have already contacted the asset creator, but not heard anything back about this yet).

So... What is the current way to refresh the gallery? What works in the most recent versions of Android?


OK, so after a lot more head scratching, I found a solution.

        using (AndroidJavaClass jcUnityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        using (AndroidJavaObject joActivity = jcUnityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
        using (AndroidJavaObject joContext = joActivity.Call<AndroidJavaObject>("getApplicationContext"))
        using (AndroidJavaClass jcMediaScannerConnection = new AndroidJavaClass(""))
        using (AndroidJavaClass jcEnvironment = new AndroidJavaClass("android.os.Environment"))
        using (AndroidJavaObject joExDir = jcEnvironment.CallStatic<AndroidJavaObject>("getExternalStorageDirectory"))
            jcMediaScannerConnection.CallStatic("scanFile", joContext, new string[] { Path }, null, null);

Path should be equal to the absolute path of your image. Insert more path's into the string[] as required. Have tested this on Android 6.0.1 and works great!