http://blog.csdn.net/datao_001/article/details/6259627
原文链接。。。
package cindy.android.test.synclistview;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
import android.widget.Toast;
public abstract class AbstructCommonActivity extends Activity {
private MyHandler handler = new MyHandler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
protected void handleOtherMessage(int flag){
}
public void sendMessage(int flag) {
handler.sendEmptyMessage(flag);
}
public void sendMessageDely(int flag,long delayMillis){
handler.sendEmptyMessageDelayed(flag, delayMillis);
}
public void showToast(String toast_message){
handler.toast_message = toast_message;
sendMessage(MyHandler.SHOW_STR_TOAST);
}
public void showToast(int res){
handler.toast_res = res;
sendMessage(MyHandler.SHOW_RES_TOAST);
}
private class MyHandler extends Handler {
public static final int SHOW_STR_TOAST = 0;
public static final int SHOW_RES_TOAST = 1;
private String toast_message=null;
private int toast_res;
@Override
public void handleMessage(Message msg) {
if (!Thread.currentThread().isInterrupted()) {
switch (msg.what) {
case SHOW_STR_TOAST:
Toast.makeText(getBaseContext(), toast_message, 1).show();
break;
case SHOW_RES_TOAST:
Toast.makeText(getBaseContext(), toast_res, 1).show();
break;
default:
handleOtherMessage(msg.what);
}
}
}
}
}
package cindy.android.test.synclistview;
import java.util.Vector;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class BookItemAdapter extends BaseAdapter{
private LayoutInflater mInflater;
private Context mContext;
private Vector<BookModel> mModels = new Vector<BookModel>();
private ListView mListView;
SyncImageLoader syncImageLoader;
public BookItemAdapter(Context context,ListView listView){
mInflater = LayoutInflater.from(context);
syncImageLoader = new SyncImageLoader();
mContext = context;
mListView = listView;
mListView.setOnScrollListener(onScrollListener);
}
public void addBook(String book_name,String out_book_url,String out_book_pic){
BookModel model = new BookModel();
model.book_name =book_name;
model.out_book_url = out_book_url;
model.out_book_pic = out_book_pic;
mModels.add(model);
}
public void clean(){
mModels.clear();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mModels.size();
}
@Override
public Object getItem(int position) {
if(position >= getCount()){
return null;
}
return mModels.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = mInflater.inflate(R.layout.book_item_adapter, null);
}
BookModel model = mModels.get(position);
convertView.setTag(position);
ImageView iv = (ImageView) convertView.findViewById(R.id.sItemIcon);
TextView sItemTitle = (TextView) convertView.findViewById(R.id.sItemTitle);
TextView sItemInfo = (TextView) convertView.findViewById(R.id.sItemInfo);
sItemTitle.setText(model.book_name);
sItemInfo.setText(model.out_book_url);
iv.setBackgroundResource(R.drawable.rc_item_bg);
syncImageLoader.loadImage(position,model.out_book_pic,imageLoadListener);
return convertView;
}
SyncImageLoader.OnImageLoadListener imageLoadListener = new SyncImageLoader.OnImageLoadListener(){
@Override
public void onImageLoad(Integer t, Drawable drawable) {
//BookModel model = (BookModel) getItem(t);
View view = mListView.findViewWithTag(t);
if(view != null){
ImageView iv = (ImageView) view.findViewById(R.id.sItemIcon);
iv.setBackgroundDrawable(drawable);
}
}
@Override
public void onError(Integer t) {
BookModel model = (BookModel) getItem(t);
View view = mListView.findViewWithTag(model);
if(view != null){
ImageView iv = (ImageView) view.findViewById(R.id.sItemIcon);
iv.setBackgroundResource(R.drawable.rc_item_bg);
}
}
};
public void loadImage(){
int start = mListView.getFirstVisiblePosition();
int end =mListView.getLastVisiblePosition();
if(end >= getCount()){
end = getCount() -1;
}
syncImageLoader.setLoadLimit(start, end);
syncImageLoader.unlock();
}
AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
DebugUtil.debug("SCROLL_STATE_FLING");
syncImageLoader.lock();
break;
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
DebugUtil.debug("SCROLL_STATE_IDLE");
loadImage();
//loadImage();
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
syncImageLoader.lock();
break;
default:
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
};
}
package cindy.android.test.synclistview;
public class BookModel {
public String book_id;
public String out_book_url;
public String author;
public String book_state_s;
public String leading_role;
public String update_time;
public String book_name;
public String out_book_pic;
public String sort_id;
public String last_update_section_title;
public String last_update_section_url;
public String introduction;
}
package cindy.android.test.synclistview;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
public class DebugUtil {
public static final String TAG = "DebugUtil";
public static final boolean DEBUG = true;
public static void toast(Context context,String content){
Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
}
public static void debug(String tag,String msg){
if (DEBUG) {
Log.d(tag, msg);
}
}
public static void debug(String msg){
if (DEBUG) {
Log.d(TAG, msg);
}
}
public static void error(String tag,String error){
Log.e(tag, error);
}
public static void error(String error){
Log.e(TAG, error);
}
}
package cindy.android.test.synclistview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class LoadStateView extends RelativeLayout{
ProgressBar progBar;
LinearLayout downLoadErrMsgBox;
TextView downLoadErrText;
Button btnListLoadErr;
public LoadStateView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onFinishInflate() {
// TODO Auto-generated method stub
super.onFinishInflate();
progBar = (ProgressBar) findViewById(R.id.progBar);
downLoadErrMsgBox = (LinearLayout) findViewById(R.id.downLoadErrMsgBox);
downLoadErrText = (TextView) findViewById(R.id.downLoadErrText);
btnListLoadErr = (Button) findViewById(R.id.btnListLoadErr);
}
public void startLoad(){
downLoadErrMsgBox.setVisibility(View.GONE);
progBar.setVisibility(View.VISIBLE);
}
public void stopLoad(){
progBar.setVisibility(View.GONE);
}
public void showError(){
downLoadErrMsgBox.setVisibility(View.VISIBLE);
progBar.setVisibility(View.GONE);
}
public void showEmpty(){
downLoadErrMsgBox.setVisibility(View.VISIBLE);
progBar.setVisibility(View.GONE);
}
public void setOnReloadClickListener(OnClickListener onReloadClickListener){
btnListLoadErr.setOnClickListener(onReloadClickListener);
}
}
package cindy.android.test.synclistview;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
public class SyncImageLoader {
private Object lock = new Object();
private boolean mAllowLoad = true;
private boolean firstLoad = true;
private int mStartLoadLimit = 0;
private int mStopLoadLimit = 0;
final Handler handler = new Handler();
private HashMap<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
public interface OnImageLoadListener {
public void onImageLoad(Integer t, Drawable drawable);
public void onError(Integer t);
}
public void setLoadLimit(int startLoadLimit,int stopLoadLimit){
if(startLoadLimit > stopLoadLimit){
return;
}
mStartLoadLimit = startLoadLimit;
mStopLoadLimit = stopLoadLimit;
}
public void restore(){
mAllowLoad = true;
firstLoad = true;
}
public void lock(){
mAllowLoad = false;
firstLoad = false;
}
public void unlock(){
mAllowLoad = true;
synchronized (lock) {
lock.notifyAll();
}
}
public void loadImage(Integer t, String imageUrl,
OnImageLoadListener listener) {
final OnImageLoadListener mListener = listener;
final String mImageUrl = imageUrl;
final Integer mt = t;
new Thread(new Runnable() {
@Override
public void run() {
if(!mAllowLoad){
DebugUtil.debug("prepare to load");
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(mAllowLoad && firstLoad){
loadImage(mImageUrl, mt, mListener);
}
if(mAllowLoad && mt <= mStopLoadLimit && mt >= mStartLoadLimit){
loadImage(mImageUrl, mt, mListener);
}
}
}).start();
}
private void loadImage(final String mImageUrl,final Integer mt,final OnImageLoadListener mListener){
if (imageCache.containsKey(mImageUrl)) {
SoftReference<Drawable> softReference = imageCache.get(mImageUrl);
final Drawable d = softReference.get();
if (d != null) {
handler.post(new Runnable() {
@Override
public void run() {
if(mAllowLoad){
mListener.onImageLoad(mt, d);
}
}
});
return;
}
}
try {
final Drawable d = loadImageFromUrl(/blog_article/mImageUrl/index.html);
if(d != null){
imageCache.put(mImageUrl, new SoftReference<Drawable>(d));
}
handler.post(new Runnable() {
@Override
public void run() {
if(mAllowLoad){
mListener.onImageLoad(mt, d);
}
}
});
} catch (IOException e) {
handler.post(new Runnable() {
@Override
public void run() {
mListener.onError(mt);
}
});
e.printStackTrace();
}
}
public static Drawable loadImageFromUrl(/blog_article/String url/index.html) throws IOException {
DebugUtil.debug(url);
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File f = new File(Environment.getExternalStorageDirectory()+"/TestSyncListView/"+MD5.getMD5(url));
if(f.exists()){
FileInputStream fis = new FileInputStream(f);
Drawable d = Drawable.createFromStream(fis, "src");
return d;
}
URL m = new URL(/blog_article/url/index.html);
InputStream i = (InputStream) m.getContent();
DataInputStream in = new DataInputStream(i);
FileOutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int byteread=0;
while ((byteread = in.read(buffer)) != -1) {
out.write(buffer, 0, byteread);
}
in.close();
out.close();
Drawable d = Drawable.createFromStream(i, "src");
return loadImageFromUrl(url);
}else{
URL m = new URL(/blog_article/url/index.html);
InputStream i = (InputStream) m.getContent();
Drawable d = Drawable.createFromStream(i, "src");
return d;
}
}
}
package cindy.android.test.synclistview;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class TestListViewActivity extends AbstructCommonActivity
implements AdapterView.OnItemClickListener{
ListView viewBookList;
BookItemAdapter adapter;
//ViewGroup listFolder;
LoadStateView loadStateView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewBookList = (ListView) findViewById(R.id.viewBookList);
adapter = new BookItemAdapter(this,viewBookList);
loadStateView = (LoadStateView) findViewById(R.id.downloadStatusBox);
loadStateView.setOnReloadClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
reload();
}
});
//listFolder = (ViewGroup) getLayoutInflater().inflate(R.layout.load_more, null);
//viewBookList.addFooterView(listFolder);
viewBookList.setAdapter(adapter);
viewBookList.setOnItemClickListener(this);
reload();
}
private void reload(){
adapter.clean();
loadStateView.startLoad();
new Thread(new Runnable(){
@Override
public void run() {
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadDate();
sendMessage(REFRESH_LIST);
//sendMessageDely(LOAD_IMAGE, 500);
}
}).start();
}
public void loadDate(){
for(int i=0;i<10;i++){
adapter.addBook("吞噬星空"+i,
"http://www.pfwx.com/bookinfo/11/11000.html",
"http://www.pfwx.com/files/article/image/11/11000/11000s.jpg");
adapter.addBook("仙逆"+i,
"http://www.pfwx.com/bookinfo/9/9760.html",
"http://www.pfwx.com/files/article/image/9/9760/9760s.jpg");
adapter.addBook("武动乾坤"+i,
"http://www.pfwx.com/bookinfo/13/13939.html",
"http://www.pfwx.com/files/article/image/13/13939/13939s.jpg");
adapter.addBook("凡人修仙传"+i,
"http://www.pfwx.com/bookinfo/3/3237.html",
"http://www.pfwx.com/files/article/image/3/3237/3237s.jpg");
adapter.addBook("遮天"+i,
"http://www.pfwx.com/bookinfo/11/11381.html",
"http://www.pfwx.com/files/article/image/11/11381/11381s.jpg");
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
private static final int REFRESH_LIST = 0x10001;
private static final int SHOW_LOAD_STATE_VIEW = 0x10003;
private static final int HIDE_LOAD_STATE_VIEW = 0x10004;
@Override
protected void handleOtherMessage(int flag) {
switch (flag) {
case REFRESH_LIST:
adapter.notifyDataSetChanged();
loadStateView.stopLoad();
if(adapter.getCount() == 0){
loadStateView.showEmpty();
}
break;
case SHOW_LOAD_STATE_VIEW:
loadStateView.startLoad();
break;
case HIDE_LOAD_STATE_VIEW:
loadStateView.stopLoad();
break;
default:
break;
}
}
}
终端切换到 <sdk>/tools/ 目录下执行 android 命令就可以把AVD Manager 打开了。 可是,如果你没有添加 <sdk>/tools 到你的环境变量中时,输入 android 回车后终端只会提示你
android:找不到命令
而只要在android前加上 ./ 就可以解决问题:
./android
更简单的办法是将 <sdk>/tools 路径添加进 PATH 环境变量。可以添加进用户级环境变量,也可以添加到系统环境变量中。通过命令或编辑文件均可,在这里我只提供一个办法,打开终端,输入:
sudo gedit /etc/environment
回车,在PATH=”………………….”的双引号中追加上:
:<sdk>/tools:<sdk>/platform-tools
比如:
:/opt/android-sdk/tools:/opt/android-sdk/platform-tools
注意,:是分隔符。
重启一下或者 source /etc/environment(立即生效) 在终端输入 android 回车就会有反应了。
安装Android NDK
下载Android NDK : http://developer.android.com/sdk/ndk/index.html
echo 解压缩得到android-ndk-r6b目录,即可。 tar -jxvf android-ndk-r6b-linux-x86.tar.bz2
也将其路径加入到source路径中
经过了上述步骤,在命令行下敲:
ndk-bulid
弹出如下的错误,而不是说ndk-build not found,就说明ndk环境已经安装成功了。
Android NDK: Could not find application project directory !
Android NDK: Please define the NDK_PROJECT_PATH variable to point to it.
/home/braincol/workspace/android/android-ndk-r5/build/core/build-local.mk:85: *** Android NDK: Aborting . Stop.
二、代码的编写
1.首先是写java代码
建立一个Android应用工程HelloJni,创建HelloJni.java文件:
HelloJni.java :
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.hellojni; import android.app.Activity; import android.widget.TextView; import android.os.Bundle; public class HelloJni extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ TextView tv = new TextView(this ); tv.setText( stringFromJNI() ); setContentView(tv); } /* A native method that is implemented by the * 'hello-jni' native library, which is packaged * with this application. */ public native String stringFromJNI(); /* This is another native method declaration that is *not* * implemented by 'hello-jni'. This is simply to show that * you can declare as many native methods in your Java code * as you want, their implementation is searched in the * currently loaded native libraries only the first time * you call them. * * Trying to call this function will result in a * java.lang.UnsatisfiedLinkError exception ! */ public native String unimplementedStringFromJNI(); /* this is used to load the 'hello-jni' library on application * startup. The library has already been unpacked into * /data/data/com.example.HelloJni/lib/libhello-jni.so at * installation time by the package manager. */ static { System.loadLibrary("hello-jni" ); } }
这段代码很简单,注释也很清晰,这里只提两点::
static{
System.loadLibrary("hello-jni"
);
}
表明程序开始运行的时候会加 载hello-jni, static区声明的代码会先于onCreate方法执行。如果你的程序中有多个类,而且如果HelloJni这个类不是你应用程序的入口,那么 hello-jni(完整的名字是libhello-jni.so)这个库会在第一次使用HelloJni这个类的时候加载。
public native String stringFromJNI();
public native String unimplementedStringFromJNI();
可以看到这两个方法的声明中有 native 关键字, 这个关键字表示这两个方法是本地方法,也就是说这两个方法是通过本地代码(C/C++)实现的,在java代码中仅仅是声明。
用eclipse编译该工程,生成相应的.class文件,这步必须在下一步之前完成,因为生成.h文件需要用到相应的.class文件。
2. 编写相应的C/C++代码
刚开始学的时候,有个问题会让人很困惑,相应的C/C++代码如何编写,函数名如何定义? 这里讲一个方法,利用javah这个工具生成相应的.h文件,然后根据这个.h文件编写相应的C/C++代码。
2.1 生成相应.h文件:
就拿我这的环境来说,首先在终端下进入刚刚建立的HelloJni工程的目录:
braincol@ubuntu:~$ cd workspace/android/NDK/hello-jni/
ls查看工程文件
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls
AndroidManifest.xml assets bin default.properties gen res src
可以看到目前仅仅有几个标准的android应用程序的文件(夹)。
首先我们在工程目录下建立一个jni文件夹:
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ mkdir jni
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls
AndroidManifest.xml assets bin default.properties gen jni res src
下面就可以生成相应的.h文件了:
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ javah -classpath bin -d jni com.example.hellojni.HelloJni
-classpath bin:表示类的路劲
-d jni: 表示生成的头文件存放的目录
com.example.hellojni.HelloJni 则是完整类名
这一步的成功要建立在已经在 bin/com/example/hellojni/ 目录下生成了 HelloJni.class的基础之上。
现在可以看到jni目录下多了个.h文件:
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ cd jni/
braincol@ubuntu:~/workspace/android/NDK/hello-jni/jni$ ls
com_example_hellojni_HelloJni.h
我们来看看com_example_hellojni_HelloJni.h的内容:
com_example_hellojni_HelloJni.h :
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_example_hellojni_HelloJni */ #ifndef _Included_com_example_hellojni_HelloJni #define _Included_com_example_hellojni_HelloJni #ifdef __cplusplus extern "C" { #endif /* * Class: com_example_hellojni_HelloJni * Method: stringFromJNI * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI (JNIEnv *, jobject); /* * Class: com_example_hellojni_HelloJni * Method: unimplementedStringFromJNI * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif
上面代码中的JNIEXPORT 和 JNICALL 是jni的宏,在android的jni中不需要,当然写上去也不会有错。
从上面的源码中可以看出这个函数名那是相当的长啊。。。。 不过还是很有规律的, 完全按照:java_pacakege_class_mathod 形式来命名。
也就是说:
Hello.java中 stringFromJNI() 方法对应于 C/C++中的 Java_com_example_hellojni_HelloJni_stringFromJNI() 方法
HelloJni.java中的 unimplementedStringFromJNI() 方法对应于 C/C++中的 Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI() 方法
注意下其中的注释:
Signature: ()Ljava/lang/String;
()Ljava/lang/String;
()表示函数的参数为空(这里为空是指除了JNIEnv *, jobject 这两个参数之外没有其他参数,JNIEnv*, jobject是所有jni函数必有的两个参数,分别表示jni环境和对应的java类(或对象)本身),
Ljava/lang/String; 表示函数的返回值是java的String对象。
2.2 编写相应的.c文件:
hello-jni.c :
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <string.h> #include <jni.h> /* This is a trivial JNI example where we use a native method * to return a new VM String. See the corresponding Java source * file located at: * * apps/samples/hello-jni/project/src/com/example/HelloJni/HelloJni.java */ jstring Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz ) { return (*env)->NewStringUTF(env, "Hello from JNI !" ); }
这里只是实现了 Java_com_example_hellojni_HelloJni_stringFromJNI方法,而 Java_com_example_hellojni_HelloJni_unimplementedStringFromJNI 方法并没有实现,因为在HelloJni.java中只调用了stringFromJNI()方法,所以 unimplementedStringFromJNI()方法没有实现也没关系,不过建议最好还是把所有java中定义的本地方法都实现了,写个空函数 也行啊。。。有总比没有好。
Java_com_example_hellojni_HelloJni_stringFromJNI() 函数只是简单的返回了一个内容为 "Hello from JNI !" 的jstring对象(对应于java中的String对象)。
hello-jni.c文件已经编写好了,现在可以把com_example_hellojni_HelloJni.h文件给删了,当然留着也行,只是我还是习惯把不需要的文件给清理干净了。
3. 编译hello-jni.c 生成相应的库
3.1 编写Android.mk文件
在jni目录下(即hello-jni.c 同级目录下)新建一个Android.mk文件, Android.mk 文件是Android 的 makefile文件,内容如下:
# Copyright (C) 2009 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE := hello-jni LOCAL_SRC_FILES := hello-jni.c include $(BUILD_SHARED_LIBRARY)
LOCAL_PATH := $(call my-dir)
一个Android.mk 文件首先必须定义好LOCAL_PATH变量。它用于在开发树中查找源文件。在这个例子中,宏函数’my-dir’, 由编译系统提供,用于返回当前路径(即包含Android.mk file文件的目录)。
include $( CLEAR_VARS)
CLEAR_VARS由编译系统提供,指定让GNU MAKEFILE为你清除许多LOCAL_XXX变量(例如 LOCAL_MODULE, LOCAL_SRC_FILES, LOCAL_STATIC_LIBRARIES, 等等...),
除LOCAL_PATH 。这是必要的,因为所有的编译控制文件都在同一个GNU MAKE执行环境中,所有的变量都是全局的。
LOCAL_MODULE := hello-jni
编译的目标对象,LOCAL_MODULE变量必须定义,以标识你在Android.mk文件中描述的每个模块。名称必须是唯一的,而且不包含任何空格。
注意:编译系统会自动产生合适的前缀和后缀,换句话说,一个被命名为'hello-jni'的共享库模块,将会生成'libhello-jni.so'文件。
重要注意事项:
如果你把库命名为‘libhello-jni’,编译系统将不会添加任何的lib前缀,也会生成 'libhello-jni.so',这是为了支持来源于Android平台的源代码的Android.mk文件,如果你确实需要这么做的话。
LOCAL_SRC_FILES := hello-jni.c
LOCAL_SRC_FILES变量必须包含将要编译打包进模块中的C或C++源代码文件。注意,你不用在这里列出头文件和包含文件,因为编译系统将会自动为你找出依赖型的文件;仅仅列出直接传递给编译器的源代码文件就好。
注意,默认的C++源码文件的扩展名是’.cpp’. 指定一个不同的扩展名也是可能的,只要定义LOCAL_DEFAULT_CPP_EXTENSION变量,不要忘记开始的小圆点(也就是’.cxx’,而不是’cxx’)
include $(BUILD_SHARED_LIBRARY)
BUILD_SHARED_LIBRARY表示编译生成共享库,是编译系统提供的变量,指向 一个GNU Makefile脚本,负责收集自从上次调用'include $(CLEAR_VARS)'以来,定义在LOCAL_XXX变量中的所有信息,并且决定编译什么,如何正确地去做。还有 BUILD_STATIC_LIBRARY变量表示生成静态库:lib$(LOCAL_MODULE).a, BUILD_EXECUTABLE 表示生成可执行文件。
braincol@ubuntu:~/workspace/android/NDK/hello-jni/jni$ cd ..
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ls
AndroidManifest.xml assets bin default.properties gen jni libs obj res src
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ ndk-build
Gdbserver : [arm-linux-androideabi-4.4.3] libs/armeabi/gdbserver
Gdbsetup : libs/armeabi/gdb.setup
Install : libhello-jni.so => libs/armeabi/libhello-jni.so
可以看到已经正确的生成了libhello-jni.so共享库了, 我们去 libs/armeabi/ 目录下看看:
braincol@ubuntu:~/workspace/android/NDK/hello-jni$ cd libs/
braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs$ ls
armeabi
braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs$ cd armeabi/
braincol@ubuntu:~/workspace/android/NDK/hello-jni/libs/armeabi$ ls
gdbserver gdb.setup libhello-jni.so
4. 在eclipse重新编译HelloJni工程,生成apk
eclipse中刷新下HelloJni工程,重新编译生成apk,libhello-jni.so共享库会一起打包在apk文件内。
在模拟器中看看运行结果:
注意:NDK R7版本自带的awk是64位的,在32位的机器上使用会出错。
将awk命令删除或重命名即可。
awk路径在:android-ndk-r7/prebuilt/linux-x86/bin/awk
================================================================================
Android NDK: Host 'awk' tool is outdated. Please define HOST_AWK to point to Gawk or Nawk !Add Starhayashih