我的APP中有一个JAVA和一个JNI层 是否可以从Java层向系统消息池发送消息,然后在JNI层中获取消息?
出于某种原因,我无法直接从Java调用JNI方法,我必须在Android中找到类似Windows的WndProc的消息方法。
答案 0 :(得分:0)
您可以使用套接字在Java和JNI之间进行通信。在JNI中设置套接字服务器以监听客户端连接,然后使用套接字以Java连接到服务器。
JNI中的套接字服务器。
struct sockaddr_in serv_addr;
int sockfd, connfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(6666);
bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(sockfd, 10);
while (1) {
connfd = accept(sockfd, (struct sockaddr*)NULL, NULL);
time_t result;
time(&result);
cout << "connecting from java " << ctime(&result);
char buffer[1024] = { 0 };
read(connfd, buffer, sizeof(buffer)/sizeof(char));
cout << "receive command... " << buffer << endl;
close(connfd);
if (strcmp(buffer, "END") == 0) {
cout << "socket thread terminate" << endl;
break;
}
}
Java中的套接字客户端
for (int i = 0; i < 3; i++) {
try {
Socket socket = new Socket(Inet4Address.getByName("localhost"), 6666);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
switch (i) {
case 0:
writer.write("ADD");
break;
case 1:
writer.write("SUB");
break;
case 2:
writer.write("END");
break;
default:
break;
}
Thread.sleep(2000);
writer.flush();
socket.close();
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}