Search code examples
c#androidunity-game-enginescoped-storage

Accessing Database stored in Internal Storage of Android Q


I would like to access the database that is stored in the Internal storage. I'm using the following code to do so.

db_connection_string = "URI=file:" + GetAndroidInternalFilesDir() + "/employee.db";
Debug.Log("db_connection_string" + db_connection_string);
db_connection = new SqliteConnection(db_connection_string);

Following is my GetAndroidInternalFilesDir function.

public static string GetAndroidInternalFilesDir()
{
    string[] potentialDirectories = new string[]
    {
        "/storage/Company",
        "/sdcard/Company",
        "/storage/emulated/0/Company",
        "/mnt/sdcard/Company",
        "/storage/sdcard0/Company",
        "/storage/sdcard1/Company"
    };

    if(Application.platform == RuntimePlatform.Android)
    {
        for(int i = 0; i < potentialDirectories.Length; i++)
        {
            if(Directory.Exists(potentialDirectories[i]))
            {
                return potentialDirectories[i];
            }
        }
    }
    return "";
}

The above code works fine in every device that is <Android10 but it fails with Android 11 and above. The SDK Version is set to 30 in my Unity3D. I have also tried changing it to 29 with no success. How can I fix this?

UPDATE:

I have used the following code to trigger the permission for scoped storage but still, it shows zero success.

void initiate()
{
    AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject packageManager = jc.Call<AndroidJavaObject>("getPackageManager");
    AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION");
    AndroidJavaObject launchIntent = packageManager.Call<AndroidJavaObject>("getLaunchIntentForPackage", packageManager);
    launchIntent = jo.Call<AndroidJavaObject>("setData", packageManager);
    jc.Call("startActivity", launchIntent);
}

Solution

  • if you want to search in listed directories (not in scope of your app) then you need a MANAGE_EXTERNAL_STORAGE permission. some doc in HERE