Monday, 28 April 2014

Tagged under: , ,

Android Tutorial - First Android App: Flashlight

Ever thought of creating your own mobile application? Well, with Android, creating your own app is no longer a tedious task, something that could be done only by the professionals. All you need is the basic knowledge of java and xml, and the right way to start off.
This tutorial aims at creating a very basic android application, a flashlight.

Pre-requisites:

1. If using PC:
  • Android SDK
  • Eclipse with ADT plugin
2. If using an Android device : Tablet, cell phone (I had built it on a tablet)
  • An Android IDE, for which I used AIDE
Now, lets get started with the tutorial:

Step I: Create a new Android Project in Eclipse. I have named it 'Lumos', something you can expect from a Harry Potter fan :P

Step II: Ask for Permissions
In the AndroidManifest.xml file, you have to specify the permissions that your application would be requiring in order to perform its tasks. In our case, we require the access to the Camera and its functions in order to start the flashlight.
Open the AndroidManifest.xml and change it to the one as below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.aj.flash"     android:versionCode="1"     android:versionName="1.0" >     <uses-sdk         android:minSdkVersion="8"         android:targetSdkVersion="11" />     <uses-permission android:name="android.permission.CAMERA" />     <uses-feature android:name="android.hardware.camera" />     <application         android:icon="@drawable/ic_launcher"         android:label="@string/app_name" >         <activity             android:label="@string/app_name"             android:name="com.aj.lumos.MainActivity" android:screenOrientation="portrait">             <intent-filter >                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application> </manifest>
As you can see, the below two lines are the ones that are used to get the permission to access the camera and its functions:

<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

Step III: The Layout of the App
Eclipse by default creates a file named main.xml in res->Layout. Open the file and paste the following code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/radial_background"
    tools:context=".MainActivity" >

    <ImageButton
        android:id="@+id/btnSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dip"
        android:src="@drawable/btn_switch_on"
        android:background="@null"
        android:contentDescription="@null"
 android:onClick="switchClicked"/>

    <TextView android:text="Developed by aj"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_centerHorizontal="true"
         android:gravity="center"
         android:padding="15dip"
         android:textSize="13dip"
         android:textColor="#3b3b3b"
         android:layout_marginBottom="15dip"/>

</RelativeLayout>

The 'ImageButton' is nothing but the image of the bulb, which will be used as a button to switch the flashlight on and off. This button is identified by the id: 'btnSwitch'
The 'TextView' field is the one where you can flaunt your name, telling the world that you are the developer of this app :P

Step IV: The actual code
Open the file MainActivity.java and paste the below code:

package com.aj.lumos;

import com.aj.flash.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity{

 ImageButton btnSwitch;
 private Camera camera;
 private boolean isFlashOn;
 private boolean hasFlash;
 Parameters params;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);

 hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);


 if (!hasFlash) {
 AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
 alert.setTitle("Error");
 alert.setMessage("Sorry, your device doesn't support flash light!");
 alert.setButton("OK", new DialogInterface.OnClickListener() {

 public void onClick(DialogInterface dialog, int which) {
  finish();
 }
 });
 alert.show();
 return;
 }

 getCamera();
 toggleswitch();
 }

 public void switchClicked(View v){
 if (isFlashOn) {
 turnOffFlash();
 } else {
 turnOnFlash();
 }
 }

 private void getCamera() {
 if (camera == null) {
 try {
  camera = Camera.open();
  params = camera.getParameters();
 } catch (RuntimeException e) {
  Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
 }
 }
 }

//Turning On flash
 private void turnOnFlash() {
  if (!isFlashOn) {
   if (camera == null || params == null) {
    return;
   }

   params = camera.getParameters();
   params.setFlashMode(Parameters.FLASH_MODE_TORCH);
   camera.setParameters(params);
   camera.startPreview();
   isFlashOn = true;
   toggleswitch();
  }
 }

//Turning Off flash
 private void turnOffFlash() {
  if (isFlashOn) {
   if (camera == null || params == null) {
    return;
   }

   params = camera.getParameters();
   params.setFlashMode(Parameters.FLASH_MODE_OFF);
   camera.setParameters(params);
   camera.stopPreview();
   isFlashOn = false;
   toggleswitch();
  }
 }

 private void toggleswitch(){
  if(isFlashOn){
   btnSwitch.setImageResource(R.drawable.btn_switch_on);
  }else{
   btnSwitch.setImageResource(R.drawable.btn_switch_off);
  }
 }

 @Override
 protected void onStop() {
  super.onStop();
  if (camera != null) {
   camera.release();
   camera = null;
  }
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
 }

 @Override
 protected void onStart() {
  super.onStart();
  getCamera();
 }

 @Override
 protected void onPause() {
  super.onPause();
 }
}

I have tried to modularize the above piece of code by defining separate methods for various tasks. The methods in the above snippet are self explanatory.

You will be requiring a few images that have been used in this tutorial. Download these resources from the download box alongside or use this link: Resources
These images and the xml file in the above zip go into res->drawable-hdpi

Compile the above code and run it on your Android device.
Voila!! We now have our own flashlight app!

I have created an APK of the flashlight app, which can be downloaded from Lumos or from the download box alongside.

Have queries?? Stuck anywhere?? Post all the issues on Compild


Kindly Bookmark and Share it:

2 comments:

  1. Simply want to say your article is as astounding. The clearness to your
    publish is just excellent and that i could assume you're knowledgeable in this subject.
    Well with your permission allow me to grasp your RSS feed to keep updated with approaching post.
    Thanks 1,000,000 and please keep up the gratifying work.


    my page lycanthrope

    ReplyDelete
  2. Android Chat Head Library
    Chat head is new feature which floats on screen instead of residing inside conventional application. This feature is very continent for multitasking as user can work and chat at the same time.
    Android Chat Head Library

    ReplyDelete