Question

I have written a code for strobe light from various sources but the problem is it is not working properly. Here is the code:

StrobeLight.java

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

 public class StrobeLight extends Activity implements OnClickListener
   {
    Button button;
    Camera cam;
    StrobeRunner runner;
    Thread bw;

    public final Handler mHandler = new Handler();

    public final Runnable mShowToastRunnable = new Runnable() {
        public void run() {
            showMessage();
        }
    };



    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.strobelight); 
        final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);

        button=(Button)findViewById(R.id.power);

        runner = StrobeRunner.getInstance();
        runner.controller = this;

        if(runner.isRunning)
        {   

        }
        else
        {
            try
            {

                cam = Camera.open();

                if(cam==null)
                {
                    togglebutton.setEnabled(false);
                    TextView t = (TextView)findViewById(R.id.TextView01);
                    t.setText(R.string.nocamera);
                    return;
                }

                cam.release();
            }
            catch(RuntimeException ex)
            {
                togglebutton.setEnabled(false);
                TextView t = (TextView)findViewById(R.id.TextView01);
                t.setText(R.string.nocamera);
                Toast.makeText(getApplicationContext(), "Error connecting to camera flash.", Toast.LENGTH_LONG).show();
                return;
            }
        } 


        togglebutton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks
                if (togglebutton.isChecked()) {
                    bw = new Thread(runner);
                    bw.start();
                } else {
                    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=progress;

            }
        });

        final SeekBar skbaroff = (SeekBar)findViewById(R.id.SeekBar02);
        skbaroff.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.delayoff=progress;

            }
        });


    }

    @Override
    protected void onStop() {
        runner.requestStop=true;
        ToggleButton togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
        togglebutton.setChecked(false);

        super.onStop();
    }

    public void showMessage()
    {
        String err = runner.errorMessage;
        runner.errorMessage="";
        if(!err.equals(""))
        {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, err, duration);
            toast.show();
        }

        ToggleButton togglebutton = (ToggleButton) findViewById(R.id.ToggleButton01);
        togglebutton.setChecked(false);
    }

StrobeRunner.java

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 StrobeLight 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);
    }

}

StrobeLight.xml (Layout)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/SmugeBlue"
    android:orientation="vertical" >

    <com.google.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:id="@+id/ad"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="a15332ae6427e75" />

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:layout_below="@id/ad" >

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:paddingLeft="5dp"
            android:textColor="@color/Yellow1"
            android:text="@string/speedon" >
        </TextView>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_below="@id/tableRow1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <SeekBar
            android:id="@+id/SeekBar01"
            android:layout_width="fill_parent"
            android:max="10"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:progress="1" >
        </SeekBar>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tableRow2"
        android:paddingTop="5dp" >

        <TextView
            android:id="@+id/TextView03"
            android:layout_width="wrap_content"
            android:paddingLeft="5dp"
            android:textColor="@color/Yellow1"
            android:text="@string/speedoff" >
        </TextView>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tableRow3" >

        <SeekBar
            android:id="@+id/SeekBar02"
            android:layout_width="fill_parent"
            android:max="10"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:progress="1" >
        </SeekBar>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="15dp" 
        android:layout_below="@id/tableRow4">

        <TextView
            android:id="@+id/TextView02"
            android:layout_width="wrap_content"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:textColor="@color/Yellow1"
            android:text="@string/healthwarning" >
        </TextView>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:layout_below="@id/tableRow5" >

        <TextView
            android:id="@+id/TextViewHW2"
            android:layout_width="wrap_content"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:textColor="@color/Orange1"
            android:text="@string/healthwarning2" >
        </TextView>
    </TableRow>

    <TableRow
        android:id="@+id/tableRow7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" >

        <ToggleButton
            android:id="@+id/ToggleButton01"
            android:layout_width="wrap_content"
            android:background="@drawable/strobetoggle"
            android:paddingLeft="5dp"
            android:paddingRight="5dp" 
            android:text="">
        </ToggleButton>
    </TableRow>

</RelativeLayout>

Now the problem is the seekbar is not working properly. When I slide any of the seekbars, the Camera start to blink like a dying bulb. I have the camera permission in my Manifest file.

Also, I have another class which acquires the flashlight. But when I am moving from this activity to other, it is causing the App to crash.

LauncherClass.java

public class LightsOn extends Activity implements OnKeyListener {
    ImageView button;
    Boolean flashon = true;
    private boolean hasFlash;
    private boolean needOnPause = true;
    Parameters myparas;
    private Camera mycamera;
    int flash = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.lightson);

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


        button = (ImageView) findViewById(R.id.power);
        button.setBackgroundResource(R.drawable.offswitch);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (flashon) {
                    Toast.makeText(LightsOn.this, "Flashlight off..!!",
                            Toast.LENGTH_SHORT).show();
                    button.setBackgroundResource(R.drawable.onswitch);
                    if (mycamera == null || myparas == null) {
                        return;
                    } else {
                        myparas = mycamera.getParameters();
                        myparas.setFlashMode(Parameters.FLASH_MODE_OFF);
                        mycamera.setParameters(myparas);
                        mycamera.stopPreview();
                        flashon = false;
                    }
                } else {
                    Toast.makeText(LightsOn.this, "Flashlight on..!!",
                            Toast.LENGTH_SHORT).show();
                    button.setBackgroundResource(R.drawable.offswitch);
                    if (mycamera == null || myparas == null) {
                        return;
                    } else {
                        myparas = mycamera.getParameters();
                        myparas.setFlashMode(Parameters.FLASH_MODE_TORCH);
                        mycamera.setParameters(myparas);
                        mycamera.startPreview();
                        flashon = true;
                    }
                }
            }
        });
    }

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

        if (!hasFlash) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("Sorry your device doesnt support flash.");
            dialog.setMessage("Press 'OKAY' to exit..");
            dialog.setPositiveButton("Okay.. :( :(",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                            moveTaskToBack(true);
                        }
                    });
            dialog.setNegativeButton("More Apps by AKSHAT JAISWAL",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Toast.makeText(LightsOn.this,
                                    "Account Coming Soon..", Toast.LENGTH_SHORT)
                                    .show();
                            finish();
                            moveTaskToBack(true);
                        }
                    });
            dialog.setNeutralButton("See website for more",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Toast.makeText(LightsOn.this,
                                    "Website to be Launched Soon..",
                                    Toast.LENGTH_SHORT).show();
                            finish();
                            moveTaskToBack(true);
                        }
                    });

            dialog.show();
        }

    }

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

    @Override
    protected void onPause() {
        try {
            if (!needOnPause) {
                super.onPause();
            }

            else {
                super.onPause();
                Toast.makeText(LightsOn.this, "Flashlight off..!!",Toast.LENGTH_SHORT).show();
                button.setBackgroundResource(R.drawable.onswitch);
                myparas.setFlashMode(Parameters.FLASH_MODE_OFF);
                mycamera.setParameters(myparas);
                mycamera.stopPreview();
                flashon = false;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

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

    @Override
    protected void onResume() {
        super.onResume();
        Toast.makeText(LightsOn.this, "Flashlight on..!!", Toast.LENGTH_SHORT)
                .show();
        button.setBackgroundResource(R.drawable.offswitch);
        if (hasFlash)
            myparas = mycamera.getParameters();
        myparas.setFlashMode(Parameters.FLASH_MODE_TORCH);
        mycamera.setParameters(myparas);
        mycamera.startPreview();
        flashon = true;
    }

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

    @Override
    protected void onStart() {
        super.onStart();
        // on starting the app get the camera params
        getCamera();
    }


    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        return false;
    }

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

        myparas = mycamera.getParameters();
        myparas.setFlashMode(Parameters.FLASH_MODE_OFF);
        mycamera.setParameters(myparas);
        mycamera.stopPreview();
        flashon = false;

        if (mycamera != null) {
            mycamera.release();
            mycamera = null;
        }
        Log.d("Camera", "Back Pressed");
    }

}
Was it helpful?

Solution 2

The reason your app is crashing when moving between the Apps is your onPause. You have not released the camera and hence its causing the app to crash when going out of the activity. At the onpause of your activity, just release the camera.

@Override
protected void onPause() {
    try {
        if (!needOnPause) {
            super.onPause();
        }

        else {
            super.onPause();
            Toast.makeText(LightsOn.this, "Flashlight off..!!",Toast.LENGTH_SHORT).show();
            button.setBackgroundResource(R.drawable.onswitch);
            myparas.setFlashMode(Parameters.FLASH_MODE_OFF);
            mycamera.setParameters(myparas);
            mycamera.stopPreview();
            flashon = false;
            mycamera.release();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

OTHER TIPS

did you use below permissions in AndroidManifest.xml?

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

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature android:name="android.hardware.camera.flash" />

Also you should remember to release camera after use.

Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open() it in onResume()).

One more thing if you are using Android SDK 2.1 then you should be aware of torch mode, which is not supported on samsung devices. See Here for more details.

Also have a look on here and here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top