我是ndk编程的新手,并尝试制作一个项目。我的项目的目的是构建一个客户端,我可以使用按钮的监听器来调用套接字编程的本机方法。并且,android中已经有服务器运行。当我构建它并将其导出为apk时,一切运行正常。但不幸的是,在我安装apk并尝试运行它之后。系统提示:不幸的是,NativeSocket已停止。以下是我的代码:NativeSocketActivity.java:
package gz.kaiwii;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class NativeSocketActivity extends Activity {
/** Called when the activity is first created. */
final Button button = (Button) findViewById(R.id.button1);
/*static*/
static{
System.loadLibrary("NativeSocket");
}
/*native method stuff*/
static native void start();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
start();
}
});
}
}
Android.门口:
LOCAL_PATH:= $(调用my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := NativeSocket
### Add all source file names to be included in lib separated by a whitespace
LOCAL_SRC_FILES := NativeSocket.c
include $(BUILD_SHARED_LIBRARY)
NativeSocket.c:
#include <string.h>
#include <jni.h>
/* Make the necessary includes and set up the variables. */
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdlib.h>
JNIEXPORT void JNICALL Java_gz_kaiwii_NativeSocketActivity_start
(JNIEnv *env, jclass jclss)
{
int sockfd;
int len;
struct sockaddr_un address;
int result;
char ch = 'A';
/* Create a socket for the client. */
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
/* Name the socket, as agreed with the server. */
address.sun_family = AF_UNIX;
strcpy(address.sun_path, "server_socket");
len = sizeof(address);
/* Now connect our socket to the server's socket. */
result = connect(sockfd, (struct sockaddr *)&address, len);
/*
if(result == -1) {
perror("oops: client1");
exit(1);
}
*/
/* We can now read/write via sockfd. */
write(sockfd, &ch, 1);
read(sockfd, &ch, 1);
/*
printf("char from server = %c\n", ch);
*/
close(sockfd);
}
我不确定在这种情况下是否需要这个 - 但你尝试将<uses-permission android:name="android.permission.INTERNET" />
添加到你的AndroidManifest.xml
文件中吗?
还有什么是确切的错误/异常以及崩溃时的调用堆栈?您可以在DDMS中或在命令行上使用adb logcat
查看它。
另外 - 验证C函数的返回值并记录相应的错误消息。使用<android/log.h>
。
您在setContentView ndk错误之后在onCreate方法中创建按钮引用永远不会强制关闭仅关闭vm。