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);
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" />
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.
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.
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.
I am new to Java / Android. I am developing an application for a school project, where I need to turn the blitz/flash from the camera on and off, like a strobe light, and I need to control how long it is on and off, right now I use Thread.sleep(); to control the wait time, but that is not accurate enough. I would like to use some type of timer maybe System.nanotime(), but I do not know a good way to use this, can any of you hackers help me?
I have tried this. hope there are a better way.
public void waiton(int ms){
long t0 = System.nanoTime()+ ms*1000000;
while(t0 > System.nanoTime()){
}
}
instead of sleep.
Threat.sleep(5);
I want to see how fast i can make a steady strobe light, it is not a strobe light i want in the end, but i want to see how fast i can make it. it is for a study! :P.
Here you can see the code i am working on.
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Switch;
public class FlashActivity extends Activity {
public Camera cam = Camera.open();
int i = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.flashview);
final Button onbutton = (Button)findViewById(R.id.onbutton);
final Button offbutton = (Button)findViewById(R.id.offbutton);
final Switch switchonoff = (Switch)findViewById(R.id.switch1);
onbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
i = 1;
new Thread(new Runnable() {
public void run() {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Camera.Parameters p = cam.getParameters(), p2 = cam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
p2.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cam.startPreview();
cam.cancelAutoFocus();
//cam.autoFocus(null);
while (i == 1){
cam.setParameters(p);
waiton(10);
cam.setParameters(p2);
waitoff(10);
}
}
}).start();
}
});
offbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
i = 0;
cam.stopPreview();
}
});
switchonoff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Switch nv = (Switch)v;
if(nv.isChecked()){
i = 1;
}else{
i = 0;
}
}
});
}
#Override
protected void onStop() {
super.onStop();
cam.stopPreview();
i = 0;
if (cam != null) {
cam.release();
}
}
#Override
protected void onPause() {
super.onStop();
cam.stopPreview();
if (cam != null) {
cam.release();
}
}
public void waiton(int ms){
long t0 = System.nanoTime()+ ms*1000000;
while(t0 > System.nanoTime()){
}
}
public void waitoff(int ms){
long t1 = System.nanoTime()+ ms*1000000;
while(t1 > System.nanoTime()){
}
}
};
Ignore the switch, right now i am converting from 2 buttons to a switch. But i want the flash to work before, i make some more changes to it.
If some of you have a way to control the blitz/flash without using the camera, that works for all newer android phones. That would be perfect.
I have some problems with auto-focus, that throw a error ones in a while, this may make my program more unstable, something with that the focus areal can not be 0,0,0,0, and do not know what i should change it to.
Later when it works, I think I will convert it to a state machine, to get some more functionality out of it. If it is possible for me :p.