How To Toggle Android Camera Flash On Microphone Audio Capture? - android

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

Related

I am making a torch App in android

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

Flash Light Not turn On?

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.

Constantly change TextView while microphone is on

I am trying to have my application start to record sound from the microphone when a button is pressed. I want it to print out the amplitude of the sound recorded while the microphone is on to my TextView object.
Here is my code for the RecordSound class:
import android.media.MediaRecorder;
public class RecordSound {
private MediaRecorder mRecorder = null;
public void start() {
if (mRecorder == 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 (Exception e) {
e.printStackTrace();
}
mRecorder.start();
}
}
public void stop() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public double getAmplitude() {
if (mRecorder != null) {
return mRecorder.getMaxAmplitude();
}
else {
return 0;
}
}
public boolean isOn() {
if (mRecorder == null) {
return false;
}
else {
return true;
}
}
}
Here is my code for the MainActivity class:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private RecordSound mRecorder = null;
private TextView tv = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button recordButton = (Button) findViewById(R.id.bRecord);
tv = (TextView)findViewById(R.id.data);
mRecorder = new RecordSound();
recordButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mRecorder.isOn()) {
mRecorder.stop();
}
else {
mRecorder.start();
}
if (mRecorder.isOn()) {
// long t= System.currentTimeMillis();
// long end = t+15000;
// while(System.currentTimeMillis() < end) {
// tv.setText(String.valueOf(mRecorder.getAmplitude()));
// }
//
tv.setText(String.valueOf(mRecorder.getAmplitude()));
}
}
});
while (mRecorder != null && mRecorder.isOn()) {
tv.setText(String.valueOf(mRecorder.getAmplitude()));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The code that is commented out is my attempt at making the microphone record and print the amplitude for the first fifteen seconds that the microphone is on.
Currently I am able to press the button to start recording. It will then print out the amplitude value to the TextView, but it is always 0.0. I've tried a while statement several different places, both in and out of the onClick() method. I can't seem to get the TextView to update dynamically while the microphone is recording sound.
I didn't really try to run your code and I don't know much about MediaRecoder in Android. But I guess the problem of your code is that your while loop is inside onCreate() method, and so the loop only runs when the onCreate() is called (in case of you haven't understood when Android system calls onCreate() method of your app, I suggest reading the Activity Lifecycle document). Clearly, your media recorder hasn't been started when the while loop runs, so this statment:
tv.setText(String.valueOf(mRecorder.getAmplitude()));
is not runned at all.
Then when you press the button for the first time, the media recoder is started and right after that, you get the amplitude, set the TextView value also for the first and only one time. The document of MediaRecorder.getMaxAmplitude() says that it returns
the maximum absolute amplitude measured since the last call, or 0 when
called for the first time
That's why you always get 0.0 display on the TextView.
In order to update the TextView dynamically while the microphone is on, you should maintain a background thread that check the media recoder and get amplitude periodically. For this purpose, you can consider using Timer and TimerTask. But since Android system doesn't allow you to update the UI from any thread other than the main thread, you may have to use Handler. I found this answer is useful for you.

I have problems with Android 4.0+ But no in 2.2

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.

Timer in control off hardware, making the flash stady

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.

Categories

Resources