I tried to make flashlight blink on pressing a button continuously until the button is pressed again. The flash is blinking continuously but I am unable to stop the blinking as the app freezes. Here is my Code:
public void Buts1(View view) {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
long blinkDelay = 50;//delay in ms
if(textView.getText().toString().equals("ON")){
boolean s=false;
while (textView.getText().toString().equals("ON")){
if(s){
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
}
s=false;
}else{
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
s=true;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I believe you're freezing the UI thread here. Also I don't see anything that sets the textView text to "OFF".
I've slightly modified your code, which assumes textView starts with the text "OFF" and will change to "ON" when you click the button. Clicking the button again will set the textView text to "OFF" and turn the flashing off. This works by being on a separate thread instead of the UI thread.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Thread flashThread = new Thread(new Runnable() {
#Override
public void run() {
boolean s=false;
long blinkDelay = 50;//delay in ms
while (textView.getText().toString().equals("ON")){
if(s){
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
}
s=false;
}else{
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
s=true;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
if(textView.getText().toString().equalsIgnoreCase("OFF")){
textView.setText("ON");
flashThread.start();
}else{
flashThread.interrupt();
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
textView.setText("OFF");
}
}
});
Related
I'm developing an application where if the screen of the phone is facing up the flashlight starts blinking. If the screen of the phone is facing downwards the flashlight is suppose to stop blinking. For detecting whether if the screen of the phone is facing up or down I'm using the accelerometer. The code to detect the orientation of the screen is here:
#Override
protected void onResume() {
super.onResume();
smAccelerometer.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
smAccelerometer.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
int type = event.sensor.getType();
if (type == Sensor.TYPE_ACCELEROMETER) {
float gz = event.values[2];
if (mGZ == 0) {
mGZ = gz;
} else {
if ((mGZ * gz) < 0) {
mEventCountSinceGZChanged++;
if (mEventCountSinceGZChanged == MAX_COUNT_GZ_CHANGE) {
mGZ = gz;
mEventCountSinceGZChanged = 0;
if (gz > 0) {
Log.d(TAG, "now screen is facing up.");
Toast toast = Toast.makeText(MainActivity.this, "Up", Toast.LENGTH_SHORT);
toast.show();
flashlightFrequency();
} else if (gz < 0) {
Log.d(TAG, "now screen is facing down.");
Toast toast = Toast.makeText(MainActivity.this, "Down", Toast.LENGTH_SHORT);
toast.show();
}
}
} else {
if (mEventCountSinceGZChanged > 0) {
mGZ = gz;
mEventCountSinceGZChanged = 0;
}
}
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
As you can see from this code, whenever the screen is facing up i call the method flashlightFrequency() which turns the flashlight on and off in intervals:
public void flashlightFrequency() {
String myString = "0101010101";
int frequency = 2000; //Delay in ms
CameraManager camManager;
String cameraId = null; // Usually front camera is at 0 position.
camManager = (CameraManager) getApplicationContext().getSystemService(Context.CAMERA_SERVICE);
try {
cameraId = camManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i <= myString.length(); i++) {
if (i == myString.length()) {
flashlightFrequency();
}
if (myString.charAt(i) == '0') {
try {
camManager.setTorchMode(cameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
} else {
try {
camManager.setTorchMode(cameraId, false);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(frequency);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The accelerometer works fine and I'm able to detect the orientation of the screen UNTIL I call the method flashlightFrequency(). When the flashlight starts the phone no longer registers motions. It seems like the flashlight cancels the SensorListener. Whenever the flashlight is turned on I can't use the accelerometer to detect the orientation of the screen.
The solution was to implement the flashlightFrequency() in an IntentService class. By doing that the flashlight will run in the background and therefore not interfere with the accelerometer.
I am new to android. I have made a simple torch light application. Everything is perfectly fine but the blinking segment is making the problem. If I presses the button "Blink", flashlight starts blinking but when I again presses the button, blinking doesn't stop rather than blinking adds up. For example if I presses the button two times then the function executes two times. If its in order then it must stop on second press. Anyone have a solution about it. please help.
Here is the MainActivity.java
package epicerastudios.torch;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private ImageButton mBlinkOnOffButton;
private Boolean isTorchOn;
private Boolean isBlinkOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FlashLightActivity", "onCreate()");
setContentView(R.layout.activity_main);
mTorchOnOffButton = (ImageButton) findViewById(R.id.Switch);
mBlinkOnOffButton = (ImageButton) findViewById(R.id.Blink) ;
isTorchOn = false;
isBlinkOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
mBlinkOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isBlinkOn) {
turnOffBlink();
isBlinkOn = false;
} else {
turnOnBlink();
isBlinkOn = true;
}
}
});
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
mTorchOnOffButton.setImageResource(R.drawable.btn_on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
mTorchOnOffButton.setImageResource(R.drawable.btn_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOnBlink() {
mBlinkOnOffButton.setImageResource(R.drawable.blink_on);
String myString = "0101010101";
long blinkDelay = 300; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
}
}
catch (Exception e){
e.printStackTrace();
}
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void turnOffBlink() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
mBlinkOnOffButton.setImageResource(R.drawable.blink_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
if(isTorchOn || isBlinkOn){
turnOffFlashLight();
turnOffBlink();
}
}
#Override
protected void onPause() {
super.onPause();
if(isTorchOn || isBlinkOn){
turnOffFlashLight();
turnOffBlink();
}
}
#Override
protected void onResume() {
super.onResume();
if(isTorchOn || isBlinkOn){
turnOnFlashLight();
turnOnBlink();
}
}
}
Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="epicerastudios.torch.MainActivity"
android:background="#fff">
<ImageButton
android:id="#+id/Switch"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#fff"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/btn_off" />
<ImageButton
android:id="#+id/Blink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/Switch"
android:layout_alignLeft="#id/Switch"
android:background="#fff"
android:src="#drawable/blink_off" />
</RelativeLayout>
I think it's becouse of your for loop which is not stopped when you press the button again.
public void turnOnBlink() {
mBlinkOnOffButton.setImageResource(R.drawable.blink_on);
String myString = "0101010101";
long blinkDelay = 300; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if(!isBlinkOn) {
break;
}
if (myString.charAt(i) == '0') {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
button
mBlinkOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isBlinkOn) {
isBlinkOn = false;
turnOffBlink();
} else {
isBlinkOn = true;
turnOnBlink();
}
}
});
I am developing an Android application that converts morse code to sounds and flashes. The flashes part works well, but I'm having troubles with sound part.
here is the code I have so far:
SoundPool sp =new SoundPool.Builder().setMaxStreams(1).build(); // declare before onCreate()
int soundId = sp.load(this,R.raw.beep,1); // declared inside onCreate()
public void flashCode(View view){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},0);
}
}
int dotTime=150; // in milliseconds
long ms=System.currentTimeMillis();
long ms2=System.currentTimeMillis();
//
//int streamID=mSoundPool.load(this,R.raw.beep,1);
for (int i=0;i<code.length();i++)
{
streamID=sp.play(soundId,1,1,1,1,1.0f);
sp.pause(streamID);
if (String.valueOf(code.charAt(i)).contentEquals("."))
{
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
ms=System.currentTimeMillis();
ms2=System.currentTimeMillis()+dotTime;
camManager.setTorchMode(cameraId, true);
//mSoundPool.resume(streamID);
while (ms<ms2){
ms=System.currentTimeMillis();
}
camManager.setTorchMode(cameraId, false);
//mSoundPool.stop(streamID);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
if (String.valueOf(code.charAt(i)).contentEquals("-"))
{
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
ms=System.currentTimeMillis();
ms2=System.currentTimeMillis()+dotTime*3;
camManager.setTorchMode(cameraId, true);
//mSoundPool.resume(streamID);
while (ms<ms2){
ms=System.currentTimeMillis();
}
camManager.setTorchMode(cameraId, false);
//mSoundPool.stop(streamID);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
if (String.valueOf(code.charAt(i)).contentEquals(" "))
{
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
ms=System.currentTimeMillis();
ms2=System.currentTimeMillis()+dotTime;
camManager.setTorchMode(cameraId, false);
while (ms<ms2){
ms=System.currentTimeMillis();
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
}
What I want is the play a sound when I turn flash on and off, but only during that time. I tried with SoundPool but when I tested it out, the flash and sounds weren't synced and MediaPlayer it even skipped some sounds.
Could you tell me what I'm doing wrong or tell me how would you do it.
i want to add flashlight Blinking mode in android studio with a button. but i don't know that how can i put a code and how to implement this code with a button. because i want that if i press button then flashlight start blinking.
can anyone tell me that how can i implement this code with a button?
String[] list1 = { "1", "0", "1", "0", "1", "0", "1", "0", "1", "0" };
for (int i = 0; i < list1.length; i++) {
if (list1[i].equals("0")) {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
}
You can use this code for blink i make this as method :
private void BlinkFlash(){
String myString = "010101010101";
long blinkDelay =50; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
} else {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and it will call like this :
BlinkMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BlinkFlash();
}
});
Hope this will work for you and yeah make string long if you want blink long time then
All of these below codes put inside any where in your activity/fragment:
Status, handler, Camera variables:
boolean isOn[] = {false};
boolean[] isBlinking = {false};
Handler handler = new Handler();
CameraManager camManager = null;
String cameraId = null;
Handle button click listener on your activity/fragment:
camManager = (CameraManager) view.getContext().getSystemService(Context.CAMERA_SERVICE);
buttonFlash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isBlinking[0]){
BlinkMode(view);
isBlinking[0] = true;
} else {
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
isBlinking[0] = false;
}
}
});
Blinking method:
Thread splashThread2;
private void BlinkMode(View view){
splashThread2 = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(100);
if(!isOn[0]){
OnFlash();
isOn[0] = true;
} else {
isOn[0] = false;
OffFlash();
}
}
} catch (Exception e) {
}
}
};
splashThread2.start();
}
Handle when goback
#Override
public void onStop() {
super.onStop();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
#Override
public void onPause() {
super.onPause();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
On/Off Method for new version of Android:
private void OnFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
isOn[0] = true;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
private void OffFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, false); //Turn ON
isOn[0] = false;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
After I take 3 shot camera stops responding (crashes).If I try to restart application camera state == locked and default camera gets locked too.
Example code:
private Runnable SimpleShot=new Runnable()
{
#Override
public void run()
{
int i=0;
while (i<7)
{
simpleShot();
try
{
Thread.sleep(1500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
i++;
}
}
};
private void simpleShot()
{
//System.gc();
camera.takePicture(shutterCallback,rawCallback, this);
}
If I don't use thread camera doesn't response after 3rd shot too. Please Help.
In end method onPictureTaken, I call camera.startPreview();
LogCat http://pastebin.com/qDcthyNe
#Override
public void onPictureTaken(byte[] paramArrayOfByte, Camera paramCamera)
{
if(Utils.isSDAval() && Utils.PrepareAppFolder())
{
String path = Utils.APP_FOLDER+"/"+"APP"+"_"+Utils.getDate()+ CameraPrefsActivity.EXT_PIC;
try
{
FileOutputStream os = new FileOutputStream(path);
os.write(paramArrayOfByte);
os.close();
} catch (Exception e)
{
Utils.ShowInfo(this,getString(R.string.app_error_io));
e.printStackTrace();
}
Utils.ShowInfo(this,getString(R.string.app_shot_ok));
SharedPreferences main_pref = PreferenceManager.getDefaultSharedPreferences(this);
String string_format = main_pref.getString("pref_preview_time","0");
int timer_val = -1;
if(string_format.contains("0"))
{
timer_val = -1;
}
if(string_format.contains("1"))
{
timer_val = 1;
}
if(string_format.contains("3"))
{
timer_val = 3;
}
if(string_format.contains("5"))
{
timer_val = 5;
}
if(string_format.contains("10"))
{
timer_val = 10;
}
if(timer_val > 0)
{
Intent intent = new Intent(this,CameraPreview.class);
CameraPreview.setupActivity(path,timer_val);
startActivity(intent);
}
}
else
{
Utils.ShowInfo(this,getString(R.string.app_error_sd));
}
paramCamera.startPreview();
}
This guy had the same problem and apparently its the emulator, try running it on a real device it worked for him.