Including files in building apk application in Unity - android

How to add files and folders to the apk file when building it in unity.
What I need is to have some files and a folder to be present in the parent directory of the application ( android/data/com.company.product/files) after installing it on Android.

This is my code for copying files from streaming assets into android persist path:
using System.IO;
using UnityEngine;
public static class FileManager
{
public static string RereadFile(string fileName)
{ //copies and unpacks file from apk to persistentDataPath where it can be accessed
string destinationPath = Path.Combine(Application.persistentDataPath, fileName);
#if UNITY_EDITOR
string sourcePath = Path.Combine(Application.streamingAssetsPath, fileName);
#else
string sourcePath = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
#endif
//UnityEngine.Debug.Log(string.Format("{0}-{1}-{2}-{3}", sourcePath, File.GetLastWriteTimeUtc(sourcePath), File.GetLastWriteTimeUtc(destinationPath)));
//copy whatsoever
//if DB does not exist in persistent data folder (folder "Documents" on iOS) or source DB is newer then copy it
//if (!File.Exists(destinationPath) || (File.GetLastWriteTimeUtc(sourcePath) > File.GetLastWriteTimeUtc(destinationPath)))
{
if (sourcePath.Contains("://"))
{
// Android
WWW www = new WWW(sourcePath);
while (!www.isDone) {; } // Wait for download to complete - not pretty at all but easy hack for now
if (string.IsNullOrEmpty(www.error))
{
File.WriteAllBytes(destinationPath, www.bytes);
}
else
{
Debug.Log("ERROR: the file DB named " + fileName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
}
}
else
{
// Mac, Windows, Iphone
//validate the existens of the DB in the original folder (folder "streamingAssets")
if (File.Exists(sourcePath))
{
//copy file - alle systems except Android
File.Copy(sourcePath, destinationPath, true);
}
else
{
Debug.Log("ERROR: the file DB named " + fileName + " doesn't exist in the StreamingAssets Folder, please copy it there.");
}
}
}
StreamReader reader = new StreamReader(destinationPath);
var jsonString = reader.ReadToEnd();
reader.Close();
return jsonString;
}
}
I hope it helps.

Related

Fixing data path not found error with SQLite

I've got the sqlite db working in the editor just fine. However when using it in Android, I get an error saying data path not found.
I believe I have the needed libsqlite.so files in the correct plugins/ android folder and the other DLLs that the editor looks for.
Here is my code:
string filepath = Application.dataPath + "/" + "Players.db"; //.db
if(!File.Exists(filepath))
{
// if it doesn't ->
// open StreamingAssets directory and load the db ->
try {
WWW loadDB = new WWW ("jar:file://" + Application.persistentDataPath + "!/Assets/" + "StreamingAssets/Players.db"); // .db this is the path to your StreamingAssets in android
while (!loadDB.isDone) {
} // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
// then save to Application.persistentDataPath
File.WriteAllBytes (filepath, loadDB.bytes);
} catch (Exception ex) {
GameObject.Find ("Advice").GetComponent<Text> ().text = ex.Message;
}
}
You are using Application.DataPath to save files. In editor mode it refers to Assets folder but in android build it refers to APK package which is a compressed file and you have no access to it. So use Application.persistentDataPath instead.
string filepath = Application.persistentDataPath + "/" + "Players.db"; //.db

Android Cache folder is created as file

I am using Disk Cache folder for storing image files. It works perfectly, but after anyone performs Clean Data from his/her device the cache folder turns into a file.
Here is the code for creating cache directory
File myDiskCacheDir=getDiskCacheDir(this,IMAGE_CACHE_DIR);
diskCache=new MyDiskCache(this,myDiskCacheDir);
public static File getDiskCacheDir(Context context, String uniqueName) {
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||(!isExternalStorageRemovable()))
{
cachePath=getExternalCacheDir(context).getPath();
}
else {
cachePath=context.getCacheDir().getPath();
}
new File(cachePath).mkdirs();
return new File(cachePath + File.separator + uniqueName);
}
public static File getExternalCacheDir(Context context) {
if (Utils.hasFroyo()) {
return context.getExternalCacheDir();
}
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
File cacheDirFile=new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
cacheDirFile.mkdirs();
return cacheDirFile;
}
I am facing this problem in Android 4.2 and below only.
Use
new File(cachePath + "/").mkdirs();

How to extract files from .obb file?

in my application I downloaded the expansion file at Android->obb->packagename->main.1.packagename.obb .
Can someone explain to me, even with the sample code how to extract my files from it ?
I tried to use the APK Expansion Zip Library as :
ZipResourceFile expansionFile = APKExpansionSupport.getAPKExpansionZipFile(MainActivity.this, 3, 0);
for (ZipResourceFile.ZipEntryRO entry : expansionFile.getAllEntries())
Log.d("",entry.mFileName);
InputStream input = expansionFile.getInputStream(Environment.getExternalStorageDirectory().toString()
+ "/sdcard/Android/obb/com.example.project/main.3.com.example.project.obb/obb/file.zip/file.apk");
But expansionFile is always null.
The .obb file was created with Jobb, used on the folder obb/file.zip .
Solved with the following code:
final StorageManager storageManager = (StorageManager) getSystemService(STORAGE_SERVICE);
String obbPath = Environment.getExternalStorageDirectory() + "/Android/obb";
final String obbFilePath = obbPath + "/com.example.project/main.3.com.example.project.obb";
OnObbStateChangeListener mount_listener = new OnObbStateChangeListener() {
public void onObbStateChange(String path, int state) {
if (state == OnObbStateChangeListener.MOUNTED) {
if (storageManager.isObbMounted(obbFilePath)) {
Log.d("Main","Mounted successful");
String newPath = storageManager.getMountedObbPath(obbFilePath);
File expPath = new File(newPath+"/file.zip/file.apk");
Log.d("Main","File exist: " + expPath.exists());
}
}
}
};
storageManager.mountObb(obbFilePath, "key", mount_listener);
After mounting the .obb file , I can access my data in the path mnt/obb/myfolder .
I used this for reading a specific file from the obb:
In your AndroidManifest.xml:
<!-- Needed for reading the obb file -->
<provider
android:name=".extension.ZipFileContentProvider"
android:authorities="com.example.extension.ZipFileContentProvider"/>
ZipFileContentProvider:
public class ZipFileContentProvider extends APEZProvider {
#Override
public String getAuthority() {
return "com.example.extension.ZipFileContentProvider";
}
}
Get file URI:
final Uri CONTENT_URI = Uri.parse("content://" + "com.example.extension.ZipFileContentProvider");
Uri uri = Uri.parse(CONTENT_URI + "/drawable/" + name)
To create the obb file i used a gradle script (the res folder is in the same directory):
task createExpansionFile(type: Zip) {
from 'res'
entryCompression = ZipEntryCompression.STORED
archiveName = 'main' + '.' + '1' + '.' + 'com.example' + '.obb'
println archiveName
println relativePath(destinationDir)
println relativePath(archivePath)
}

Unity - Reading text files (Android & Web Player)

I'm trying to read a text file in Unity. I have problems.
In desktop, when I generate the Stand Alone, I need to copy manually the text file. I don't know how include inside my application.
In web application (and Android), I copy the file manually but my game can't find it.
This is my "Read" code:
public static string Read(string filename) {
//string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
string filePath = System.IO.Path.Combine(Application.dataPath, filename);
string result = "";
if (filePath.Contains("://")) {
// The next line is because if I use path.combine I
// get something like: "http://bla.bla/bla\filename.csv"
filePath = Application.dataPath +"/"+ System.Uri.EscapeUriString(filename);
//filePath = System.IO.Path.Combine(Application.streamingAssetsPath, filename);
WWW www = new WWW(filePath);
int timeout = 20*1000;
while(!www.isDone) {
System.Threading.Thread.Sleep(100);
timeout -= 100;
// NOTE: Always get a timeout exception ¬¬
if(timeout <= 0) {
throw new TimeoutException("The operation was timed-out ("+filePath+")");
}
}
//yield return www;
result = www.text;
} else {
#if !UNITY_WEBPLAYER
result = System.IO.File.ReadAllText(filePath);
#else
using(var read = System.IO.File.OpenRead(filePath)) {
using(var sr = new StreamReader(read)) {
result = sr.ReadToEnd();
}
}
#endif
}
return result;
}
My questions are:
How can I include my "text file" as a Game Resource?
Is something wrong on my code?
Unity offers a special folder called Resources where you can keep files and load them at runtime through Resources.Load
Resources.Load on Unity docs
Create a folder called Resources in your project, and put your files in it (in this case, you text file).
Here's an example. It assumes that you're sticking your file straight into the Resources folder (not a subfolder in Resources)
public static string Read(string filename) {
//Load the text file using Reources.Load
TextAsset theTextFile = Resources.Load<TextAsset>(filename);
//There's a text file named filename, lets get it's contents and return it
if(theTextFile != null)
return theTextFile.text;
//There's no file, return an empty string.
return string.Empty;
}

Where is my Excel file on Android saved?

I have this code which makes new Excel file.
The file is blank, it only creates a sheet.
Code goes like this
public void onClick(View v) {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Havaji");
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellValue("Hi there");
try{
FileOutputStream output = new FileOutputStream("Test2.xls");
workbook.write(output);
output.close();
}
...
Where is that file saved ?
How to manage to save a file on the location on the mobile device that i want?
How to create a directory where all the files are gonna be stored?
Here are a few methods you'll find useful for your purposes:
Creates all the directories along the path provided:
public static boolean createPath(String path) {
File pathFile = new File(path);
if (!pathFile.exists()) {
boolean result = pathFile.mkdirs();
if (!result) {
Log.e(TAG, "Unable to create directory path: " +
path);
return false;
}
}
if (!pathFile.isDirectory()) {
return false;
}
return true;
}
Returns the root of the external storage directory:
public static String extDirectory() {
File file = Environment.getExternalStorageDirectory();
return file.getAbsolutePath();
}
Returns the path to the root of an application's external storage directory:
public static String externalMyAppDataRoot(Context context) {
return externalAppDataRoot() + File.separatorChar
+ context.getPackageName() + File.separatorChar + "data";
}
Returns the path to the root of the Android application data directory:
public static String externalAppDataRoot() {
return extDirectory() + File.separatorChar + "Android/data";
}
I'm guessing that is being stored in /data/app//files/Test2.xls, though i'm not completely sure
I would try to pass in an absolute file path. If you want the file to be in the sdcard, i would use the Context.getExternalFilesDir to get the root path of the sdcard.

Categories

Resources