Showing posts with label c language. Show all posts
Showing posts with label c language. Show all posts

11 Steps to learn Android JNI



Hi Friends,

It’s been around 2 years since I started working in android, but I never got chance to create one complete jni work. So, today I planned to learn Android jni. Now, here is what I learnt… for our reference

Android JNI

Requirement

  • Eclipse with android sdk
  • Android ndk(Download it from: http://developer.android.com/tools/sdk/ndk/index.html)

Steps to create a jni work… let’s take an example of squaring a number (same example, which I learnt from another blog)

Step 1: create an android project in eclipse (example: FirstJni).

Step 2: Create a folder in the name jni inside FirstJni.

Step 3: Create a file named Android.mk in the jni folder.

Step 4: Create a file SquaredWrapper.java in scr folder, which is a wrapper class. The wrapper’s job is to load the library, expose any native functions we wish to use directly, and provide any functions that we want to be able to utilize private native functions.

SqaredWrapper.java 

package com.alag.firstjni;

public class SquaredWrapper {
    // Declare native method (and make it public to expose it directly)
    public static native int squared(int base);
    
    // Provide additional functionality, that "extends" the native method
    public static int to4(int base)
    {
        int sq = squared(base);
        return squared(sq);
    }
    
    // Load library
    static {
        System.loadLibrary("squared");
    }
}

Step 5: Creating class file with the SquaredWrapper.java. use the following command in the FirstJni folder
cd src # change into the source directory
javac -d /tmp/ com/alag/firstjni/SquaredWrapper.java

Step 6: Creating C header file with the created Class file. use the following command
cd /tmp
javah -jni com.alag.firstjni.SquaredWrapper

This will create following squared.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class com_alag_firstjni_SquaredWrapper */

#ifndef _Included_com_alag_firstjni_SquaredWrapper
#define _Included_com_alag_firstjni_SquaredWrapper
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_alag_firstjni_SquaredWrapper
 * Method:    squared
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_com_alag_firstjni_SquaredWrapper_squared
  (JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif

Step 7: Create C source file now with the prototype in the header file in jni folder,
 
Squared.c
#include "squared.h";

JNIEXPORT jint JNICALL Java_com_alag_firstjni_SquaredWrapper_squared
  (JNIEnv * je, jclass jc, jint base)
{
        return (base*base);
}

Step 8: Now have the Squared.h and Squared.c file in the jni folder and write following lines in the Android.mk created in the jni  folder,

Android.mk
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := squared
LOCAL_SRC_FILES := squared.c

include $(BUILD_SHARED_LIBRARY)

Step 9: Building Shared library
Inside the FirstJni folder (which has src and jni folders), run the ndk-build script in the ndk folder.
cd FirstJni
/path/to/ndk-build # for example: ~/build/android-ndk/android-ndk-r7c/ndk-build
If the build script found your Android.mk and the library compiled without issue, you’ll see the following:
Compile thumb  : squared <= squared.c
SharedLibrary  : libsquared.so
Install        : libsquared.so => libs/armeabi/libsquared.so
Step 10: By default, when we created a new Android project in Eclipse an activity was generated. Put the following in it
package com.alag.firstjni;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

          @Override
          protected void onCreate(Bundle savedInstanceState) {
                   super.onCreate(savedInstanceState);
                   setContentView(R.layout.activity_main);
                  
                   int b = 3;
        int a = SquaredWrapper.to4(b);
        Log.i("JNIDemo", String.format("%d->%d", b,a));
          }

          @Override
          public boolean onCreateOptionsMenu(Menu menu) {
                   // Inflate the menu; this adds items to the action bar if it is present.
                   getMenuInflater().inflate(R.menu.main, menu);
                   return true;
          }

}
Step 11: run it, either in the emulator or on a device, and we would see in LogCat an entry tagged with JNIDemo. In this case, we’d expect something like 3->81, since 3^4 = 81.

So, we are now ready to play with ndk :P

Thanks a lot to http://blog.edwards-research.com for teaching me Android jni basics.

Signal in LINUX

Hi friends,

Currently, I'm working in wake-up issue in my project. I wanna inform android when my host OS windows wakes up. My project leader gave me an idea to send a signal from windows to android in the shell and use that signal to wake android when windows wakes up, like in exam days I keep alarm by 4am, my bad wakes up and give me a kick ;). But I'm zero at LINUX signal concept, as usual i studied it. Now, I'm typing here for my future ref. and other beginner's use.

SIGNAL IN LINUX

Now, we use CTRL + C to terminate something in LINUX. But, we don't wanna let someone to terminate our code with CTRL + C. So, what we have to do now. We have to monitor the user input and we should not let the system to perform any operation when user gives CTRL +C.

But, Instead what we can do in LINUX is, CTRL + C will generate a signal SIGINT in LINUX, so we can register a function to this signal in our code. So that when we user press CTRL + C, it will call our function, so our code won't be terminated.

What is signal in LINUX ? 
 LINUX has a set of signals. One nice example is, kill -9 PID, which we use to kill a process. Here, we are sending KILL signal to a process. Similarly, few other signals are available in LINUX. (SRY, i don't know to explain it, pls ask prof.google :( )

How can we register a function to a signal ?
here is the syntax,

signal(SIGINT, sig_handler)
SIGINT - signal generated on pressing CTRL + C. It can be any LINUX signal.
sig_handler - our function, which will be executed on receiving SIGINT signal.

What should be the sig_handler signature? 
here it is,
void sig_handler(int signo) {}
signo - signal number crossponding to the register signal.
Inside the function, we can write our own story.

Ok, How the final code will be? 
here is the simple one,
#include <stdio.h>
#include
<signal.h>
#include <unistd.h>

void sig_handler(int signo)
{
  if (signo == SIGINT)
    printf("received SIGINT\n");
}

int main(void)
{
  if (signal(SIGINT, sig_handler) == SIG_ERR)
  printf("\ncan't catch SIGINT\n");
  // A long long wait so that we can easily issue a signal to this process
  while(1)
    sleep(1);
  return 0;
}

Now, run the code and press CTRL + C. It will print "^Creceived SIGINT".

But, LINUX has alot of signals, is it possible to do for all signal of LINUX?
 Expect SIGKILL and SIGSTOP, we can use any signal in the place of SIGINT. So, change signal you would like register, change the body of sig_handler function as you like. Your coding will be done.

In my case, I have to generate a signal on my own... I choose to send user signal(SIGUSR1)...
So, the code will be?
here it is,

#include <stdio.h>
#include
<signal.h>
#include <unistd.h>

void sig_handler(int signo)
{
  if (signo == SIGUSR1)
    printf("received SIGUSR1\n");
}

int main(void)
{
  if (signal(SIGUSR1, sig_handler) == SIG_ERR)
  printf("\ncan't catch SIGUSR1\n");
  // A long long wait so that we can easily issue a signal to this process
  while(1)
    sleep(1);
  return 0;
}

Thats all, compile and run it :)... But how to send user signal? The following line will do that...
KILL -USR1 PID
 Got the signal!!!....

MAGIC(MATH) in C - CRACK IT IF YOU CAN!!!

Hi friends,

When I was doing my C language course... My instructor shown a small magic and asked us to find the logic behind it... I and my friends took one day to crack it...
Do you wanna know... what is that magic???
Would you like to crack it???
Could you crack it???
Ok here is the link for that .exe file... Download it and command the answer IF YOU CAN...

DOWNLOAD(.ZIP)

(Friends, the above link will open the MEGAUPLOAD site... you need to wait for 30 to 40 sec and then click on the regular download..and then you can download the zip file..you need to extract the zip to get the exe file- this is because i cannot upload or link the exe file directly from my system)..

ANSWER:
It’s been a week; I didn't receive any response... So here is solution...

Whatever may be the number... When you add the digits and subtract it from the number... the result will be multiples of 9... So each time, I gave the same symbol for the all multiples of 9... so your symbol has to be, the symbol which I gave for those multiples of 9…

And here is the source code…

SOURCE CODE

Pythagorean triplet

question:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^(2) + b^(2) = c^(2)
For example, 3^(2) + 4^(2) = 9 + 16 = 25 = 5^(2).
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
answer:
#include
#include
void main()
{
 long int a,b,c,as,bs,cs;
 clrscr();
 for(a=1;a<1000;a++)
  for(b=1;b<1000;b++)
   for(c=1;c<1000;c++)
   {
    as=a*a;
    bs=b*b;
    cs=c*c;
    if((as+bs)==cs)
     {
     if(a+b+c==1000)
      printf("a=%ld,b=%ld,c=%ld\t as=%ld,bs=%ld,cs=%ld\tproduct=%ld\n",a,b,c,as,bs,cs,a*b*c);
     }
   }
 printf("over\n");

 getch();
} 

answer:31875000

posted under , | 0 Comments

prime number

question:

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6^(th) prime is 13.
What is the 1001^(st) prime number?
answer:
  #include
#include
void main()
{
 long int i,j,prime,count=0;
 clrscr();
 for(i=2;i<10000;i++)
 {
  prime=1;
  for(j=2;j<=i/2;j++)
   {
    if(i%j==0)
     {
      prime=0;
     }
   }
   if(prime==1)
   {
    count=count+1;
    if(count==1001)
    {
    printf("%ld is prime\n",i);
    break;
    }
   }
  }
  printf("count is %ld",count);
  getch();
}
answer:7927

posted under , | 0 Comments

Differance between sum square and square sum

question:

The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + ... + 10^(2) = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^(2) = 55^(2) = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
answer:
#include
#include
void main()
{
 long int i,sum=0,sq=0;
 clrscr();
 for(i=0;i<=100;i++)
 {
  sum=sum+i;
  sq=sq+(i*i);
 }
 printf("sum sq=%ld,sq=%ld,diff=%ld",sum*sum,sq,(sum*sum)-sq);
 printf("over");
 getch();
}

output:25164150

posted under , | 0 Comments

palindromic number

hello friends,
recently i have started working on projecteular.net which tests our programming skill... so i have created few programs... those codes are here..one after other
question:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

answer:
#include
#include
void main()
{
 long int d0,d3,d2,d1,d5,d4,i,j,l,max=0;;
 clrscr();
 for(l=999;l>100;l--)
 for(i=999;i>100;i--)
  {
   j=l*i;
// j=986689;
   d5=(j%10);
   d4=((j-d5)%100)/10;
   d3=((j-d5-d4)%1000)/100;
   d2=((j-d5-d4-d3)%10000)/1000;
   d1=((j-d5-d4-d3-d2)%100000)/10000;
   d0=((j-d5-d4-d3-d2-d1)%1000000)/100000;
   if(d0==d5)
    if(d1==d4)
     if(d2==d3)
      {
       printf("l=%ld,i=%ld,j=%ld\n",l,i,j);
       if(max
       max=j;
      }
  }
 printf("max is %ld",max);
 getch();
}

Answer:906609

posted under , | 0 Comments
Older Posts Home

About Me

My photo
Hi everyone,myself Alagappan...electronic and communication engg. student... living in madurai... interested in everything... want to achieve something great in my lifetime...

Followers


Recent Comments