try this code of your Application instance (you should write the class in manifest):
This code is copying content of assets/files folder to the cache folder of app (you can place other path in copyAssetFolder() function). Only when App is launched for the first time
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.preference.PreferenceManager;
public class MyApplication extends Application {
private static Context s_sharedContext;
@Override
public void onCreate () {
super.onCreate();
if (!PreferenceManager.getDefaultSharedPreferences(
getApplicationContext())
.getBoolean("installed", false)) {
PreferenceManager.getDefaultSharedPreferences(
getApplicationContext())
.edit().putBoolean("installed", true).commit();
copyAssetFolder(getAssets(), "files",
"/data/data/com.example.appname/files");
}
}
private static boolean copyAssetFolder(AssetManager assetManager,
String fromAssetPath, String toPath) {
try {
String[] files = assetManager.list(fromAssetPath);
new File(toPath).mkdirs();
boolean res = true;
for (String file : files)
if (file.contains("."))
res &= copyAsset(assetManager,
fromAssetPath + "/" + file,
toPath + "/" + file);
else
res &= copyAssetFolder(assetManager,
fromAssetPath + "/" + file,
toPath + "/" + file);
return res;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean copyAsset(AssetManager assetManager,
String fromAssetPath, String toPath) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(fromAssetPath);
new File(toPath).createNewFile();
out = new FileOutputStream(toPath);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
return true;
} catch(Exception e) {
e.printStackTrace();
return false;
}
}
private static void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…