android studio 修改jni-demo控制led,做来玩玩
cpp:
#include <jni.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <linux/gpio.h>
#include <android/log.h>
#define LOG_TAG "gpio jni"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
extern "C" {
JNIEXPORT jstring JNICALL Java_com_example_testjni_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
JNIEXPORT void JNICALL Java_com_example_testjni_MainActivity_gpioctlFromJNI(JNIEnv *env,jobject,jint i) {
// system("chmod 0666 /sys/class/leds/LEDGREEN/brightness"); //给权限
// LOGI("chmod 0666 /sys/class/leds/LEDGREEN/brightness");
if(i==1)
system("echo 0 > /sys/class/leds/LEDGREEN/brightness"); //red
else
system("echo 1 > /sys/class/leds/LEDGREEN/brightness"); //blue
}
java:
package com.example.testjni;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
import com.example.testjni.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
int i=1;
private Button button;
// Used to load the 'testjni' library on application startup.
static {
System.loadLibrary("testjni");
}
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Example of a call to a native method
button.setText(stringFromJNI());
i=~i;
gpioctlFromJNI(i);
}
});
}
/**
* A native method that is implemented by the 'testjni' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public native void gpioctlFromJNI(int i);
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
android:textAllCaps="false"
android:text="确认"/>
</androidx.constraintlayout.widget.ConstraintLayout>