Wikipedia

Search results

Monday, May 27, 2013

Custom Dialog Tutorial

Create custom dialog view in android tutorial.


MainActivity.java

package com.customdialognew;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.widget.TextView;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
       
       
        Dialog alert = new Dialog(this);
        alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alert.setContentView(R.layout.title);
        TextView msg = (TextView)alert.findViewById(R.id.textView1);
        msg.setText("Hello Friends.\nIP address : 111.111.1.111");
        alert.show();
    }
   
    @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;
    }

}



activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>



info.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/ic_launcher" >
   

</LinearLayout>



title.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set IP address"
        android:textColor="#ff0000"
        android:textAppearance="?android:attr/textAppearanceLarge" />
   
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:layout_marginTop="5dp"
        android:background="#00ff00"
        />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#775500"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>




click here to Download.

Android Video Capture Tutorial

Tutorial for Capture video in android device.

AndroidVideoCapture.java

package com.exercise.AndroidVideoCapture;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

public class AndroidVideoCapture extends Activity{
   
    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;

    Button myButton;
    SurfaceHolder surfaceHolder;
    boolean recording;
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        recording = false;
       
        setContentView(R.layout.main);
       
        //Get Camera for preview
        myCamera = getCameraInstance();
        if(myCamera == null){
            Toast.makeText(AndroidVideoCapture.this,
                    "Fail to get Camera",
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
        myCameraPreview.addView(myCameraSurfaceView);
       
        myButton = (Button)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }
   
    Button.OnClickListener myButtonOnClickListener
    = new Button.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(recording){
                // stop recording and release camera
                mediaRecorder.stop();  // stop the recording
                releaseMediaRecorder(); // release the MediaRecorder object
               
                //Exit after saved
                finish();
            }else{
               
                //Release Camera before MediaRecorder start
                releaseCamera();
               
                if(!prepareMediaRecorder()){
                    Toast.makeText(AndroidVideoCapture.this,
                            "Fail in prepareMediaRecorder()!\n - Ended -",
                            Toast.LENGTH_LONG).show();
                    finish();
                }
               
                mediaRecorder.start();
                recording = true;
                myButton.setText("STOP");
            }
        }};
   
    private Camera getCameraInstance(){
        // TODO Auto-generated method stub
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }
   
    private boolean prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));

        mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
        mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
        mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M

        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;
       
    }
   
    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = null;
            myCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();        // release the camera for other applications
            myCamera = null;
        }
    }
   
    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

        private SurfaceHolder mHolder;
        private Camera mCamera;
       
        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;

            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                int height) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (mHolder.getSurface() == null){
              // preview surface does not exist
              return;
            }

            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e){
              // ignore: tried to stop a non-existent preview
            }

            // make any resize, rotate or reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            // The Surface has been created, now tell the camera where to draw the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub
           
        }
    }
}



main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <RelativeLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
        <FrameLayout
            android:id="@+id/videoview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
        <Button
            android:id="@+id/mybutton"
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            android:text="REC"
            android:textSize="12dp"/>
    </RelativeLayout>
</LinearLayout>



AndroidManifest.xml  

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.exercise.AndroidVideoCapture"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="10" />
    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidVideoCapture"
                  android:label="@string/app_name"
                  android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                  android:screenOrientation="landscape">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>
 




 

click here to Download.


Analog Clock Widget Tutorial

create custom analog clock widget in this tutorial.


Widget.java

package sandy.Tutorials.Widgets.AnalogClock;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class Widget extends AppWidgetProvider
{   
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
        {
          
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
           
            Intent AlarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(new ComponentName("com.android.alarmclock", "com.android.alarmclock.AlarmClock"));
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, AlarmClockIntent, 0);
            views.setOnClickPendingIntent(R.id.Widget, pendingIntent);
                                   
            AppWidgetManager.getInstance(context).updateAppWidget(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), views);
        }
    }
}


Info.java

package sandy.Tutorials.Widgets.AnalogClock;

import android.app.Activity;
import android.os.Bundle;

public class Info extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState); setContentView(R.layout.info);
    }
}


widget.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/Widget"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center" >

    <AnalogClock
        android:id="@+id/AnalogClock"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:dial="@drawable/widgetdial"
        android:hand_hour="@drawable/widgethour"
        android:hand_minute="@drawable/widgetminute"
         />

</RelativeLayout>


info.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Thank you for installing the Custom Analog Clock Widget.\n\nPlease read these important instructions.\n\nThis is a widget, not a regular application. Unlike regular applications, widgets are placed on the home screen and offer useful (hopefully) information at a glance. In many cases, such as with this widget, you can press the widget and view additional, or more detailed, information. Pressing this widget will open the Alarm Clock application.\n" />

</LinearLayout>




 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="sandy.Tutorials.Widgets.AnalogClock" android:versionCode="1" android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Info" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.INFO" />
            </intent-filter>
        </activity>
        <receiver android:name=".Widget" android:label="Custom Analog Clock">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" />
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest>  



following images used for analog clock 










   
UI when you run this tutorial

 


for Source code click here to Download.

Friday, May 17, 2013

Animated Text Tutorial

Text animation tutorial. text animation in round shape if you need to change shape little-bit changes required.


MainActivity.java

package com.example.animae.text;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;

public class MainActivity extends Activity {

 int colorAlpha=getTitleColor();;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new GraphicsView(this));
    }
    private static class GraphicsView extends View {
        private static final String AnimatedTxt =
            "devloped by Sandip Chaniyara (Sandy)";

        private Animation rotateAnim;

        public GraphicsView(Context context) {
            super(context);
        }
        private void createAnim(Canvas canvas) {
            rotateAnim = new RotateAnimation(0, 90, canvas.getWidth()/2, canvas.getHeight()/2);
            rotateAnim.setRepeatMode(Animation.REVERSE);
            rotateAnim.setRepeatCount(Animation.INFINITE);
            rotateAnim.setDuration(10000L);
            rotateAnim.setInterpolator(new AccelerateDecelerateInterpolator());

            startAnimation(rotateAnim);
        }
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);

            // creates the animation the first time
            if (rotateAnim == null) {
                createAnim(canvas);
            }

            Path circle = new Path();

            int centerX = canvas.getWidth() / 2;
            int centerY = canvas.getHeight() / 2;
            int r = Math.min(centerX, centerY);

            circle.addCircle(centerX, centerY, r, Direction.CW);
            Paint paint = new Paint();
            paint.setColor(Color.GREEN);
            paint.setTextSize(30);
            paint.setAntiAlias(true);

            canvas.drawTextOnPath(AnimatedTxt, circle, 0, 30, paint);
        }
    }
}
 
activity_main.xml

<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" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        android:marqueeRepeatLimit="marquee_forever"
        tools:context=".MainActivity" />
</RelativeLayout>


Android SQLite Tutorial

Example of SQLite Database for android.


AndroidSQLiteTutorialActivity.java

package com.androidhive.androidsqlite;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class AndroidSQLiteTutorialActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        DatabaseHandler db = new DatabaseHandler(this);
       
        /**
         * CRUD Operations
         * */
        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("Sandy", "9100000000"));
        db.addContact(new Contact("Darshak", "9199999999"));
        db.addContact(new Contact("Keyur", "9522222222"));
        db.addContact(new Contact("Raj", "9533333333"));

        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        List<Contact> contacts = db.getAllContacts();      

        for (Contact cn : contacts) {
            String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber();
                // Writing Contacts to log
        Log.d("Name: ", log);
       
        }
    }
}


Contact.java

package com.androidhive.androidsqlite;
public class Contact {

 //private variables
 int _id;
 String _name;
 String _phone_number;

 // Empty constructor
 public Contact(){

 }
 // constructor
 public Contact(int id, String name, String _phone_number){
  this._id = id;
  this._name = name;
  this._phone_number = _phone_number;
 }

 // constructor
 public Contact(String name, String _phone_number){
  this._name = name;
  this._phone_number = _phone_number;
 }
 // getting ID
 public int getID(){
  return this._id;
 }

 // setting id
 public void setID(int id){
  this._id = id;
 }

 // getting name
 public String getName(){
  return this._name;
 }

 // setting name
 public void setName(String name){
  this._name = name;
 }

 // getting phone number
 public String getPhoneNumber(){
  return this._phone_number;
 }

 // setting phone number
 public void setPhoneNumber(String phone_number){
  this._phone_number = phone_number;
 }
}


DatabaseHandler.java

package com.androidhive.androidsqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
 // All Static variables
 // Database Version
 private static final int DATABASE_VERSION = 1;
 // Database Name
 private static final String DATABASE_NAME = "contactsManager";
 // Contacts table name
 private static final String TABLE_CONTACTS = "contacts";
 // Contacts Table Columns names
 private static final String KEY_ID = "id";
 private static final String KEY_NAME = "name";
 private static final String KEY_PH_NO = "phone_number";
 public DatabaseHandler(Context context) {
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }
 // Creating Tables
 @Override
 public void onCreate(SQLiteDatabase db) {
  String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
    + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
    + KEY_PH_NO + " TEXT" + ")";
  db.execSQL(CREATE_CONTACTS_TABLE);
 }
 // Upgrading database
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // Drop older table if existed
  db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
  // Create tables again
  onCreate(db);
 }
 /**
  * All CRUD(Create, Read, Update, Delete) Operations
  */
 // Adding new contact
 void addContact(Contact contact) {
  SQLiteDatabase db = this.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put(KEY_NAME, contact.getName()); // Contact Name
  values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
  // Inserting Row
  db.insert(TABLE_CONTACTS, null, values);
  db.close(); // Closing database connection
 }
 // Getting single contact
 Contact getContact(int id) {
  SQLiteDatabase db = this.getReadableDatabase();
  Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
    KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
    new String[] { String.valueOf(id) }, null, null, null, null);
  if (cursor != null)
   cursor.moveToFirst();
  Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
    cursor.getString(1), cursor.getString(2));
  // return contact
  return contact;
 }

 // Getting All Contacts
 public List<Contact> getAllContacts() {
  List<Contact> contactList = new ArrayList<Contact>();
  // Select All Query
  String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
  SQLiteDatabase db = this.getWritableDatabase();
  Cursor cursor = db.rawQuery(selectQuery, null);
  // looping through all rows and adding to list
  if (cursor.moveToFirst()) {
   do {
    Contact contact = new Contact();
    contact.setID(Integer.parseInt(cursor.getString(0)));
    contact.setName(cursor.getString(1));
    contact.setPhoneNumber(cursor.getString(2));
    // Adding contact to list
    contactList.add(contact);
   } while (cursor.moveToNext());
  }
  // return contact list
  return contactList;
 }
 // Updating single contact
 public int updateContact(Contact contact) {
  SQLiteDatabase db = this.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put(KEY_NAME, contact.getName());
  values.put(KEY_PH_NO, contact.getPhoneNumber());
  // updating row
  return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
    new String[] { String.valueOf(contact.getID()) });
 }
 // Deleting single contact
 public void deleteContact(Contact contact) {
  SQLiteDatabase db = this.getWritableDatabase();
  db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
    new String[] { String.valueOf(contact.getID()) });
  db.close();
 }

 // Getting contacts Count
 public int getContactsCount() {
  String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
  SQLiteDatabase db = this.getReadableDatabase();
  Cursor cursor = db.rawQuery(countQuery, null);
  cursor.close();
  // return count
  return cursor.getCount();
 }
}


main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/demot"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>


Strobe Light Demo

This demo example used to Camera Flash light effect(StrobeLight).


StrobeLightConfig.java

package com.stwalkerster.android.apps.strobelight;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class StrobeLightConfig extends Activity {

    boolean check = false;
   
    Camera sandy;
    StrobeRunner runner;
    Thread bw;
    ImageButton btnClick;

    public final Handler mHandler = new Handler();

    public final Runnable mShowToastRunnable = new Runnable() {
        public void run() {

        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnClick = (ImageButton) findViewById(R.id.btnSwitch);
       
       
        runner = StrobeRunner.getInstance();
        runner.controller = this;

        if (runner.isRunning) {

        } else {
            try {
                sandy = Camera.open();

                if (sandy == null) {
                    return;
                }

                sandy.release();
            } catch (RuntimeException ex) {
                return;
            }
        }
       
        bw = new Thread(runner);
        bw.start();
       
        btnClick.setOnClickListener(new View.OnClickListener() {
           
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (check) {
                    bw = new Thread(runner);
                    bw.start();
                    check = false;
                } else {
                    check = true;
                    runner.requestStop = true;
                }           
            }
        });

        final SeekBar skbar = (SeekBar) findViewById(R.id.SeekBar01);
        skbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {


                runner.delay = 101 - progress;
                runner.delayoff = 101 - progress;

            }
        });

    }

    @Override
    protected void onStop() {
//        runner.requestStop = true;

        super.onStop();
    }
   
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
//        super.onBackPressed();

        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startActivity(startMain);
       
    }

}


StrobeRunner.java

package com.stwalkerster.android.apps.strobelight;

import android.hardware.Camera;

public class StrobeRunner implements Runnable {

    protected StrobeRunner()
    {
       
    }
   
    public static StrobeRunner getInstance()
    {
        return ( instance == null ? instance = new StrobeRunner() : instance );
    }
   
    private static StrobeRunner instance;
   
   
    public volatile boolean requestStop = false;
    public volatile boolean isRunning = false;
    public volatile int delay = 10;
    public volatile int delayoff = 500;
    public volatile StrobeLightConfig controller;
    public volatile String errorMessage = "";
   
    @Override
    public void run() {
        if(isRunning)
            return;
       
        requestStop=false;
        isRunning = true;
       
        Camera cam = Camera.open();
       
        Camera.Parameters pon = cam.getParameters(), poff = cam.getParameters();
       
        pon.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        poff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
       
        while(!requestStop)
        {
            try{
                cam.setParameters(pon);
                Thread.sleep(delay);
                cam.setParameters(poff);
                Thread.sleep(delayoff);
            }
            catch(InterruptedException ex)
            {
               
            }
            catch(RuntimeException ex)
            {
                requestStop = true;
                errorMessage = "Error setting camera flash status. Your device may be unsupported.";
            }
        }
       
        cam.release();
       
        isRunning = false;
        requestStop=false;
       
        controller.mHandler.post(controller.mShowToastRunnable);
    }

}



main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/TableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <SeekBar
        android:id="@+id/SeekBar01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:progress="0"
        android:layout_alignParentTop="true"
         >
    </SeekBar>
   
    <ImageButton
        android:id="@+id/btnSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/w_led_on"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"/>

</RelativeLayout>




click here to Download.