Android (Java): JNI Source code

Source: Internet
Author: User

public void OnCreate (Bundle savedinstancestate)
{
Super.oncreate (savedinstancestate);
Button btn = New button (this);
Btn.settext ("Test Ndk");
Btn.setonclicklistener (New Buttononclicklistener ());
Setcontentview (BTN);
Toast.maketext (Getapplicationcontext (), PATH, Toast.length_long). Show ();
}

Public final class Buttononclicklistener implements onclicklistener{

@Override
public void OnClick (View arg0) {
TODO auto-generated Method Stub
byte[] data = "Zhanghongliu". GetBytes ();
FileInputStream FIS = null;
FileOutputStream fos = null;
int i = 0;
for (i=1;i<=200000;i++) {
try {
FIS = new FileInputStream (ResourcePath);
int size = fis.available ();
data = new Byte[size];
Fis.read (data, 0, size);
String result = Filejnilib.videocrypt (Data,encryptpath);
Toast.maketext (Getapplicationcontext (), result, Toast.length_long). Show ();

data = Filejnilib.videoderypt (Encryptpath);
FOS = new FileOutputStream (Decryptpath);
Fos.write (data);
} catch (FileNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}finally{
try {
if (null! = FIS) {
Fis.close ();
}
if (null! = FOS) {
Fos.close ();
}
data = null;
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
LOG.I ("Count", i+ "");
data = null;
}
Toast.maketext (Getapplicationcontext (), new String (data), Toast.length_long). Show ();
Show ();
}

public void Show () {
File NewFile = new file (PATH);
FileInputStream instream = null;
try {
instream = new FileInputStream (newfile);
} catch (FileNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
String content = Fileutil.readinstream (instream);
LOG.I ("FileText", content);
Toast.maketext (Getapplicationcontext (), content, Toast.length_long). Show ();
}

}

public static String Readinstream (FileInputStream instream) {
try {
Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();
byte[] buffer = new byte[1024];
int length =-1;
while (length = instream.read (buffer))! =-1) {
Outstream.write (buffer, 0, length);
}
Outstream.close ();
Instream.close ();
return outstream.tostring ();
} catch (IOException e) {
LOG.I (TAG, E.getmessage ());
}
return null;
}

public class Filejnilib {

static {
System.loadlibrary ("Filejni");
}
public static native string Videocrypt (byte[] content, string dest_file);
public static native byte[] Videoderypt (String dest_file);

public static native String Videoderypt (string dest_file, Bytearrayoutputstream outputstream);

}

/* Don't EDIT this file-it are machine generated */
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/stat.h>

Main header files for #include <jni.h>//jni

#include <android/log.h>
#define LOG_TAG "JNI"
#define Logi (...) __android_log_print (Android_log_info, Log_tag, __va_args__)
/* Header for class Com_test_jni_filejnilib */

/*
* Class:com_test_jni_filejnilib
* Method:videocrypt
* Signature: ([bljava/lang/string;) V
*/
Jniexport jstring Jnicall Videocrypt
(JNIENV * env, Jclass thiz, jbytearray content, jstring dest_file) {
Env->getstringutfchars (Source,null);

const char *path = (*env)->getstringutfchars (env, Dest_file, NULL);
Logi (path);

FILE *FP = fopen (path, "WB");
if (fp==null) {
Logi ("fopen error");
(*env)->releasestringutfchars (env,dest_file, path);
Return (*ENV)->newstringutf (env, "fopen error");
}
Char *data = (*env)->getbytearrayelements (env,content, 0);
int size = (*env)->getarraylength (env,content);
int ilen = sizeof (data),//c or expression length character in the language
Logi ("File size is%d", size);

Crypt (data,size);

/****** File Write Method ***********/
FPUTC (' C ', FP);
Fputs (DATA,FP);
Fwrite (DATA,SIZE,1,FP);
fprintf (FP, "%s", data);
/*****************/

Fclose (FP);
(*env)->releasebytearrayelements (env,content,data,0);
(*env)->releasestringutfchars (env,dest_file, path);
Logi ("execute complete");
Return (*ENV)->newstringutf (env, "encrypt successful");
}

/*
* Class:com_test_jni_filejnilib
* Method:videoderypt
* Signature: (ljava/lang/string;) [B
*/
Jniexport Jbytearray Jnicall Videoderypt
(JNIENV * env, Jclass thiz, jstring dest_file) {
const char *path = (*env)->getstringutfchars (env, Dest_file, NULL);
Logi (path);

   /***** Gets the file length *******/
   int size;
   struct stat  Tfilestat;
   if (Path, &tfilestat)
   {
    logi (" File not found error ");
     (*env)->releasestringutfchars (env,dest_file, path);
    return NULL;
   }
   size=tFileStat.st_size;
   logi ("File size is%d", size);//error int
   /************/

/***** Allocating Memory *******/
char *temp = NULL;
temp= (char*) malloc (size);
if (temp = = NULL)
{
Logi ("malloc error");
(*env)->releasestringutfchars (env,dest_file, path);
return NULL;
}
memset (temp,0x00,size*sizeof (char) +1);//Initialize Memory
/************/

FILE *FP = fopen (path, "RB");
if (fp==null) {
Logi ("fopen error");
(*env)->releasestringutfchars (env,dest_file, path);
Free (temp);//Release memory
Temp=null;
return NULL;
}

/****** file Read Method ***********/
FGETC (FP);
Fgets (TEMP,100,FP);
Fread (TEMP,SIZE,1,FP);
FSCANF (FP, "%s", temp);
/*****************/

Fclose (FP);

Crypt (temp,size);

   jbytearray JARRRV = (*env)->newbytearray (env,size);
   jbyte *jby = (*env)->getbytearrayelements (ENV,JARRRV, 0);
   memcpy (Jby, temp, size);//Copy Data
    (*env)->setbytearrayregion (env, JARRRV, 0,size, jby);//convert Jbyte to Jbarray array
    (*env)->releasebytearrayelements (ENV,JARRRV, jby,0);//release jby array * Resolves a long-running exit problem Internal reference exceeds the specified number of
   //(*env)->deletelocalref (ENV,JARRRV);//Impact Program
   //(*env)->deletelocalref (env,temp);//not   general use malloc for memory, free to release
    Free (temp);
   temp=NULL;
    (*env)->releasestringutfchars (env,dest_file, path);
   logi ("execute complete");
   return JARRRV;
}

void Crypt (char *data, int size) {
int i;
Char spwd[]= "************************";
int pwdlen = sizeof (SPWD);
Logi ("dongao.com mobile_encrypt%d", Pwdlen);
int count=0;
for (i=0; i<size; i++)
{
if (count >= pwdlen) count = 0;
Data[i]=data[i]^spwd[count++];
Logi ("%c", Spwd[count >= count=0:count++]);
}
}

/*
* Class:com_test_jni_filejnilib
* Method:videoderypt
* Signature: (ljava/lang/string; Ljava/io/bytearrayoutputstream;) V
*/
Jniexport jstring Jnicall Videoderypt2bytearray
(JNIENV * env, Jclass thiz, jstring dest_file, Jobject outputstream) {
return NULL;
}

static const Jninativemethod Gmethods[] = {//defines the array of bulk registrations, which is a key part of registration
{"Videocrypt", "([bljava/lang/string;) ljava/lang/string;", (void*) Videocrypt},//FUNC2 is the native function name declared in Java, "() V" Is the signature of the function, which can be obtained through Javah.
{"Videoderypt", "(ljava/lang/string;) [B", (void*) Videoderypt},
{"Videoderypt", "(ljava/lang/string; Ljava/io/bytearrayoutputstream;) ljava/lang/string; ", (void*) Videoderypt2bytearray}
};


Jniexport jint jni_onload (javavm* vm, void *reserved)//This is a declaration of jni_onload and must be declared in such a way

{

jnienv* env = NULL; Registration is implemented in JNIEnv, so you must first obtain it

Jint result =-1;


if ((*VM)->getenv (VM, (void**) &env, jni_version_1_4)! = JNI_OK)//Get JAVAVM from JNIEnv, general use 1.4 version

return-1;

Jclass Clazz;

static const char* Const kclassname= "Com/test/jni/filejnilib";

Clazz = (*env)->findclass (env, kclassname); Here you can find the class to register, provided that the class is already loaded into the Java virtual machine. This shows that there is no correspondence between the dynamic library and the class with the native method.

if (clazz = = NULL)

{

Logi ("Cannot get class:%s\n", kclassname);

return-1;

}

if ((*env)->registernatives (env, clazz,gmethods, sizeof (gmethods)/sizeof (gmethods[0]))! = JNI_OK)//Here is the key, Associate the local function with a Java class method. Regardless of whether it has been connected before, will replace the previous!

{

Logi ("Register native Method failed!\n");

return-1;

}

return jni_version_1_4; This is important and must be returned to the version or the load will fail.

}

Original http://blog.csdn.net/zhanghongliu1122/article/details/9411921

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.