Showing posts with label solution. Show all posts
Showing posts with label solution. 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.

Blue Talk


Hi friends,

Get it on Google PlayOct 2011, I started my career with android, and it is been one and half years. For Last one year, it is been a dream for me to open developer account in GOOGLE PLAY. But days passed in search/in learning for new idea, concept and bla bla. Now, I can't control my interest to enter into Google Play as a developer, so I planned to publish something. I went through my pass-time work in android; I had code, which I wrote to transfer text in Bluetooth. Of-course, this is school days program. But my interest asked me to give a touch to it and released it in the Google Play. So, I did the same...

BLUE TALK

"Wanna talk in classroom? Wanna chat in meeting hall? Or Wanna share the secret?
Let us help you now @ any place (@ close range).
One easy and smart way to talk, when you can't talk.
Keep talking... keep enjoying..."

This is how I have started my first app in Google play.



It is a basic Bluetooth chat app to communicate with a friend at short range. It will search the discoverable devices in the short range. It will show the list of devices, from which we can select and communicate.

There is Limitation/Requirement in it since it is half done. It supports only when the app in foreground and one-to-one connection only. Give me some time; I'm trying to remove the limitation and requirement in it.

Now this work is motivating to do more and taught me to create a real time work. Hope, your support will also be there :).

Special thanks to Dipta Pandit help me in designing work...
Get it on Google PlayThanks to my friends for supporting me...
Thanks to Eclipse and Google...


Android - CTS.

Hi Friends,

Our project running android along with Windows is grown up (Running Dual OS in parallel). The time is rushing to release it to the world, but we have to get the license for it to release it in the Android eco-system.  The first thing comes into the play in getting the license is CTS. Fortunately, I got the chance to study and run CTS in our project. Now, here is what I understood and doing in CTS...

 Android Compatibility Program 

The Android Compatibility Program defines the technical details of Android platform and provides tools used by OEMs to ensure that developers' apps run on a variety of devices. The Android SDK provides built-in tools that Developers use to clearly state the device features their apps require. And Google Play shows apps only to those devices that can properly run them.

An "Android compatible device” is the one that can run any application written by third-party developers using the Android SDK and NDK. Google use this as a filter to separate devices that can participate in the Android app ecosystem, and those that cannot. Devices that are properly compatible can seek approval to use the Android trademark. Devices that are not compatible are merely derived from the Android source code and may not participate in the Android app ecosystem.

In other words, compatibility is a prerequisite to participate in the Android apps ecosystem. Anyone is accepted to use the Android source code, but if the device isn't compatible, it's not considered part of the Android ecosystem.

Devices that are Android compatible may seek to license the Google Play client software. This allows them to become part of the Android app ecosystem, by allowing users to download developers' apps from a catalogue shared by all compatible devices. This option isn't available to devices that aren't compatible.

Now, for our project to become part of Android Eco-system and to use Google client software like Google play, maps, etc. we need to pass CTS test.

BUILDING CTS

Android Source tree has the source for cts, we just need to build it to use it.

make cts” will build the cts and the output will be available in the path “android/out/host/linux-x86/cts”.

RUNNING CTS IN WINDOWS

Copy the android-cts folder from the output path to windows and run the following command in the command prompt.

set SDK_ROOT=C:\Users\AMI\AppData\Local\Android\android-sdk

java -Xmx512M -cp C:\Users\alagappanr\Desktop\android-cts\tools\cts-tradefed.jar;C:\Users\alagappanr\Desktop\android-cts\tools\hosttestlib.jar;C:\Users\alagappanr\Desktop\android-cts\tools\ddmlib-prebuilt.jar;C:\Users\alagappanr\Desktop\android-cts\tools\tradefed-prebuilt.jar -DCTS_ROOT=C:\Users\alagappanr\Desktop\ com.android.cts.tradefed.command.CtsConsole

Change the SDK and CTS path accordingly before running above lines.

Once you start the cts, it will provide the cts prompt “cts-tf >”.

NOTE: Device should be connected via adb throughout the test.

CTS COMMANDS

Few important commands are,

·         “help” and “help all” will show the commands and its usage.
·         “exit” will exit the cts prompt.
·         “run cts” command
run cts --plan test_plan_name: run a test plan.
eg. run cts –plan Android : to run android test plan.
run cts --package/-p : run a CTS test package
eg. run cts –p android.net : to run android.net package.
run cts --class/-c [--method/-m] : run a specific test class and/ormethod
run cts --continue-session session_ID: run all not executed tests from a previous CTS session
eg. run cts –continue-session 5 : to continue session 5 unexecuted cases.

Rest of the command signature and usage are shown once you run help command.

CTS Result

Test result will available in the folder “android-cts\repository\results”.

To view the test result, Open the testResult.xml generated in the folder “android-cts\repository\results\date_time”.

So, What you are waiting for... send the result to google, get the license and get google client software & service for your device and release your product in the market... :) 

Yep it is easy to say the last two lines.. But difficult to implement...

Android Input Device Events

Hi friends,

I have got task dealing with touch monitor. I have to implement multitouch in our project. In the middle, I wanted to see input events. My teammate gave me the keyword to see the input event and to manually send input event to any devices. I would like to put it here. So, Me and You can refer, when we want it...

Android getevent and sendevent 

ya, as you guess...
  • getevent is to read the input event from the device(/dev/input/device-name) and
  • sendevent is to write the input event to the device(/dev/input/device_name) manually
Before, the getevent and sendevent... Lets have a brief look into the input event...
Input Event : Basically inputs are written has (sequence of ) events in the device(/dev/input/event(device) in case of Linux). All input events comprise of three values namely,
  • Type  : type of the event like Key, Sync, Misc, LED, etc.
  • Code  : value corresponding to the key, which is pressed.
  • Value : Zero for release and One for click/press, in case of key press and mouse click event. some running number in other case( I don't have too much knowledge in it).
With these 3, OS will understand the input given by us and perform the action to the corresponding input.
 
Example : when we press key 2 in the keyboard... event sequence will be like the below

In ubuntu,  (I wrote a c program to read the input even from device and the output is below)
Event: type 4 (Misc), code 4 (ScanCode), value 458783   [Conveying the event is scancode]
Event: type 1 (Key), code 3 (2), value 1                             [key 2 pressed]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]
Event: type 4 (Misc), code 4 (ScanCode), value 458783    [conveying the event is scancode]
Event: type 1 (Key), code 3 (2), value 0                             [key 2 release]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]

In andriod,
Event: type 1 (Key), code 3 (2), value 1                             [key 2 pressed]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]
Event: type 1 (Key), code 3 (2), value 0                             [key 2 release]
Event: type 0 (Sync), code 0 (Sync), value 0                      [sync event]

This is for pressing the key 2 once... This will be written into the device, OS will read it and perform the actions.

ok now...

getevent : will print the event written into the device.
syntax    : getevent device
example : getevent /dev/input/event0
output    :  In android, it didn't say the scancode... but all the inputs are handled as scancodes. output is,
0001 0003 00000001
0000 0000 00000000
0001 0003 00000000
0000 0000 00000000

sendevent : will allow us to give the input in the terminal.
syntax       : sendevent device type code value.
example    : for writing key 2 into the device.
shell@android:/ # sendevent dev/input/event0 0000 0000 00000000
shell@android:/ # sendevent dev/input/event0 0001 0003 00000001
shell@android:/ # sendevent dev/input/event0 0000 0000 00000000
shell@android:/ # sendevent dev/input/event0 0000 0000 00000000


P.S. : Remember the two points below,

  1.  Run it in the android shell.
  2.  Should have root permission.


Don't want your android to sleep soon!!!


Hi friend,

I got another one interesting task in my project.  The task is by default the sleep time in Android ICS was 1 min, we want to set to 30 minutes as default.

If you check in Settings > display > sleep, it will display as 1 minute as default and there will not be any never option.

So now if we want to change the default sleep value while customizing the android, just follow the following steps…

Step 1: open the following xml file… android/frameworks/base/packages/SettingsProvider/res/values/defaults.xml.

Step 2: change the default sleep time value in the line,
<"integer name="def_screen_off_timeout">60000<"/integer">… I changed it to 1800000 (30 minutes)…
Now, if you check in Settings > display > sleep, it will display as 30 minutes as default…

And if you don’t want timeout, set it to ‘-1’ …
Now, if you check in Settings > display > sleep, it won’t show any time out value… :)


ANOTHER METHOD: Editing the sleep time in the Settings source…

Step 1: open the file, android/packages/apps/Settings/src/com/android/settings/DisplaySettings.java

Step 2: Add the line, “Settings.System.putInt(getContentResolver(), SCREEN_OFF_TIMEOUT, -1);” before the line “ final long currentTimeout = Settings.System.getLong(resolver, SCREEN_OFF_TIMEOUT,               FALLBACK_SCREEN_TIMEOUT_VALUE);”

Now, if you check in Settings > display > sleep, it won’t show any time out value… :)

DO REBUILD THE ANDROID AFTER THE CHANGES!!! DON’T FORGET!!!

Task Completed :) :) :)

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