2012年6月20日 星期三

[Example] [Android] [JAVA] JNI & NDK應用_BMI

JNI & NDK應用_BMI
JNI會將使用者輸入的身高體重傳到C
真正計算是由C來實作
C會將算完的答案回傳到JAVA
JAVA再將其顯示在UI上

流程方法
藉由java撰寫native method,JNI即可在Java中呼叫C寫的程式
C的程式藉由NDK包成.so檔,就可以被JNI呼叫

程式流程
1). (java) 撰寫native method,不需實做

2). 將寫好的.java檔,編成.class檔,再轉成.h檔

3). (C) 撰寫C程式碼,實做.h中的function標頭

4). 撰寫NDK需要的Android.mk

5). 利用NDK將C程式碼轉成.so檔

6). (java) 利用JNI呼叫C的程式















//=============================================================
[Main.java]
package com.jni;

import java.text.DecimalFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {
 double height, weight;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  Button button = (Button) findViewById(R.id.button_submit);
  button.setOnClickListener(calbmi);

 }

 private OnClickListener calbmi = new OnClickListener() {

  @Override
  public void onClick(View v) {
   DecimalFormat nf = new DecimalFormat("0.00");
   EditText fieldheight = (EditText) findViewById(R.id.edit_height);
   EditText fieldweight = (EditText) findViewById(R.id.edit_weight);
   
   try {
    height = Double.parseDouble(fieldheight.getText().toString());
    weight = Double.parseDouble(fieldweight.getText().toString());
   } catch (NumberFormatException e) {
    // Toast.makeText(v.getContext(),
    // "Please submit height and weight.", Toast.LENGTH_LONG)
    // .show();
    openOptionsDialog();
   }

   if (height == 0 || weight == 0) {
    openOptionsDialog();
   } 
   else {
    TextView bmi = (TextView) findViewById(R.id.text_result);
    double bmi_value = new Bmi().calbmi(height, weight);
    bmi.setText("Your BMI is " + nf.format(bmi_value));
   }
  }
 };

 private void openOptionsDialog() {
  AlertDialog.Builder dialog = new AlertDialog.Builder(Main.this);
  dialog.setTitle(R.string.dialog_title);
  dialog.setMessage(R.string.dialog_msg);
  dialog.setPositiveButton(R.string.dialog_btn,
    new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialoginterface, int i) {
     }
    });
  dialog.show();
 }


}


[Bmi.java]
package com.jni;

public class Bmi {
 public native String stringFromJNI();
 public native double calbmi(double height, double weight);
 static{
  System.loadLibrary("cal_bmi_c");
 }
}




參考資料:
[Android] [JAVA] JNI & NDK

沒有留言:

張貼留言