我正在使用NDK来实现我的Android应用程序, 我的C代码中有一个无限循环来通过socket发送和recv,然后我将这个传输的数据存储在一个与我的java代码共享的变量中,现在我需要在textview上在线看到这个变量,但我可以&#39 ;因为循环在C代码里面而不是在doInBackground()中的java ...并且它需要像那样,所以我想知道如何在我的C代码循环中调用PublishProgress,或者直接赋值变量来自C ...的文本视图
public class ClientTask extends AsyncTask<Void, Long, String>
{
private TextView textStatus;
private TextView textStatus2;
private InetAddress serverAdress;
long dif; // This is my shared variable between c and java
public native String clientFromJNI();
static {
System.loadLibrary("hello-jni");
}
private static final int PORT = 1234;
public ClientTask(View textStatus,View textStatus2 , InetAddress serverAdress)
{
this.textStatus = (TextView) textStatus;
this.textStatus2 = (TextView) textStatus2;
this.serverAdress = serverAdress;
}
@Override
protected String doInBackground(Void... params)
{
//publishProgress(dif);
/* // I tried this to call publishProgress frequently by another thread but it did't work well
new Thread(new Runnable() {
public void run(){
while (true) {
publishProgress(dif);
}
}
}).start();
*/
return clientFromJNI();
}
@Override
protected void onPostExecute(String result)
{
setTextStatus("CLI: " + result );
}
@Override
protected void onProgressUpdate(Long... progress) {
textStatus2.setText(Long.toString(progress[0]));
// textStatus.setText(Long.toString(progress[0]));
}
这是我的C代码
JNIEXPORT jstring JNICALL
Java_com_example_hellojni_ClientTask_clientFromJNI(JNIEnv* env, jobject obj )
{
jfieldID fid;
jmethodID mid;
jclass myclass;
jclass cls = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env,cls,"dif","J");
// mid = (*env)->GetMethodID(env,cls,"publishProgress","()V");
//I don't know how to get publishProgress if it is possible
int connfd;
short port;
struct sockaddr_in servaddr, cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
port=1234;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(port);
servaddr.sin_addr.s_addr = inet_addr("192.168.49.1");
connfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
connect(connfd, (struct sockaddr *) &servaddr,sizeof(servaddr));
long now;
char str[16];
while (1)
{
read(connfd, str, 16 );
sscanf(str,"%lu",&now);
(*env)->SetLongField(env, obj ,fid , now);
//(*env)->CallVoidMethod(env,obj,); I wish here I can call publishProgress but I don't know how, please help me!
}
close (connfd);
return (*env)->NewStringUTF(env, str);
}
我知道在没有NDK的情况下实现这个很容易,但是我需要用C做这个,请帮助我。