Not Working Properly Orientation of Flashlight Android Application - android

I am creating Flashlight Android App..and facing below problem..Please guide me ...
when i press button in potrait mode Flash light is goes on and when I rotate to landscape mode flash light goes off..
ImageButton imagebuttonon, imagebuttonoff;
public static Camera cmr;
Camera.Parameters parameters;
boolean isFlash = false;
boolean isOn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagebuttonoff = (ImageButton) findViewById(R.id.imagebuttonoff);
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
{
cmr = Camera.open();
parameters = cmr.getParameters();
isFlash = true;
}
imagebuttonoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isFlash)
{
//if flash light is not on
if (!isOn) {
imagebuttonoff.setImageResource(R.drawable.onswitch); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cmr.setParameters(parameters);
cmr.startPreview();
isOn = true;
} else {
imagebuttonoff.setImageResource(R.drawable.offswitch);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cmr.setParameters(parameters);
cmr.stopPreview();
isOn = false;
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error");
builder.setMessage("Flash light not available");
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 onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
cmr.stopPreview();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onResume() {
super.onResume();
if (isOn)
cmr.startPreview();
}
#Override
protected void onStart() {
super.onStart();
cmr.startPreview();
}
#Override
protected void onStop() {
super.onStop();
if (cmr != null)
cmr.release();
cmr = null;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.getBoolean("mode", false);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}

I have a solution for this, which will also be helpful for others who are interested in creating a Flashlight Android Application, as described on my blog.
I just entered these lines in the Manifest.xml file.
<activity android:name=".MainActivity" android:configChanges="orientation|screenSize">

Related

Bar code detector reads QR-code several times

I`m trying to create bar code reader for my app, and it works fine, but the problem is when I keep focusing on QR-Code, it continues to read and never stops!!!
How can I make this happen only once?
In this code, it continues to "Toast" until I close the app, and when I use Intent for for closing the current activity and open another activity, the activity opens several times!!!
Here is the code:
public class BarcodeCaptureActivity extends AppCompatActivity {
private SurfaceView camera_preview;
TextView text;
BarcodeDetector barcodeDetector;
CameraSource cameraSource;
final int requestCameraPermissionID = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode_capture);
camera_preview = (SurfaceView) findViewById(R.id.camera_preview);
text = (TextView) findViewById(R.id.text);
barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource = new CameraSource.Builder(this, barcodeDetector).setRequestedPreviewSize(640, 480).build();
camera_preview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(BarcodeCaptureActivity.this, new String[]{Manifest.permission.CAMERA},requestCameraPermissionID);
return;
}
try {
cameraSource.start(camera_preview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcode = detections.getDetectedItems();
if (qrcode.size() != 0){
text.post(new Runnable() {
#Override
public void run() {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
text.setText(qrcode.valueAt(0).displayValue);
String title = text.getText().toString();
Toast.makeText(BarcodeCaptureActivity.this, "" + title, Toast.LENGTH_SHORT).show();
finish();
}
});
}
}
});
}
Thank for any help...
UPDATE
Problem solved with adding onDestroy and onPause methods...
#Override
protected void onPause() {
super.onPause();
cameraSource.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
cameraSource.stop();
}

Code to remain flashlight when activity is on paused and screen lock is pressed

i am implementing flashlight, and i have called all the functions i,e onDestroy() onBackpressed() to remain my flash light on. but i have bug that if i pressed on back and after that screen is locked the flashlight switches off after few seconds. kindly help me with the code.
public class MainActivity extends AppCompatActivity {
ImageButton btnSwitch;
Camera camera;
Camera.Parameters parameters;
boolean isflash = false;
boolean ison = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
if(getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH));
{
try {
camera = Camera.open();
parameters = camera.getParameters();
isflash = true;
}catch (Exception e ){
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
}
btnSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isflash)
{
if (!ison)
{
btnSwitch.setImageResource(R.drawable.off);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
ison = true;
}
else {
btnSwitch.setImageResource(R.drawable.btn_switch_on);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.stopPreview();
ison = false;
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error.....");
builder.setMessage("FlashLight is not available on this device....");
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(!ison){
if (camera!=null)
{
camera.release();
camera = null;
}
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(!ison){
if (camera!=null)
{
camera.release();
camera = null;
}
}
}
#Override
protected void onPause() {
super.onPause();
if(!ison){
if (camera!=null)
{
camera.release();
camera = null;
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(!ison) {
if (camera != null) {
camera.release();
camera = null;
}
}
}
}

Flashlight app crash within secs of icon clicked [closed]

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" />

Pointing to wrong UI from posted Runnable after screen orintation changes

This is my little test program. My problem is that from run() method I access to fields of wrong (old) Activity, which was destroyed after screen orientation changed. What's the way to handle this situation?
And, by the way, I must have my activity been recreated, because in real application I have different layouts for portrait and landscape modes!
public class MainActivity extends Activity {
private EditText edit;
private Button button;
private ProgressDialog progressDialog;
private boolean isLoginInProgress = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit_timer);
button = (Button) findViewById(R.id.btn_start);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (edit.getText().toString().length() == 0) throw new Exception();
long dTime = Long.parseLong(edit.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MainActivity.this.isLoginInProgress = false;
progressDialog.dismiss();
}
}, dTime);
progressDialog.show();
isLoginInProgress = true;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "bad time value", Toast.LENGTH_SHORT).show();
}
}
});
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("loading");
if (savedInstanceState != null) { // activity is restarted
isLoginInProgress = savedInstanceState.getBoolean("fl_login");
edit.setText(savedInstanceState.getString("edit"));
}
if (isLoginInProgress) { // Show dialog again
progressDialog.show();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("fl_login", isLoginInProgress);
outState.putString("edit", edit.getText().toString());
}
#Override
public void onDestroy(){
super.onDestroy();
progressDialog.dismiss();
}
}
You Can Use Database(SQLITE) for Storing Your Values..

proper handling AlertDialog when configration change

I saw many solution to maintain AlertDialog and most of them doesn't work probably when screen dim down. but this which i made works fine is there any other light weight way to do that , I want to use it inside Fragment from ACL .
public class Test extends Activity {
AlertDialog dialog;
boolean dialog_should_be_shown = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btn = new Button(this);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
createDialog();
}
});
setContentView(btn);
if (savedInstanceState != null) {
dialog_should_be_shown = savedInstanceState.getBoolean("flag",
false);
}
}
private void createDialog() {
dialog = new AlertDialog.Builder(Test.this).setMessage("HEllo")
.setCancelable(true).create();
dialog.show();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("flag", dialog_should_be_shown);
}
#Override
protected void onResume() {
super.onResume();
if (dialog_should_be_shown) {
createDialog();
}
}
#Override
protected void onPause() {
super.onPause();
if (dialog != null && dialog.isShowing()) {
dialog_should_be_shown = true;
dialog.dismiss();
} else {
dialog_should_be_shown = false;
}
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_test, menu);
return true;
}
}
UPDATE :
I dont want to retain Framgnet in memory.
use DialogFragment instead, it is included on the support library and you can retain it using setRetainInstance(true),
http://developer.android.com/reference/android/app/DialogFragment.html

Categories

Resources