Search This Blog

Saturday, January 7, 2012

Android java app - Blinking camera flash LED

I'm developing hardware control applications for the Android phone platform to replicate functionality I've previously used in gadgets for the Arduino.

Finally I achieved my goal of replicating the very first "I'm Alive!" hardware test on a new platform.  Whenever you make a new gadget, the first program you run blinks a light to show health.

I was able to get the LED used for the camera flash to blink!  Hooray!   In my earlier post I found the code and permissions needed to turn it on and off with a button press.   Then I had to find a suitable system clock to use to time the blinking, but got sidetracked generating audio tones.  So finally I put the two together and here is how I did it using the Android SDK in Eclipse.  This technique is limited to <500Hz because the system clock is milliseconds.   The next step will be to find a method to access a faster clock.  However if the goal is communicate to humans or slow serial interface, this might be good enough.

in AndroidManifest.xml you need (you may not need them all, didn't test that)

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.FLASHLIGHT"/>
    <uses-permission android:name="android.permission.HARDWARE_TEST"></uses-permission>

The code I wrote looks like this (copied out the relevant bits from a larger program so hopefully I didn't leave out something critical).  This code was placed in a callback from a button press.  The actual flashing is just done with the for loops, but the rest starts it in another thread so the phone is locked up while this is running.  You don't have to do this but you might frustrate a user if you don't.  I tried it first without the additional thread.   The full app is here, but the relevant bits are below  http://code.google.com/p/arduino-java-xyzcnc/downloads/detail?name=Siliconfish%20Blink.zip&can=2&q=#makechanges
  
    //variables for light blinking
    private final int blinkrate_ms = 100;
    private long nextblink = blinkrate_ms;
        
            //blink the light
            // Use a new thread to flash as this can take a while
                final Thread thread = new Thread(new Runnable() {
                    public void run() {
                        handler.post(new Runnable() {


                            public void run() {                              
                                // loop to flash the camera LED
                                for(int q = 0; q<10; q++)  {
                            nextblink = SystemClock.elapsedRealtime() + blinkrate_ms;
                            while (SystemClock.elapsedRealtime()<nextblink) {
                            setOn(true, null);
                            }
                            nextblink = SystemClock.elapsedRealtime() + blinkrate_ms;
                            while (SystemClock.elapsedRealtime()<nextblink) {
                            setOn(false, null);
                            }
                            } //for
                                
                            }
                        });
                    } 
                }); //thread
                thread.start();
           
                  
It required these functions which turn on and off the LED
     
    // code largely copied from   http://www.java2s.com/Open-Source/Android/Tools/quick-settings/com/bwx/bequick/flashlight/Droid22Flashlight.java.htm
    // Controls the camera flash LED
    
    private Object mManager;


    public boolean isOn(Context context) {
        try {
            Object manager = getManager();
            if (manager != null) {
                Method getFlashlightEnabledMethod = manager.getClass()
                        .getMethod("getFlashlightEnabled");
                return (Boolean) getFlashlightEnabledMethod
                        .invoke(manager);
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return false;
    }


    public void setOn(boolean on, Context context) {
        try {
            Object manager = getManager();
            if (manager != null) {
                Method setFlashlightEnabledMethod = manager.getClass()
                        .getMethod("setFlashlightEnabled",
                                boolean.class);
                setFlashlightEnabledMethod.invoke(manager, on);
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
    }


    private Object getManager() {
        if (mManager == null) {
            try {
                Class<?> managerClass = Class
                        .forName("android.os.ServiceManager");
                Method methodGetService = managerClass.getMethod(
                        "getService", String.class);
                IBinder hardwareService = (IBinder) methodGetService
                        .invoke(managerClass, "hardware");


                Class<?> stubClass = Class
                        .forName("android.os.IHardwareService$Stub");
                Method asInterfaceMethod = stubClass.getMethod(
                        "asInterface", IBinder.class);
                mManager = asInterfaceMethod.invoke(stubClass,
                        hardwareService);
            } catch (Exception e) {
                Log.e(TAG, "", e);
            }
        }
        return mManager;
    }

15 comments:

  1. Hi,

    Great post (and great blog too). I just did a Google search on controlling the flash LED of an Android phone and ended up here - which was exactly where I needed to be.

    I'm in the beginning stages of trying to create a simple Visual Light Communications link from an Android Phone to my Arduino board. The fact that you've been able to flash the LED at 500Hz is certainly great news for me (It means I can probably get the data rate at up to 10bytes per second).

    Out of curiosity, did you get much further down the path to seeing if you could get the frequency higher? Or is the system clock too big an obstacle?

    Cheers,

    Keiran.

    ReplyDelete
  2. Out of town and didn't see this comment. Here is the problem. In a later post I discussed System.nanotime(), which is a faster timer, but rapidly you run into processor interrupts. I probably should have written more about that topic but veered off into publishing apps.

    If you flash the LED really fast you'll see that sometimes the processor gets busy and the flashing gets very flaky, since android is not a real time operating system.

    If you want to use it for communications, and I bailed on that idea, you are going to have to find a coding scheme that allows for an irregular clock. Let me know if you figure it out!

    ReplyDelete
  3. The Cuffmate LED is another wonderful flashlight that comes with a handcuff key made into it for all police officers. The Cuffmate is a dual LED flashlight made of an unbreakable polymer case with a steel alloy handcuff key attached to one end. Bussmann Fuses

    ReplyDelete

  4. Another illustration point for creating games on Android gadgets is the programming dialect included JavaRecommended Site

    ReplyDelete
  5. Later on in life, you noticed the great flashlights carried by Scully and Moulder on the Xfiles. They had the best distance and intensity of any flash light seen before, and I think in every episode they used these flash lights.bolder lc90

    ReplyDelete
  6. Must read article by everyone including a valid content which educate folks with its unique blog. Thus, exploring the readers curiosity in gaining a valuable content. Thanks to the blogger.

    Data Science Training in Bhilai

    ReplyDelete
  7. Thanks a lot for one’s intriguing write-up. It’s actually exceptional. Searching ahead for this sort of revisions.
    best digital marketing training institute in hyderabad

    ReplyDelete
  8. Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers.
    business analytics training in hyderabad

    ReplyDelete
  9. i'm fulfilled to consider this make perceived Very helpful for me, as it contains part of guidance. I generally favor to buttonhole The fantastic and happy I found this include number in you statement. much appreciated NordVPN Crack

    ReplyDelete
  10. this is a pounding blog. I wind it. you have such a lot of mastery about this depend, and as a repercussion a ton enthusiasm. You further to know a method for making individuals rally toward the back it, clearly from the reactions. Office 2016 Crack Download

    ReplyDelete
  11. Glorious web site! I love the way it is straightforward upon my eyes it's far. I'm contemplating the way in which I might be prompted whenever another conspicuous screen has been made. glancing through out extra new updates. Have a colossal extensive stretches of significant stretches of light hours!! https://wishesquotz.com/happy-birthday-wishes-for-son-in-law/

    ReplyDelete