apk携带资源之raw & assets
wo-07 10-14 dfeixtay or
/res/raw & /assets 携带资源
在android开发中,总有一些资源是想要随着安装包apk携带的,这些资源如数据库文件,文本,mp3等等。最早的做法是,在prebulid过程中,修改mk文件,将指定文件提前拷贝到系统某一文件夹目录下。这样的做法,既不科学也不美观还不安全,处于对代码的洁癖,我终于在不太忙的时候把这些资源文件带在自己的apk下。
之前说过没,由于提升速度,从文本解析调整为数据库查询。在携带文件时,这两种文件本没有不同,只是这里要讲一点inputstream的时候,二进制文件的db文件,和纯文本文件txt的方式可以不同,原因好像是,纯文本是按照unicode编码的,是16位16位的传的,二进制文件是8位传的。又想到之前ftp传输的时候,也是写的二进制传输。
言归正传,无论是raw文件夹还是assets文件夹,都是在生成apk的时候不编译而直接携带在apk的压缩包中的,这可以打开apk检验。这想必也是raw的得名。
提取的方法都是从inputstream转,转成什么形式的,要看对inputstream的操作,下篇也许会讲。具体的过程是:
private void getRaw(){ File target = new File("/data/data/com.android.");// InputStream in = this.getResources().openRawResource(R.raw.weather_db);// try {// } catch (IOException e1) {// // TODO Auto-generated catch block// e1.printStackTrace();// } InputStream in = null; OutputStream out = null; BufferedInputStream bin = null; BufferedOutputStream bout = null; try{ ////////////////////////////////////////////////////////////////////// int xx = 1;//R.raw.parse_weather_db_aa; xx+=1; try{ in = getResources().openRawResource(xx); }catch(Exception e){ e.printStackTrace(); } out = new FileOutputStream(target); bin = new BufferedInputStream(in); bout = new BufferedOutputStream(out); byte[] b = new byte[1024]; int len = bin.read(b); while (len != -1){ bout.write(b, 0, len); len = bin.read(b); }// exec("chmod 777 "+target.getAbsolutePath()); } catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try{ if (bin != null){ bin.close(); } if (bout != null){ bout.close(); } } catch (IOException e){ e.printStackTrace(); } } } private void getAsset(){// if(WeatherWidget.loadRunning(this, "FirstSetup")){ if(true){ WeatherWidget.saveRunning(this, false, "FirstSetup"); File databs = new File("/data/data/com.android."); if(!databs.exists()){ databs.mkdir(); } InputStream in = null; OutputStream out = null; BufferedInputStream bin = null; BufferedOutputStream bout = null; AssetManager am = getAssets(); String asName = "parse_weather_db_aa"; while(true){ try{ in = am.open(asName); out = new FileOutputStream(databs.getPath()+"/weather_db"); asName = nextAsset(asName); bin = new BufferedInputStream(in); bout = new BufferedOutputStream(out); byte[] b = new byte[8192]; int len = bin.read(); while (len != -1){ bout.write(b, 0, len); len = bin.read(b); } continue; } catch (FileNotFoundException e){ e.printStackTrace(); try{ if (bin != null){ bin.close(); } if (bout != null){ bout.close(); } break; } catch (IOException ee){ ee.printStackTrace(); } break; } catch (IOException e){ e.printStackTrace(); try{ if (bin != null){ bin.close(); } if (bout != null){ bout.close(); } break; } catch (IOException eee){ eee.printStackTrace(); } break; } } } }