/
android.c
75 lines (63 loc) · 1.68 KB
/
android.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <jni.h>
#include <android/log.h>
#include "network.h"
network* client_init(port_t port);
int client_run(network *n);
int pfd[2];
void* stdio_thread(void *useradata)
{
ssize_t readSize;
char buf[1024];
while ((readSize = read(pfd[0], buf, sizeof buf - 1)) > 0) {
if (buf[readSize - 1] == '\n') {
--readSize;
}
buf[readSize] = 0;
__android_log_write(ANDROID_LOG_VERBOSE, "newnode", buf);
}
return NULL;
}
void start_stdio_thread()
{
setvbuf(stdout, NULL, _IOLBF, 0);
setvbuf(stderr, NULL, _IOLBF, 0);
pipe(pfd);
dup2(pfd[1], 1);
dup2(pfd[1], 2);
pthread_t t;
if (pthread_create(&t, NULL, stdio_thread, NULL) == -1) {
return;
}
pthread_detach(t);
}
void* android_main(void *userdata)
{
client_run((network*)userdata);
return NULL;
}
JNIEXPORT void JNICALL Java_com_clostra_newnode_NewNode_setCacheDir(JNIEnv* env, jobject thiz, jstring cacheDir)
{
const char* cCacheDir = (*env)->GetStringUTFChars(env, cacheDir, NULL);
chdir(cCacheDir);
network *n = client_init(8006);
pthread_t t;
pthread_create(&t, NULL, android_main, n);
(*env)->ReleaseStringUTFChars(env, cacheDir, cCacheDir);
}
// XXX: compat
JNIEXPORT void JNICALL Java_com_clostra_dcdn_Dcdn_setCacheDir(JNIEnv* env, jobject thiz, jstring cacheDir)
{
Java_com_clostra_newnode_NewNode_setCacheDir(env, thiz, cacheDir);
}
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env;
if ((*vm)->GetEnv(vm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
start_stdio_thread();
return JNI_VERSION_1_6;
}