包含so 文件到APK的小技巧 (这个内容不是合理的做法,请查阅我关于NDK 1.6的博文来讨论Google 的推荐做法)

来源:互联网 发布:淘宝打折怎么取消 编辑:程序博客网 时间:2024/04/27 15:55

 

package com.example.android.simplejni;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class SimpleJNI extends Activity {
 
 
   
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        File file=new File("/data/data/com.example.android.simplejni/files/libsimplejni.so");
        if(file.exists()== false) // 非常有用

      {
    
       
        try { 
               InputStream is = getAssets().open("libsimplejni.so");           
              int size =  is.available();
              byte[] buffer = new byte[size];
               is.read(buffer);
             
               
              FileOutputStream fos = openFileOutput("libsimplejni.so", Activity.MODE_WORLD_WRITEABLE);  
              fos.write(buffer);
              fos.close();
               
               is.close();
          } catch (IOException e) {
              // Should never happen!
              throw new RuntimeException(e);
          }
        }
          loadlib();
         
        TextView tv = new TextView(this);
        //int sum = Native.add(2, 3);
        int sum = add(2, 3, "Hello");
        tv.setText("2 + 3 = " + Integer.toString(sum));
        setContentView(tv);
    }
     
    public void jShowText(String s) {
  Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
 }
    public native int add(int a, int b, String st);
    void loadlib() {
     // The runtime will add "lib" on the front and ".o" on the end of
     // the name supplied to loadLibrary.
       // System.load("/data/arcsoft/libsimplejni.so");
     System.load("/data/data/com.example.android.simplejni/files/libsimplejni.so");
     
    }
}      

 

 

代码关键有3点:

1:把so放到assert目录

2:在onCreate里面 过渡一下资源位置。(担千万不要反复去刷新这个文件,否则会找出 JNI函数出错)

3:把load jni的工作 防一个函数,而不是static。