15 数据在安卓设备上的存储,加载

时间:2021-10-11 04:44:17

存储和加载:

public void ConnectToSqlite (string DBName)
    {   //判断名字是否规范,如果不规范就加上后缀
        if (!DBName.Contains (".sqlite")) {
            DBName  = ".sqlite";
        }
        //如果运行在编辑器中
        #if UNITY_EDITOR
        //获取路径
        sqlitePath = "Data Source ="   Application.streamingAssetsPath   "/"   DBName;
        //实例连接对象
        connection = new SqliteConnection (sqlitePath);
        //如果运行在Android设备中
        #elif UNITY_ANDROID
        //数据库连接的字符串
        string connectionStr = "URI = file:"   Application.persistentDataPath   "/"   DBName;
        //Android APK中数据库文件的路径
        string androidPath = "jar:file://"   Application.dataPath   "!/assets/"   DBName;
        //Android沙盒路径
        string androidFilePath = Application.persistentDataPath   "/"   DBName;
        //如果Android项目源文件中不存在数据库文件,说明没有加载过,需要加载
        if(!File.Exists(androidFilePath))
        {
        //从APK路径拿到Sqlite数据库文件,下载
        WWW www = new WWW(androidPath);
        //下载未完成时,保持等待
        while(!www.isDone){}
        //下载完成,IO流写入到沙盒路径
        File.WriteAllBytes(androidFilePath, www.bytes);
        }
        //实例连接对象
        connection = new SqliteConnection(connectionStr);
        #endif  

        //创建数据库命令对象
        command = connection.CreateCommand ();
        try {
            //打开数据库
            connection.Open ();
        } catch (System.Exception ex) {
            //输出报错信息
            print (ex);
        }
    }