android驅動學習入門-android應用怎麼呼叫驅動2
android應用怎麼呼叫驅動的結構層次:
android應用
|| 通過native實現
|
C/C++程式碼
|
| 通過open(close、ioctl、write、read)操作裝置
|
C裝置驅動
從上面可以看得出,上層android應用要呼叫底層驅動,簡單的方式就是,先通過native呼叫C/C++,再通過open(close、ioctl、write、read)動作,操作驅動,就是那麼一個過程。
上一篇文章已經說過:C/C++怎麼呼叫驅動程式http://blog.csdn.net/menghnhhuan/article/details/7428693
下面說一下android應用是怎麼通過native呼叫C/C++程式碼的,可以將native方法比作Java程式同C程式的介面,其實現步驟:
1、在Java中宣告native()方法,然後編譯;
2、用javah產生一個.h檔案;
3、寫一個.c檔案實現native匯出方法,其中需要包含第二步產生的.h檔案(注意其中又包含了JDK帶的jni.h檔案);
4、將第三步的.c檔案編譯成動態連結庫檔案.SO;
5、在Java中用System.loadLibrary()方法載入第四步產生的動態連結庫檔案,這個native()方法就可以在Java中被訪問了。
首先建立一個android專案,寫一個程式碼控制這個led的亮滅,程式碼如下:
public class NativeExampleActivity extends Activity { TextView textView01; private Button btnStart; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnStart = (Button) this.findViewById(R.id.btnStart); btnStart.setOnClickListener(clickButtonStart); textView01 = (Button) this.findViewById(R.id.btnStart); } private OnClickListener clickButtonStart = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //textView01.setText("led state: "+ledFunction(0)); textView01.setText("led state: "+ledFunction(1)); } }; static { try { System.loadLibrary("org_natives_example_NativeExampleActivity");//載入庫檔案,系統會自動處理成lib***.so } catch (Throwable t) { } } public native int ledFunction(int a);//native方法,控制led的亮滅 }
然後在工程的bin/classes目錄下在cmd中執行javah -jni org.natives.example.NativeExampleActivity,
就會在根目錄下得到一個org_natives_example_NativeExampleActivity.h的檔案
然後根據標頭檔案的內容編寫org_natives_example_NativeExampleActivity.c檔案
#include "com_hode_hodeframework_modelupdate_CheckFile.h"
JNIEXPORT jint JNICALL Java_org_natives_example_NativeExampleActivity_ledFunction(JNIEnv *, jobject, jint a)
{
int fd;
int ret;
fd = open("/dev/vib",O_RDWR);//Open device ,get the handle
if(a==0)
ioctl(fd,0x22); //call the output function to on LEDs
else
ioctl(fd,0x11); //call the output function to off LEDs
ret = close(fd); //close device
return a;
}
之後編譯生成so檔案如“liborg_natives_example_NativeExampleActivity.so”,名稱與System.loadLibrary("org_natives_example_NativeExampleActivity")中的名稱一致
Android.mk檔案如下:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_PRELINK_MODULE := false
LOCAL_MODULE := liborg_natives_example_NativeExampleActivity
LOCAL_MODULE_TAGS := optional
LOCAL_SRC_FILES := org_natives_example_NativeExampleActivity.c
LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog
LOCAL_SHARED_LIBRARIES := libutils
include $(BUILD_SHARED_LIBRARY)
把編譯生成的庫.so和之前的驅動.ko檔案push到手機,下載應用,led就可以跑起來了。