link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>

Sunday, June 15, 2014

Flashy the Flash Light: a tutorial to make your own flash light app Day 2

Hello again!!

First lets quickly recap what we went over on the first day of this tutorial:

  • build an .XML with a toggle button that will be used to turn the LED light of your phone on and off
  • how to modify the Manifest file to get permission to use the camera features of the phone
your layout.xml should look like this:


    


and your manifest file should look like this:


    
    

    
        
            
                

                
            
        
    



Now that that's settled lets get into the JAVA section!! woot woot!
First open the java activity (project>src>com.something...>MainActivity.Java).  When you open the file there should only be about 10 lines of code and we're going to be working the public class first.  It should read "public class MainActivity extends Activity".  After activity type "implements OnClickListener"

This should bring up an error on the 'OnClickListener" hover over it and you should get these options:



Click on the first option import 'OnClickListener' (android.view.View).  Now this should bring up another error over the activity name 'MainActivity'.  Hover over the underlined phrase and click on the first quick fix 'Add unimplemented methods' and this will add an onClick method.

An onClick method is exactly what it sounds like (just like when someone says 'do this on three'). So on a button click it will perform a task.  In our case, this task will be turning on a light.

Now we're going to define the toggle button and the camera.  This is done above the On Create method.  I want you to write "ToggleButton = tb;"  "public static Camera OurCam= null;" and "Parameters p;"

The next step is to connect the toggle button we just defined to the toggle button inside the activity.xml file that was defined earlier.  To do this just type "tb = (ToggleButton) findViewById(R.id.toggleButton1);" "tb.setOnClickListener(this);"

We're finally on the last step of having a functioning LED flashlight!  Inside the onClick method we're going to make an if statement that checks to see if the toggle button is on or off and add the Camera functionality.  The final On Click method will look like this:

@Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  if (tb.isChecked()) {
   ourCam = Camera.open();
   p = ourCam.getParameters();
   p.setFlashMode(Parameters.FLASH_MODE_TORCH);
   ourCam.setParameters(p);
   ourCam.startPreview();

  } else {
   ourCam.stopPreview();
   ourCam.release();
  }

 }


And that's it!! your LED light should now turn on and off!

There are still a few errors associated with this code, and I'll be going over what they are and how to fix them in the next tutorial!



No comments:

Post a Comment