您的位置:首页 > 移动开发 > Android开发

Android-调用本地方法计算int数值相加结果显示在界面上/NDK-JNI开发实例(三)

2015-08-31 15:42 861 查看
Java调用本地方法计算int数值相加,得出的结果显示在界面上;

test1.c

<span style="font-family:KaiTi_GB2312;font-size:18px;">//
// Created by y_ulongji on 2015/8/31.
//
#include <jni.h>
JNIEXPORT jint JNICALL Java_com_example_yu_1longji_android25_MainActivity_add
(JNIEnv * env, jobject obj, jint i, jint j){
//C与Java中的int数值类型相同
int y = i + j;
//返回计算结果
return y;
}
</span>


生成的方法名:

<span style="font-family:KaiTi_GB2312;font-size:18px;">JNIEXPORT jint JNICALL Java_com_example_yu_1longji_android25_MainActivity_add(JNIEnv *, jobject, jint, jint);</span>


布局文件:

activity_main.xml

<span style="font-family:KaiTi_GB2312;font-size:18px;"><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=".MainActivity">

<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="30sp" />
<Button
android:layout_centerHorizontal="true"
android:text="计算"
android:textSize="30sp"
android:onClick="click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</RelativeLayout>
</span>


MainActivity.java

<span style="font-family:KaiTi_GB2312;font-size:18px;">package com.example.yu_longji.android25;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

static {
//so类库名
System.loadLibrary("test1");
}
//本地方法  参数为int类型
public native int add(int i, int j);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView tv = (TextView)findViewById(R.id.tv);
//调用本地add()方法;
tv.setText("4+5的和为:" + add(4, 5));

}

public void click(View view){
Toast.makeText(this, "4+5的和为:" + add(4, 5), Toast.LENGTH_LONG).show();
}

}
</span>


结果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息