2012-09-10 56 views
1

我已经知道“libs”项目文件夹中的Android应用程序库被写到/ data/data/[package_name]/lib文件夹中。在运行期间,如果需要,它们将从此位置加载。Android。在运行时将库文件写入lib文件夹

我正在写出租车司机android应用程序。如果需要,我们决定将其作为通过互联网进行更新的模块包来执行。所以如果有更新只需要更新文件但不是整个apk。这已经起作用了!但我们计划添加地图,以便司机可以在其中的一个帮助下建立出租车驱动器根目录并在屏幕上查看它。

我开始在Android上查看Yandex地图工具包。问题是这个工具包有一个本地库(甚至是它的两个版本,用于不同的硬件),它是在运行时通过System.loadLibrary()加载的。我希望这些.so文件作为模块也通过互联网加载,所以我需要一种方法将我的文件写入我的应用程序的/ data/data/[package_name]/lib文件夹中。那可能吗?

+0

也许扩展库是合适的吗? http://developer.android.com/guide/google/play/expansion-files.html – schwiz

+0

只读了一些东西。认为这没有帮助。 –

+0

你读过这个问题:http://stackoverflow.com/questions/11582717/android-can-write-to-lib-dir –

回答

1

使用此代码:

public class MainActivity extends Activity { 
    private final static int FILE_WRITE_BUFFER_SIZE = 32256; 
    String[] libraryAssets = {"libmain.so"}; 
    static MainActivity instance; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     instance = this; 
     File libs = getApplicationContext().getDir("libs", 0); 
     File libMain = new File(libs, libraryAssets[0]); 
     File input = new File(Environment.getExternalStorageDirectory(), libraryAssets[0]); 
     if(libMain.exists()){ 
      Log.v("Testing", "exist"); 
     }else{ 
      try { 
       InputStream is = new BufferedInputStream(new FileInputStream(input), FILE_WRITE_BUFFER_SIZE); 
       if(streamToFile(is, libMain)){ 
        Log.v("Testing", "File copied"); 
       } 
      } catch (FileNotFoundException e) { 
        Log.v("Testing", e.toString()); 
      } catch (IOException e) { 
        Log.v("Testing", e.toString()); 
      } 
     Log.v("Testing", libMain.getAbsolutePath()); 
     } 
    } 

    private boolean streamToFile(InputStream stm, File outFile) throws IOException{ 
     byte[] buffer = new byte[FILE_WRITE_BUFFER_SIZE]; 
     int bytecount; 
     OutputStream stmOut = new FileOutputStream(outFile, false); 
     while ((bytecount = stm.read(buffer)) > 0){ 
      stmOut.write(buffer, 0, bytecount); 
     } 
     stmOut.close(); 
     stm.close(); 
     return true; 
    } 

    public static Context getContext(){ 
      return instance; 
    } 
} 

而在你需要加载库类:

private static File libMain = new File(MainActivity.getContext().getDir("libs", 0), "libmain.so"); 

static{ 
    try { 
     System.load(libMain.getAbsolutePath()); 
    }catch(Exception e){ 
     Log.v(Tag, e.toString()); 
    }catch(UnsatisfiedLinkError e){ 
     Log.v(Tag, e.toString()); 
    } 
}