My Target
- I'm coding an android studio project with some c++ code
- I want to update UI within c++ code
My Code
The code is as follows:
- MainActivity.java:
public class MainActivity extends AppCompatActivity {
// Used to load the 'davdmnn' library on application startup.
static {
System.loadLibrary("davdmnn");
}
private ActivityMainBinding binding;
private TextView tv;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Example of a call to a native method
tv = binding.sampleText;
String path = this.getFilesDir() + File.separator;
stringFromJNI(path);
}
/**
* A native method that is implemented by the 'davdmnn' native library,
* which is packaged with this application.
*/
public native String stringFromJNI(String path);
public void sendMessage(int id) {
tv.setText(id);
}
}
- native-lib.cpp
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_davdmnn_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */, jstring path) {
for (int i = 0; i < 100; i++){
// doing sth
// update tv, like tv.setText(i)
}
}
My Question
- I notice my question is related to this one. It uses a handler object to udpate UI, which is good for me.
- However, to use the solution of the related question, the attribute
tv
and methodsendMessage
must be static, which is not what I want. - So is there any way that I can pass the object (like
this
in java) into C++ methodJava_com_example_davdmnn_MainActivity_stringFromJNI
, or any other solutions?