標籤:應用 jni class
歡迎轉載,務必註明出處:http://blog.csdn.net/wang_shuai_ww/article/details/44458553
源碼:http://download.csdn.net/detail/u010406724/8515377
本篇介紹怎麼使用前面建立好的庫檔案。
要使用JNI庫檔案,那麼首先我們是需要把它載入到系統中,並對其定義介面,供給應用來調用。
建立一個工程,我的工程名為RealArmTest,過程就省略了,完成後再在src下建立一個類,不繼承其他類,包名為realarm.hardware,建立的類名為HardwareControl。代碼如下:
package realarm.hardware;public class HardwareControl {public native int LedSetState(int ledNum,int ledState);static {System.loadLibrary("LedJni");}}
具體的工程如:
主activity檔案源碼如下:
package com.example.realarmtest;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.ToggleButton;import realarm.hardware.HardwareControl;;public class MainActivity extends Activity {private HardwareControl MyLedTest = null;private ToggleButton btnLed;private ImageView imageLed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnLed = (ToggleButton) findViewById(R.id.btnLed); imageLed = (ImageView) findViewById(R.id.imageLed); MyLedTest = new HardwareControl(); MyLedTest.LedSetState(0, 0); imageLed.setImageResource(R.drawable.bulboff); btnLed.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if(btnLed.isChecked()){imageLed.setImageResource(R.drawable.bulbon);MyLedTest.LedSetState(0, 1);}else {imageLed.setImageResource(R.drawable.bulboff);MyLedTest.LedSetState(0, 0);}}}); }}
是不是發現更簡潔了,也容易理解,O(∩_∩)O。
布局檔案為:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.ledtest.MainActivity" > <ToggleButton android:id="@+id/btnLed" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/imageLed" android:layout_alignRight="@+id/imageLed" android:layout_centerVertical="true" android:textOff="開燈" android:textOn="關燈" /> <ImageView android:id="@+id/imageLed" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/btnLed" android:layout_centerHorizontal="true" android:layout_marginBottom="22dp" android:src="@drawable/bulboff" /></RelativeLayout>
另外還需要資源圖片,這裡就沒法貼出來了,需要的去上面提供的地址下載完整工程源碼就有了。
最後願看這些系列文章的朋友都能對Android驅動到上層應用有一定的瞭解。
Android 4.4.2 動態添加JNI庫方法記錄 (二 app應用程式層)