Reputation: 1407
i am new to ndk programming and have a try to make a project. My project's purpose is to build a client that i can use the button's listener to call the native method of socket programming.And,there is server running already in the android. And everything runs okay when i build it and export it as the apk.But,unfortunately,after i install the apk and try to run it.The system prompt that:Unfortunately,the NativeSocket has stopped. And the following is my code: 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.mk:
LOCAL_PATH := $(call 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);
}
Upvotes: 0
Views: 6701
Reputation: 1570
You create button reference in onCreate method after setContentView ndk error never gives force close only shutdown vm.
Upvotes: 1
Reputation: 12927
I'm not sure if this is needed in this case - but have you tried adding <uses-permission android:name="android.permission.INTERNET" />
to your AndroidManifest.xml
file?
Also what is the exact error/exception and the call stack on crash? You can view it in DDMS or with adb logcat
on commandline.
Also - verify return values from C functions and log appropriate error message. Use <android/log.h>
for that.
Upvotes: 0