使用此代码:
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());
}
}