Android NDK开发动态加载so示例源码

度娘搜到这篇博客,Android 动态加载 .SO

博文中只有部分代码,对拷贝so文件至系统目录的接口(

FileUtils.assetToFile(this, "libTestJNI.so", soFile);
)没有实现,搜索一番未得,发在这里给大家测试一下。

源码下载地址:http://download.csdn.net/detail/mnorst/8065011

package com.example.testtwolib;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {

	// 静态加载.so
	// static {
	// //System.loadLibrary("test2");
	// //System.loadLibrary("test");
	//
	// }

	private TextView mTextNum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mTextNum = (TextView) findViewById(R.id.num);

		// 动态加载.so
		load();
		// load2();

		int z = add(3, 4);
		mTextNum.setText("add=" + z);
	}

	private void load() {

		File dir = getDir("lib", Context.MODE_PRIVATE);
		File soFile = new File(dir, "libtest.so");
		FileUtils.assetToFile(this, "libtest.so", soFile);

		try {
			System.load(soFile.getAbsolutePath());
		} catch (Exception e) {
		}
	}

	private void load2() {

		File dir = getDir("lib", Context.MODE_PRIVATE);
		File soFile = new File(dir, "libtest2.so");
		FileUtils.assetToFile(this, "libtest2.so", soFile);

		try {
			System.load(soFile.getAbsolutePath());
		} catch (Exception e) {
		}
	}

	public static native int add(int x, int y);
}


package com.example.testtwolib;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;

public class FileUtils {

	public static void assetToFile(Context context, String name, File file) {
		AssetManager assetManager = context.getAssets();

		InputStream is;
		try {
			is = assetManager.open(name);
			java.io.ByteArrayOutputStream bout = new java.io.ByteArrayOutputStream();

			byte[] bufferByte = new byte[1024];
			int l = -1;
			while ((l = is.read(bufferByte)) > -1) {
				bout.write(bufferByte, 0, l);
			}
			byte[] rBytes = bout.toByteArray();
			bout.close();
			is.close();

			if (!file.exists()) {
				file.createNewFile();
			}

			DataOutputStream dos = new DataOutputStream(new FileOutputStream(
					file));
			dos.write(rBytes);
			dos.flush();
			dos.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}




你可能感兴趣的:(android,NDK开发,动态加载so,示例源码)