I am an android developer , i want to on my mobile flashlight .
I have Nexus5. My code is below.Any one can help me?
Tell me what is missing here?
I have set permissions, no error occred but not app works fine.
Main Activity.Java
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.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
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;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
/*
* First check if device is supporting flashlight or not
*/
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
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) {
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
/*
* Switch button click event to toggle flash on/off
*/
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
/*
* Get the camera
*/
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;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Turning Off flash
*/
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* Playing sound
* will play button toggle sound on flash on / off
* */
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
}else{
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.btn_switch_on);
}else{
btnSwitch.setImageResource(R.drawable.btn_switch_off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
any my Android.manifest file is here.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidhive.flashlight"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.androidhive.flashlight.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
i am posting 2nd time , i did not get solution first time.
i have read many tutorials.
These are the permissions in Manifest. I forgot to tell you, my bad!
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
There are many reasons why this might not work. hasFlash is probably not the best way to check for flash. You probably want to check for FLASH_MODE_ON in addition to FLASH_MODE_TORCH. You may need to have a preview and implement the SurfaceHolder.Callback. I would probably increase android:targetSdkVersion="17" while you're at it. I just built an open source flashlight. It works on Nexus 5 if you want to look at/use the source code. Flashlight by Joe github
You have to open your camera before accessing flash light. You declared Camera but not use it. Try this.
public void cameraon() {
cam = Camera.open();
par = cam.getParameters();
par.setFlashMode(Parameters.FLASH_MODE_ON);
par.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(par);
cam.startPreview();
}
public void cameraoff() {
par.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(par);
cam.stopPreview();
cam.release();
}
I know its late however may be it can help someone else. The reason your code does not work is that you are using the camera and media player simultaneously. if the flash gets on , your media player will stop working. Or if the media player is running then you can't get instance of camera which is required to light the Flash.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have created simple flashlight app. There isn't any error at compile. but when the icon is clicked it just stop unexpectedly. I have tried in both physical android phone and emulator. both comes up with same result. I cant see any problem in the code. can someone recify this problem.
Flashlight.java (Activity)
package flashlight.turnmeyon.crystal.laser;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
public class Flashlight extends AppCompatActivity {
ImageButton imagebutton;
Camera camera;
Camera.Parameters parameters;
boolean isflash = false;
boolean ison = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_flashlight);
imagebutton = (ImageButton) findViewById(R.id.buttonOn);
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
camera.open();
parameters = camera.getParameters();
isflash = true;
}
imagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isflash) {
if (!ison) {
imagebutton.setImageResource(R.drawable.buttonon);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
ison = true;
} else {
imagebutton.setImageResource(R.drawable.buttonof);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
ison = false;
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(Flashlight.this);
builder.setTitle("Error...........");
builder.setMessage("Flashlight is not avaliable");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
AlertDialog alertdialog = builder.create();
alertdialog.show();
}
}
});
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
}
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#757575"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageButton
android:id="#+id/buttonOn"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:background="#757575"
android:src="#drawable/buttonof"
android:scaleType="fitCenter"
android:layout_marginTop="80dp"
android:layout_marginRight="80dp"
android:layout_marginLeft="80dp"
android:layout_marginBottom="40dp"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Here is reference for you.
I created Flash Example. Please review below code.
public class MainActivity extends AppCompatActivity {
ImageView switch_on_off;
private Camera camera;
Parameters params;
public boolean isSupportFlash, isFlashLighOn;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isSupportFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isSupportFlash) {
Toast.makeText(getApplicationContext(), "Your device does not support flash. ", Toast.LENGTH_LONG).show();
}
switch_on_off = (ImageView) findViewById(R.id.switch_on_off);
connectCameraService();
switch_on_off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashLighOn) {
offFlashLight();
switch_on_off.setImageResource(R.drawable.switch_off);
} else {
onFlashLight();
switch_on_off.setImageResource(R.drawable.switch_on);
}
}
});
}
public void onFlashLight() {
if (!isFlashLighOn) {
status = "ON";
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashLighOn = true;
switch_on_off.setImageResource(R.drawable.switch_on);
}
}
public void offFlashLight() {
if (isFlashLighOn) {
status = "ON";
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashLighOn = false;
switch_on_off.setImageResource(R.drawable.switch_off);
}
}
public void connectCameraService() {
if (camera == null) {
camera = android.hardware.Camera.open();
params = camera.getParameters();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
offFlashLight();
}
#Override
protected void onPause() {
super.onPause();
offFlashLight();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
/*if (isSupportFlash) {
onFlashLight();
}*/
}
#Override
protected void onStart() {
super.onStart();
connectCameraService();
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
}
Required permission
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
Create a simple Torch application which can put on the Camera Flash and put it off. This application should have a simple UI which can put On the Flash and also put it Off.
After 1 minute of continuous use, the UI should prompt the user he wants to keep use the Torch. If the user says Yes the Torch shall remain on for another minute and this cycle shall repeat. If the user says No, the Torch shall be put off.
Creating a simple torch app is easy and I have made torch app but the second thing which is mentioned in the question to make a prompt after 1 minute that thing I am not able to understand can anyone help?
here is my code of flashlight can anyone tell me where to change in it.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity
{
`enter code here`private boolean isLightOn=false;
private Camera camera;
private Button btn;
#Override
protected void onStop()
{
super.onStop();
if(camera!= null)
camera.release();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
Context context=this;
PackageManager pk= context.getPackageManager();
if(!pk.hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Log.e("err","Device has no camera");
return;
}
camera=camera.open();
final Parameters p= camera.getParameters();
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(isLightOn)
{
Log.i("info","FlashLight is turn off");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn=false;
}
else
{
Log.i("info","FlashLight is turn On!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLightOn=true;
}
}
});
}
}
First create a XML having a switch widget. Then connect it with Java, Using onOffSwitch = (Switch) findViewById(R.id.switch1);
Get CameraManager so that u can manage camera's element(which is the flashLight), Using mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
3.Get current phone's camera ID so that you can instruct android which camera to Point , Using mCameraId = mCameraManager.getCameraIdList()[0];
Turn on using : mCameraManager.setTorchMode(mCameraId, true);
Turn off Using : mCameraManager.setTorchMode(mCameraId, false);
Code:
public class TorchActivity extends AppCompatActivity {
CameraManager mCameraManager;
String mCameraId;
Switch onOffSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_torch);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
onOffSwitch = (Switch) findViewById(R.id.switch1);
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
Boolean isFlashAvailable = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (isFlashAvailable)
{
onOffSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onOffSwitch.isChecked()) {
try {
mCameraManager.setTorchMode(mCameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
else{
try {
mCameraManager.setTorchMode(mCameraId, false);
}
catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
});
}else
{
Toast.makeText(this, "No Flash Support Found!", Toast.LENGTH_SHORT).show();
}
}
//Use these permissions!
Min SDK should be - 23
//<uses-permission android:name="android.permission.CAMERA" />
//<uses-permission android:name="android.permission.FLASHLIGHT" />
//<uses-feature android:name="android.hardware.camera" />
//<uses-feature android:name="android.hardware.camera.flash" />
if(!pk.hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Log.e("err","Device has no camera");
return;
}
camera=camera.open();
final Parameters p= camera.getParameters();
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if(isLightOn)
{
Log.i("info","FlashLight is turn off");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn=false;
}
else
{
Log.i("info","FlashLight is turn On!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLightOn=true;
new Handler().postDelayed(new Runnable() {
// Using handler with postDelayed called runnable run method
#Override
public void run() {
//Show your Alert box here
new AlertDialog.Builder(context) // you can use getApplicationContext() or your activityname.this as context
.setTitle("Do You Want to continue")
.setMessage("Are you sure you want to continue?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Do nothing, Torch continues
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// torch off
Log.i("info","FlashLight is turn off");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLightOn=false;
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}, 60000); //60000milliseconds = 60 sec = 1min.
// It will show alertbox after 1 min .
}
}
});
}
}
To run some code after a certain delay, you can do the following (where 1000 is the delay in milliseconds):
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
// code to show prompt goes here
}
}, 1000);
You can make this into a method, which gets called each time the user acknowledges the prompt.
For dialog box check this.
Check this link for flash On/Off.
for Flash Off after one min use Handler.
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//Turn off flash
}
};
handler.postDelayed(r, 1000);
How can I keep the flashlight on in the background even when I switch to next activity or next application. Also my flashlight turns off automatically when I my screen locks and I want to keep my flash glowing even the screen locks.
This is my current code:
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Camera.Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savedform);
toolbar= (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(SavedForm.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) {
// closing the application
finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
} else {
// turn on flash
turnOnFlash();
}
}
});
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Error. Failed to Open", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
// Playing sound
// will play button toggle sound on flash on / off
private void playSound(){
if(isFlashOn){
mp = MediaPlayer.create(SavedForm.this, R.raw.flashoff);
}else{
mp = MediaPlayer.create(SavedForm.this, R.raw.flashon);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.button_on);
}else{
btnSwitch.setImageResource(R.drawable.button_off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOnFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
if(hasFlash)
turnOffFlash();
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_savedform, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id==android.R.id.home){
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
}
The best way to do is by Running a Background service that handles the Flashlight.
You need to put your FlashLight Start and Stop code inside the OnStart and onDestroy of the Service. That you need to do on your own
First of all create a class named FlashLightService that extends the Service
public class FlashLightService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
// Put Your Code To Start the FlashLight Over Here
}
#Override
public void onDestroy() {
// Put Your Code To Stop the FlashLight Over Here
}
Now from any Activity you can start and stop the Flashlight according to your need
To start The FlashLight
startService(new Intent(this, FlashLightService.class));
To stop the FlashLight
stopService(new Intent(this, FlashLightService.class));
Do not forget to mention this in your AndroidManifest.xml
Let me know if this works! :)
Remove these code or line.
`
#Override
protected void onStop() {
super.onStop();
// on stop release the camera`enter code here`
if (camera != null) {
camera.release();
camera = null;
}
`
It worked for me.
I am not an android expert but I would recommend,
run it as service or run it as singleton thread.
The flash depends on the camera. Your onStop method contains: camera.release() which will release the camera hardware overriding any other acquisition methods implemented.
You could use background service to control the camera hardware. Start it from an activity and stop the service when your app is closed.
The following code works. It makes the camera flash to blink on any audio captured by the Android phone microphone. It works on Samsung Galaxy S Duos.
All I want is to make it more stable because of the presence of the thread.
package net.superlinux.concertlights;
import java.io.IOException;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
/**
* #author راني فايز أحمد
*
*/
public class FlashOnMicrophone extends Activity {
/* (non-Javadoc)
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
// Toggle button that switches Camera-flash-to-blink on and off.
ToggleButton flash_on_microphone_toggleButton;
//SeekBar to set the microphone sensitivity level at which the flash will blink.
SeekBar seekBar;
//Camera Object
Camera camera;
/* Preparing a Thread to make the GUI seperate from Camera and Microphone.
Otherwise the phone will hang and freeze. */
Thread thread;
//mRecoder is the microphone object
MediaRecorder mRecorder;
//A flag used in the thread to turn on the flash blinking .
boolean isLightOn = false;
//sensitivity holds the minimum amplitude value at which the camera flash will blink
int sensitivity=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setContentView(R.layout.flash_on_microphone);
flash_on_microphone_toggleButton = (ToggleButton) findViewById(R.id.flash_on_microphone_button);
seekBar=(SeekBar)findViewById(R.id.seekbar);
//SeekBar of sensitivity default is 1500.
seekBar.setProgress(1500); //default sensitivity value
//The following event listener sets the global variable 'sensitivity' so it can be taken by the thread.
seekBar.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) {
// TODO Auto-generated method stub
//There is a TextView not mentioned in the code here, but it's in the XML layout.
//We use this TextView to display the variable sensitivity
//We also set the current position of the SeekBar button as the sensitivity.
sensitivity=progress;
((TextView)findViewById(R.id.microphone_sensitivity_textview)).setText(getString(R.string.microphone_sensitivity_level)+"= "+sensitivity);
}
});
PackageManager pm = this.getPackageManager();
//The following makes sure that a camera exists. else warn the app user and quit the app.
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "Device has no camera!",Toast.LENGTH_LONG).show();
finish();
return;
}
//Display has to be always unlocked to keep the flash light working.
getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//Open the Camera, and get its parameters to set the camera settings.
camera = Camera.open();
final Parameters p = camera.getParameters();
//We open a thread , but will run it after defining the microphone.
thread = new Thread(new Runnable() {
#Override
public void run() {
//we make the thread running for ever.
// every time isLightOn is true , we blink the flash light.
// and turn on the flash light if the microphone amplitude exceeds the value of the variable 'sensitivity'
while(true){
while (isLightOn) {
try {
int volume_level = mRecorder.getMaxAmplitude();
if (volume_level>sensitivity){
Log.i("info", "torch is turn off!");
// make the flash off and the camera preview off too.
//we cannot reach the flash light device without the camera preview. both are attached to the other
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
//now make the flash on and the camera preview on too.
Log.i("info", "torch is turn on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
//The camera preview will not work in this case because the on & off on the preview pameter is very fast
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("info", "torch is turn off!");
e.printStackTrace();
}
}
}
}
});
/*
Prepare the audio capture source to be the microphone.
and save the audio in the file "/dev/null" .
This is a special file in Linux. Please know that Android is a Linux distribution.
This file acts like black hole in the space. You may also think of it as the dumpster of the unwanted and exiled data.
We, here , do not want to save the sound. All what we want is to sense it, and nothing else. so we throw it away in "/dev/null" .
*/
mRecorder= new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder. setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//now turn on the microphone and the thread.
mRecorder.start();
thread.start();
//the event of turning on/off the flash-on-microphone sensing
flash_on_microphone_toggleButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//flip isLightOn between true and false.
isLightOn = !isLightOn;
}
});
}
#Override
public void onBackPressed() {
//clean up and activity shutdown.
mRecorder.stop();
thread.interrupt();
super.onBackPressed();
}
#Override
protected void onRestart() {
//re-run the camera on application minimize and maximize.
camera=Camera.open();
super.onRestart();
}
}
i am doing a FlashLight and when a friend try it, he got a crash.
He have V 4.0+
Here my logcat:
https://github.com/Hersix/LogCat-FlashLightAPP/commit/9fa44813cdad14f461c14070cc0eea6e8c29c93a
I am newbie, but i read that Apps with Threads in version 4.0+ Crashes, so.. i don´t understand good, but, how can i put all my code without a thread ?
This is my app code:
package flash.light.app;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitByBackKey();
//moveTaskToBack(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void exitByBackKey() {
AlertDialog alertbox = new AlertDialog.Builder(this)
.setMessage("Do you want to Exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
finish();
//close();
}
})
.setNeutralButton("Rate us!", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
{
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Couldn´t launch Google Play",
Toast.LENGTH_LONG).show();
}
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
ImageButton btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AdView adView = (AdView) findViewById(R.id.adView);
adView.loadAd(new AdRequest());
ImageView ButtonScr = (ImageView) findViewById(R.id.imageView1);
ButtonScr.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent Screen = new Intent (MainActivity.this, ScreenActivity.class);
startActivity(Screen);
}});
// flash switch button
btnSwitch = (ImageButton) findViewById(R.id.imageButton1);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton(AlertDialog.BUTTON_POSITIVE,"OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent Screen = new Intent (MainActivity.this, ScreenActivity.class);
startActivity(Screen);
Toast.makeText(MainActivity.this, "You can use our Screen Light :)",
Toast.LENGTH_LONG).show();
// closing the application
// finish();
}
});
alert.show();
return;
}
// get the camera
getCamera();
// displaying button image
toggleButtonImage();
//Orientación de la APP Vertical
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//Codigo para que no se apague la pantalla :D
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
// Switch button click event to toggle flash on/off
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlashOn) {
// turn off flash
turnOffFlash();
// RelativeLayout layout = (RelativeLayout)findViewById(R.id.background);
// layout.setBackgroundResource(R.drawable.image6);
} else {
// turn on flash
turnOnFlash();
// RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
//layout.setBackgroundResource(R.drawable.slender);
}
}
});
}
// Get the camera
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;
}
// play sound
// playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
// Turning Off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
// playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
// Playing sound
// will play button toggle sound on flash on / off
// private void playSound(){
// if(isFlashOn){
// mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
// }else{
// mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
// }
// mp.setOnCompletionListener(new OnCompletionListener() {
// #Override
// public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// mp.release();
// }
// });
// mp.start();
// }
/*
* Toggle switch button images
* changing image states to on / off
* */
private void toggleButtonImage(){
if(isFlashOn){
btnSwitch.setImageResource(R.drawable.on);
}else{
btnSwitch.setImageResource(R.drawable.off);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
// on pause turn off the flash
turnOffFlash();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
// on resume turn on the flash
//CREO QUE ES PARA QUE SE ENCIENDA APENAS SE ABRE.
if (hasFlash){
turnOnFlash();
} else {
Toast.makeText(MainActivity.this, "You can use our Screen Light :)",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onStart() {
super.onStart();
// on starting the app get the camera params
getCamera();
}
#Override
protected void onStop() {
super.onStop();
// on stop release the camera
if (camera != null) {
camera.release();
camera = null;
}
}
}
How can i do, to run a SIMPLE app (like this, its a simple flashlight) in ALL or almost all devices?
Thanks and sorry for my english
your issue is in getCamera(), in the line Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
it looks like e.getMessage() is returning null, hence the crash.
you should probably use the format Log.e(TAG, "getCamera", e); which will print the stack trace for the exception (and not crash your app)
Replace
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
with
Log.e("MainActivity", "Camera Error. Failed to Open. Error: " + e.getMessage());
then figure out why the camera doesn't work.