Flashlight won't turn on - java

Hi I followed I followed a tutorial here and wrote out the code, I tested it but the flashlight does not turn on and I cant figure out what's gone wrong.
I left out the parts where there was sound because I preferred there not to be any.
package net.netne.benpaterson35;
import android.app.*;
import android.os.*;
import android.hardware.*;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity
{
Button mainButton1;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainButton1 = (Button) findViewById(R.id.mainButton1);
hasFlash = getApplicationContext().getPackageManager().
hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Sorry");
alert.setMessage("This device doesn't have flash a flash light");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which){
finish();
}
});
alert.show();
return;
}
getCamera();
mainButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
if (isFlashOn){
turnOffFlash();}
else {
turnOnFlash();
}
};
});
}
private void getCamera(){
if (camera == null){
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Failed to open camera", e.getMessage());
}
}
}
private void turnOnFlash() {
if (!isFlashOn){
if (camera == null || params == null){
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
private void turnOffFlash() {
if (isFlashOn){
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
}
#Override
protected void onPause()
{
super.onPause();
turnOffFlash();
}
#Override
protected void onRestart()
{
super.onRestart();
}
#Override
protected void onResume()
{
super.onResume();
if(hasFlash)
turnOnFlash();
}
#Override
protected void onStart()
{
super.onStart();
getCamera();
}
#Override
protected void onStop()
{
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
}
Thanks for reading :)

if you are working on new device the code you followed wont work on newer devices i made it work on Lollipop device by following this code give it a try
mCam = Camera.open();
Camera.Parameters p = mCam.getParameters();
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCam.setParameters(p);
mPreviewTexture = new SurfaceTexture(0);
try {
mCam.setPreviewTexture(mPreviewTexture);
} catch (IOException ex) {
// Ignore
}
mCam.startPreview();

Did you add
<uses-permission android:name="android.permission.CAMERA" />
to your AndroidManifest?
Highly suspect you didn't add the permission.

Related

How to make BLE scan and MQTT publish work in background Android Studio Java

I want make some project where Android can scan nearby Beacon/BLE and send it using MQTT. But I want the service to work in the background if the service work in the foreground it will interrupt the scanning process when screen is off.
This is my code for scanning:
package com.example.mqtt_active;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import java.nio.charset.StandardCharsets;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private Button turnon, changeLayout;
MqttAndroidClient client;
private boolean state=false;
private BluetoothAdapter bluetoothAdapter;
public static final int REQUEST_ACCESS_COARSE_LOCATION = 1;
public static final int REQUEST_ENABLE_BLUETOOTH = 11;
public static String mqtt_server,mqtt_port,mqtt_id;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
Log.d("Logger", "On Create Android");
turnon = findViewById(R.id.turnon);
changeLayout = findViewById(R.id.mqttSet);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
textView = findViewById(R.id.textView4);
textView.setText("id "+mqtt_id+" port "+mqtt_port+" server "+mqtt_server);
client = new MqttAndroidClient(this.getApplicationContext(), "tcp://"+mqtt_server+":"+mqtt_port,mqtt_id);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stateCheck();
Log.d("Logger", "State Check");
handler.postDelayed(this, 1000);
}
}, 1000);
// final Handler handlerStop = new Handler();
// handlerStop.postDelayed(new Runnable() {
// #Override
// public void run() {
// bluetoothAdapter.cancelDiscovery();
// Log.d("Logger", "Cancel Dsicovery");
// handlerStop.postDelayed(this, 2000);
// }
// }, 2000);
turnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!state){
turnon.setText("Turn Off");
Log.d("Logger", "Turn On State");
// if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
// if(checkCoarsePermission()){
// bluetoothAdapter.startDiscovery();
// }
// }
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Try ");
IMqttToken token = client.connect();
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.d("Logger", "Connect MQTT");
Toast.makeText(MainActivity.this,"connected!!",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.d("Logger", "Connect Failed");
Toast.makeText(MainActivity.this,"connection failed!!",Toast.LENGTH_LONG).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
Log.d("Logger", "error"+e);
}}
state = true;
}else{
turnon.setText("Turn On");
state = false;
// bluetoothAdapter.cancelDiscovery();
}
}
});
changeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,MqttActivity.class));
}
});
}
public void stateCheck(){
if (state){
if (bluetoothAdapter!=null & bluetoothAdapter.isEnabled()) {
if(checkCoarsePermission()){
Log.d("Logger", "Discover");
bluetoothAdapter.startDiscovery();
}
}
}
// else {
// Log.d("Logger", "Cancel");
// bluetoothAdapter.cancelDiscovery();
// }
}
private boolean checkCoarsePermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
return false;
}else {
return true;
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(devicesFoundReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(devicesFoundReceiver);
}
private final BroadcastReceiver devicesFoundReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action= intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
String RSSI = String.valueOf(rssi);
Toast.makeText(context.getApplicationContext(),"rssi "+RSSI+" "+device.getAddress(),Toast.LENGTH_SHORT).show();
Log.d("Logger", "Recive data "+device.getAddress());
if(mqtt_server!=null||mqtt_id!=null||mqtt_port!=null){
try {
Log.d("Logger", "Sending data");
String payload = "rssi:"+RSSI+"mac:"+device.getAddress();
client.publish("test",payload.getBytes(),0,false);
} catch ( MqttException e) {
e.printStackTrace();
Log.d("Logger", "Error Sending "+e);
}}
}else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_ACCESS_COARSE_LOCATION:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this,"ALLOWED", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"Forbidden",Toast.LENGTH_SHORT).show();
} break;
}
}
}
App Flow:
Insert MQTT server, port, id, topic.
Turn on the proccess.
Android scan BLE/Beacon
Android sending MAC/RSSI to MQTT
I hope someone can help to guide me, on how to make the application run in the background?
I'm a beginner, and I don't understand how to implement background service in my application. Please help me!
You need to implement a foreground service that will handle your ble scanning and MQTT logic.
See this article with an overview of how to do it. Depending on your build/target SDK, the implementation will vary.

Green N White Screen issue in Camera activity Android

This bug is only on some devices.
Project scope:
Indoor navigation system used in malls/ships to locate shops.
It uses beacons to locate shops with bluetooth connection. It uses camera to show directions (arrow) image overlays.
In ArCameraActivity, half green screen shows up in camera preview.
code:
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.opengl.Matrix;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dagger.android.support.DaggerAppCompatActivity;
public class ARActivity extends DaggerAppCompatActivity implements SensorEventListener, LocationListener,
ActivityCompat.OnRequestPermissionsResultCallback, ARView {
private static boolean IS_NAVIGATION_CLICKED = false;
#Inject
ARPresenter presenter;
#BindView(R.id.img_clear)
ImageView imgClear;
#BindView(R.id.img_logout)
ImageView imgLogout;
#BindView(R.id.img_map)
ImageView imgMap;
#BindView(R.id.img_navigation)
ImageView imgNavigation;
final static String TAG = "ARActivity";
private SurfaceView surfaceView;
private FrameLayout cameraContainerLayout;
private AROverlayView arOverlayView;
private Camera camera;
private ARCamera arCamera;
private TextView tvCurrentLocation;
private SensorManager sensorManager;
private final static int REQUEST_CAMERA_PERMISSIONS_CODE = 11;
public static final int REQUEST_LOCATION_PERMISSIONS_CODE = 0;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute
private LocationManager locationManager;
public Location location;
boolean isGPSEnabled;
boolean isNetworkEnabled;
boolean locationServiceAvailable;
private ScanRegionsService scanRegionsService;
private boolean isBeaconLoaded = false;
// private static GetMallResponse.Data.Mall identifiedMall;
private Dialog dialog = null;
private static final String IMAGE_URL = "http://98.156.231.92/maps/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ar);
ButterKnife.bind(this);
sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
cameraContainerLayout = (FrameLayout) findViewById(R.id.camera_container_layout);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
tvCurrentLocation = (TextView) findViewById(R.id.tv_current_location);
arOverlayView = new AROverlayView(this);
scanRegionsService = new ScanRegionsService(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
beginService();
}
}
if (Util.getSelectedShop() != null) {
showLoading();
}
}
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
if (!isBeaconLoaded) {
Log.d(TAG, "run: "+ isBeaconLoaded);
dismissLoading();
if(!isFinishing()) {
new AlertDialog.Builder(ARActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("There is no beacon in your surroundings")
.setMessage("Are you sure you want to stop navigation?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.setSelectedShop(null);
finish();
}
})
.show();
}
}
}
};
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i = 0; i < permissions.length; i++) {
if (permissions[i].equalsIgnoreCase(Manifest.permission.ACCESS_FINE_LOCATION) &&
grantResults[i] == PackageManager.PERMISSION_GRANTED) {
beginService();
} else if (permissions[i].equalsIgnoreCase(Manifest.permission.CAMERA) &&
grantResults[i] == PackageManager.PERMISSION_DENIED) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
}
private void beginService() {
isBeaconLoaded = false;
arOverlayView.registerReceiver();
scanRegionsService.setupSpaces();
scanRegionsService.startScanning();
onMallIdentified(Util.getSelectedMall());
new Handler().postDelayed(mRunnable, 10000);
}
#OnClick(R.id.img_map)
public void onMapClicked() {
arOverlayView.unregisterReceiver();
// Util.getRouteMap().clear();
Util.setSelectedShop(null);
// Intent intent = new Intent(this, MainActivity.class);
// startActivity(intent);
finish();
}
#OnClick(R.id.img_navigation)
public void onNavClicked() {
if (!IS_NAVIGATION_CLICKED) {
IS_NAVIGATION_CLICKED = true;
arOverlayView.showNavigationMap();
imgNavigation.setImageDrawable(getResources().getDrawable(R.drawable.navigation_on));
} else {
IS_NAVIGATION_CLICKED = false;
arOverlayView.hideNavigationMap();
imgNavigation.setImageDrawable(getResources().getDrawable(R.drawable.navigation_off));
}
}
#OnClick(R.id.img_logout)
public void onLogoutClicked() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to logout?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.set("authToken", "");
Intent intent = new Intent(ARActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onBackPressed() {
if(!((Activity) this).isFinishing()) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to exit the screen?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
#Override
public void onResume() {
super.onResume();
requestLocationPermission();
requestCameraPermission();
registerSensors();
initAROverlayView();
IntentFilter intentFilter = new IntentFilter(ForegroundScanService.ACTION_DEVICE_DISCOVERED);
registerReceiver(scanningBroadcastReceiver, intentFilter);
}
public void showClearMap() {
imgClear.setVisibility(View.VISIBLE);
}
public void hideClearMap() {
imgClear.setVisibility(View.GONE);
}
#OnClick(R.id.img_clear)
public void onClearClicked() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm")
.setMessage("Are you sure you want to stop navigation?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Util.setSelectedShop(null);
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onPause() {
unregisterReceiver(scanningBroadcastReceiver);
releaseCamera();
super.onPause();
}
public void requestCameraPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSIONS_CODE);
} else {
initARCameraView();
}
}
public void requestLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSIONS_CODE);
} else {
initLocationService();
}
}
public void initAROverlayView() {
if (arOverlayView.getParent() != null) {
((ViewGroup) arOverlayView.getParent()).removeView(arOverlayView);
}
cameraContainerLayout.addView(arOverlayView);
}
public void initARCameraView() {
reloadSurfaceView();
if (arCamera == null) {
arCamera = new ARCamera(this, surfaceView);
}
if (arCamera.getParent() != null) {
((ViewGroup) arCamera.getParent()).removeView(arCamera);
}
cameraContainerLayout.addView(arCamera);
arCamera.setKeepScreenOn(true);
initCamera();
}
private void initCamera() {
int numCams = Camera.getNumberOfCameras();
if (numCams > 0) {
try {
camera = Camera.open();
camera.startPreview();
arCamera.setCamera(camera);
} catch (RuntimeException ex) {
Toast.makeText(this, "Camera not found", Toast.LENGTH_LONG).show();
}
}
}
private void reloadSurfaceView() {
if (surfaceView.getParent() != null) {
((ViewGroup) surfaceView.getParent()).removeView(surfaceView);
}
cameraContainerLayout.addView(surfaceView);
}
private void releaseCamera() {
if (camera != null) {
camera.setPreviewCallback(null);
camera.stopPreview();
arCamera.setCamera(null);
camera.release();
camera = null;
}
}
private void registerSensors() {
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR),
SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
float[] rotationMatrixFromVector = new float[16];
float[] projectionMatrix = new float[16];
float[] rotatedProjectionMatrix = new float[16];
SensorManager.getRotationMatrixFromVector(rotationMatrixFromVector, sensorEvent.values);
if (arCamera != null) {
projectionMatrix = arCamera.getProjectionMatrix();
}
Matrix.multiplyMM(rotatedProjectionMatrix, 0, projectionMatrix, 0, rotationMatrixFromVector, 0);
this.arOverlayView.updateRotatedProjectionMatrix(rotatedProjectionMatrix);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
//do nothing
}
private void initLocationService() {
if (Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
this.locationManager = (LocationManager) this.getSystemService(this.LOCATION_SERVICE);
// Get GPS and network status
this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isNetworkEnabled && !isGPSEnabled) {
// cannot get location
this.locationServiceAvailable = false;
}
this.locationServiceAvailable = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateLatestLocation();
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateLatestLocation();
}
}
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
}
}
private void updateLatestLocation() {
if (arOverlayView != null && location != null) {
arOverlayView.updateCurrentLocation(location);
tvCurrentLocation.setText(String.format("lat: %s \nlon: %s \naltitude: %s \n",
location.getLatitude(), location.getLongitude(), location.getAltitude()));
}
}
#Override
public void onLocationChanged(Location location) {
updateLatestLocation();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private final BroadcastReceiver scanningBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: ");
isBeaconLoaded = true;
String shopname=Util.getSelectedShop().getShopImage();
Toast.makeText(context, "You are in "+shopname, Toast.LENGTH_LONG).show();
int devicesCount = intent.getIntExtra(BackgroundScanService.EXTRA_DEVICES_COUNT, 0);
RemoteBluetoothDevice device = intent.getParcelableExtra(BackgroundScanService.EXTRA_DEVICE);
Log.i("BEACON", String.format("Total discovered devices: %d\n\nLast scanned device:\n%s", devicesCount, device.toString()));
// statusText.setText(String.format("Total discovered devices: %d\n\nLast scanned device:\n%s", devicesCount, device.toString()));
}
};
#Override
public void onMallIdentified(GetMallResponse.Data.Mall mall) {
// identifiedMall = mall;
// Toast.makeText(this, "Identified "+mall.getPropertyName(), Toast.LENGTH_LONG).show();
presenter.loadShops(mall.getId());
presenter.loadRouteBeacons(mall.getId());
}
public void onUnkownPlaceIdentified() {
arOverlayView.registerReceiver();
Toast.makeText(this, "Unknown place identified", Toast.LENGTH_LONG).show();
List<GetRouteBeaconsResponse.Data.Route> floorRoute = new ArrayList<>();
}
#Override
public void onShopLoaded(List<GetShopsResponse.Data.Shop> shops) {
Log.i(TAG, "onShopLoaded");
if (shops.size() > 0) {
Util.shopMap.clear();
Log.i(TAG, "onShopLoaded shops.size " + shops.size());
Util.activeDeviceMap.clear();
for (GetShopsResponse.Data.Shop shop : shops) {
Util.shopMap.put("" + shop.getId(), shop);
if (shop.getAdImage().length() > 0) {
Drawable drbl = Util.promoImageMap.get(IMAGE_URL + shop.getAdImage());
if (drbl == null) {
String imgkey = IMAGE_URL + shop.getAdImage();
drbl = getResources().getDrawable(R.drawable.promo1, null);
Util.promoImageMap.put(imgkey, drbl);
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Drawable drb2 = drawableFromUrl(imgkey);
Util.promoImageMap.put(IMAGE_URL + shop.getAdImage(), drb2);
} catch (Exception e) {
Log.i(TAG, "Unable to download image");
}
}
};
new Thread(runnable).start();
}
}
}
}
}
#Override
public void onRouteBeaconLoaded(List<GetRouteBeaconsResponse.Data.Route> floors) {
Log.d(TAG, "onRouteBeaconLoaded: ");
Log.i(TAG, "onRouteBeaconLoaded");
// if (floors.size()>0 && Util.getSelectedShop()!=null){
// Log.i(TAG, "onRouteBeaconLoaded floors.size "+floors.size());
// Util.getRouteMap().clear();
// for (GetRouteBeaconsResponse.Data.Route route: floors){
// String comkey = route.proximityUUID+route.major+route.minor;
// Util.getRouteMap().put(comkey, route);
// }
// Util.setSelectedShop(Util.getSelectedShop());
// Log.i(TAG, "onShopLoaded setup space scanRegionsService");
// scanRegionsService.setupSpaces();
// Log.i(TAG, "onShopLoaded startScanning");
// scanRegionsService.startScanning();
// }
if (floors.size() > 0) {
Log.i(TAG, "onRouteBeaconLoaded floors.size " + floors.size());
Util.getRouteMap().clear();
for (GetRouteBeaconsResponse.Data.Route route : floors) {
String comkey = route.proximityUUID + route.major + route.minor;
Util.getRouteMap().put(comkey, route);
}
Log.i(TAG, "onShopLoaded setup space scanRegionsService");
scanRegionsService.setupSpaces();
Log.i(TAG, "onShopLoaded startScanning");
scanRegionsService.startScanning();
}
arOverlayView.registerReceiver();
}
public static Drawable drawableFromUrl(String url) throws IOException {
Bitmap x;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
x = BitmapFactory.decodeStream(input);
return new BitmapDrawable(x);
}
private void initLoadingDialog() {
dialog = new Dialog(this);
dialog.setCancelable(false);
dialog.setContentView(R.layout.show_loading);
TextView txtFind = dialog.findViewById(R.id.findingBeacons);
txtFind.setVisibility(View.VISIBLE);
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss();
}
return true;
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
public void showLoading() {
try {
if (dialog != null) {
dialog.show();
} else {
initLoadingDialog();
dialog.show();
}
} catch (Exception e) {
}
}
public void dismissLoading() {
try {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
} catch (Exception e) {
}
}
}
green screen
Getting like this for camera activity in redmi y2 phone only. Its works well on other models. What might be issue? It shows directions in camera to shop using beacon device. Android os version is not problem.
white screen on some devices - samsung tab, oneplus 7, BLU G9 Pro phone
white screen
this activity shows navigation with help of beacons in camera shows overlay of imageview. it works on some devices, i have tried various methods to resolve it,
doesn't work. added latest camera v2 api.
How can i resolve this issue? thanks in advance.
Sometimes this "green screen" issue is caused by the camera's preview resolution. Try to get supported preview size from camera instance.
mParams = mCamera.getParameters();
List<Camera.Size> supportedPreviewSizes = mParams.getSupportedPreviewSizes();
Camera.Size bestPreviewSize = supportedPreviewSizes.get(0);
for (Camera.Size sz : supportedPreviewSizes) {
/* perfect match */
if(sz.width == mWidth && sz.height == mHeight) {
bestPreviewSize = sz;
break;
} else {
int bestArea = bestPreviewSize.width*bestPreviewSize.height;
int currArea = sz.width*sz.height;
int targetArea = mWidth*mHeight;
if (Math.abs(currArea-targetArea) < Math.abs(bestArea-targetArea)) {
bestPreviewSize = sz;
}
}
}
mCurrWidth = bestPreviewSize.width;
mCurrHeight = bestPreviewSize.height;
mParams.setPreviewSize(mCurrWidth, mCurrHeight);
/* Set preview format */
mParams.setPreviewFormat(ImageFormat.NV21);
/* Apply Parameters */
mCamera.setParameters(mParams);
mCamera.startPreview();
You can also try to force some fixed resolution depending on some device conditions, like display width, for example. Some resolutions i found useful on my use case:
width = 1280;
heigth = 720;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics windowMetrics = getWindowManager().getCurrentWindowMetrics();
if (isPortrait) {
if (windowMetrics.getBounds().width() <= 720) {
width = 720;
heigth = 480;
}
} else {
if (windowMetrics.getBounds().width() <= 1344) {
width = 960;
heigth = 540;
}
}
} else {
if (isPortrait) {
if (getDisplay().getWidth() <= 720) {
width = 720;
heigth = 480;
}
} else {
if (getDisplay().getWidth() <= 1344) {
width = 960;
heigth = 540;
}
}
}
Keep in mind that the best solution for me was getting the supported sizes to calculate the best preview size.

Flashlight app not turning off in kitkat device. perfectly working on marshmallow

Here is my code of my flashlight app which is perfectly run on my nougat and marshmallow device. but when i test it to a kitkat device, flashlight turn on perfectly, but not turning off.
Whats wrong i did in this code can you help me to find it please..
I didnt find any solution in the web. please help.
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Button btnSwitch;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Camera.Parameters params;
MediaPlayer mp;
private static final String TAG = MainActivity.class.getSimpleName();
private Camera mCamera;
private Camera.Parameters parameters;
private CameraManager camManager;
private Context context;
ImageView imageFlashlight;
private static final int CAMERA_REQUEST = 50;
private boolean flashLightStatus = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageFlashlight = (ImageView) findViewById(R.id.imageFlashlight);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
// First check if device is supporting flashlight or not
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
final boolean hasCameraFlash = getPackageManager().
hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
boolean isEnabled = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED;
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
// get the camera
// displaying button image
imageFlashlight.setEnabled(isEnabled);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, CAMERA_REQUEST);
imageFlashlight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (hasCameraFlash) {
if (flashLightStatus) {
turnOffFlash();
} else
turnOnFlash();
} else {
Toast.makeText(MainActivity.this, "No flash available on your device",
Toast.LENGTH_SHORT).show();
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
private void turnOnFlash() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, true);
flashLightStatus = true;
imageFlashlight.setImageResource(R.drawable.poweron);
} catch (CameraAccessException e) {
}
} else {
imageFlashlight.setImageResource(R.drawable.poweron);
getCamera();
params = camera.getParameters();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
}
}
// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. ", e.getMessage());
}
}
}
#TargetApi(Build.VERSION_CODES.M)
private void turnOffFlash() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, false);
flashLightStatus = false;
imageFlashlight.setImageResource(R.drawable.poweroff);
} catch (CameraAccessException e) {
}
} else {
getCamera();
if (flashLightStatus) {
if (isFlashOn = true) {
return;
}
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
imageFlashlight.setEnabled(true);
} else {
Toast.makeText(MainActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
The issue is with flashLightStatus because you are not setting it inside else part of turnOnFlash method and later inside turnOffFlash,
if (flashLightStatus) {
will never be true hence control will never reach the point to turn off light so do
#TargetApi(Build.VERSION_CODES.M)
private void turnOnFlash() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId, true);
imageFlashlight.setImageResource(R.drawable.poweron);
} catch (CameraAccessException e) {
}
} else {
imageFlashlight.setImageResource(R.drawable.poweron);
getCamera();
params = camera.getParameters();
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
}
isFlashOn = true;
flashLightStatus = true;
}
and also use
if (!isFlashOn) {
return;
}
instead of
if (isFlashOn = true) {
return;
}
to return control when flash light is not on

Application Crashes when resuming the app

I am creating a simple Flashlight App, but every time I leave the app and reopen it, it crashes. Am I missing something in my code, because I am not sure what, below is an error when it crashes. Please let me know what I need to do in order to fix this resume issue:
package com.example.gkvxm.materiallight;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Toast;
import com.dd.CircularProgressButton;
import java.io.IOException;
public class FlashLightActivity extends Activity implements SurfaceHolder.Callback {
private boolean isLigtOn = false;
private Camera camera;
#Override
protected void onStart(){
super.onStart();
SurfaceView preview = (SurfaceView)findViewById(R.id.PREVIEW);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
protected void onStop(){
super.onStop();
if(camera!=null){
camera.release();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_light);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(FlashLightActivity.this, "Your Device is not supported", Toast.LENGTH_SHORT).show();
Log.e("err", "Device is not supported");
return;
}
camera = Camera.open();
final Camera.Parameters p = camera.getParameters();
final CircularProgressButton circularButton1 = (CircularProgressButton) findViewById(R.id.btnWithText);
circularButton1.setIndeterminateProgressMode(true);
circularButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isLigtOn) {
turnOffFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights Off!", Toast.LENGTH_SHORT).show();
} else {
turnOnFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights On!", Toast.LENGTH_SHORT).show();
}
if (circularButton1.getProgress() == 0) {
simulateSuccessProgress(circularButton1);
} else {
circularButton1.setProgress(0);
}
}
});
}
private void turnOnFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLigtOn = true;
}
private void turnOffFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLigtOn = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder,int format,int width,int height){
}
#Override
public void surfaceCreated(SurfaceHolder holder){
try{
Log.i("SurfaceHolder","Setting preview");
camera.setPreviewDisplay(holder);
} catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
Log.i("SurfaceHOlder", "stopping preview");
camera.stopPreview();
holder = null;
}
private void simulateSuccessProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 100);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
}
});
widthAnimation.start();
}
private void simulateErrorProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 99);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
if (value == 99) {
button.setProgress(-1);
}
}
});
widthAnimation.start();
}
}
Error :
05-22 03:08:35.646 13909-13909/com.example.gkvxm.materiallight E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.gkvxm.materiallight, PID: 13909
java.lang.RuntimeException: Camera is being used after Camera.release() was called
at android.hardware.Camera._stopPreview(Native Method)
at android.hardware.Camera.stopPreview(Camera.java:732)
at com.example.gkvxm.materiallight.FlashLightActivity.surfaceDestroyed(FlashLightActivity.java:129)
at android.view.SurfaceView.updateWindow(SurfaceView.java:564)
at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:238)
at android.view.View.dispatchWindowVisibilityChanged(View.java:8785)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1164)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1318)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Camera is being used after Camera.release() was called. So, looking at the activity lifecycle, you need to open the camera in onStart() or in onRestart(). So Maybe this code will work fine ...
package com.example.gkvxm.materiallight;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Toast;
import com.dd.CircularProgressButton;
import java.io.IOException;
public class FlashLightActivity extends Activity implements SurfaceHolder.Callback {
private boolean isLigtOn = false;
private Camera camera;
#Override
protected void onStart(){
super.onStart();
camera = Camera.open();
final Camera.Parameters p = camera.getParameters();
SurfaceView preview = (SurfaceView)findViewById(R.id.PREVIEW);
SurfaceHolder mHolder = preview.getHolder();
mHolder.addCallback(this);
}
#Override
protected void onStop(){
super.onStop();
if(camera!=null){
camera.release();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flash_light);
Context context = this;
PackageManager pm = context.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(FlashLightActivity.this, "Your Device is not supported", Toast.LENGTH_SHORT).show();
Log.e("err", "Device is not supported");
return;
}
camera = Camera.open();
final Camera.Parameters p = camera.getParameters();
final CircularProgressButton circularButton1 = (CircularProgressButton) findViewById(R.id.btnWithText);
circularButton1.setIndeterminateProgressMode(true);
circularButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isLigtOn) {
turnOffFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights Off!", Toast.LENGTH_SHORT).show();
} else {
turnOnFlash(p);
Toast.makeText(FlashLightActivity.this, "Lights On!", Toast.LENGTH_SHORT).show();
}
if (circularButton1.getProgress() == 0) {
simulateSuccessProgress(circularButton1);
} else {
circularButton1.setProgress(0);
}
}
});
}
private void turnOnFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLigtOn = true;
}
private void turnOffFlash(Camera.Parameters p){
p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
isLigtOn = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder,int format,int width,int height){
}
#Override
public void surfaceCreated(SurfaceHolder holder){
try{
Log.i("SurfaceHolder","Setting preview");
camera.setPreviewDisplay(holder);
} catch (IOException e){
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
Log.i("SurfaceHOlder", "stopping preview");
camera.stopPreview();
holder = null;
}
private void simulateSuccessProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 100);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
}
});
widthAnimation.start();
}
private void simulateErrorProgress(final CircularProgressButton button) {
ValueAnimator widthAnimation = ValueAnimator.ofInt(1, 99);
widthAnimation.setDuration(1500);
widthAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer value = (Integer) animation.getAnimatedValue();
button.setProgress(value);
if (value == 99) {
button.setProgress(-1);
}
}
});
widthAnimation.start();
}
}
As the Log says Camera is being used after Camera.release() was called. So, looking at the activity lifecycle you need to open camera in onStart() or in onRestart()
This exception is because of camera.release(); is called in the onStop() method of your activity. After releasing the camera instance you are reusing the released instance.
camera = Camera.open();
move the above line from OnCreate() to onStart()
You are releasing the camera instance in onPause() which is correct due to documentation:
public final void release ()
Added in API level 1 Disconnects and releases the Camera object
resources.
You must call this as soon as you're done with the Camera object.
But you also need to re-open it in onResume(), like you do in onCreate, since onCreate() not always is called when you resume the app.
As they state here:
Important: Call release() to release the camera for use by other
applications. Applications should release the camera immediately in
onPause() (and re-open() it in onResume()).
See this for more information about the android app lifecycle.
Good luck!
It may be you are camera.release(); on onStop(). And when surfaceDestroyed call you have used camera.stopPreview();
so camera is alredy release and you are going to stopePreview. thats way you are geting Camera is being used after Camera.release() was called this error.
so you have to cange that.
#Override
protected void onStop(){
super.onStop();
}
and on surfaceDestroyed
#Override
public void surfaceDestroyed(SurfaceHolder holder){
Log.i("SurfaceHOlder", "stopping preview");
camera.stopPreview();
camera.release();
holder = null;
}
I have same problem with camera class. Use this line onResume()
mCameraPreview.getHolder().removeCallback(mCameraPreview);
and its work now.
I had an app with the same issue,
when I removed "on click listener" inside my on create function, the problem was solved.
I think we should never insert any implementation function or other things inside our onCreate method...
It's better to use onCreate only for declaring and instantiating variables.

Keep app running in background on Android

I am really new to Android Programming. I am working on a simple app: FlashLight for Android.
I need the app to continue run in background if the user presses the menubutton or locks the screen. The light should not stop until the user presses the button the stop the light.
Below is my code:
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;
}
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;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
// changing button/switch image
toggleButtonImage();
}
}
/*
* 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);
}
}
/*
* 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();
}
#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;
}
}
}
You;re turning off the light in onPause. When the screen is locked or the app is minimized, onPause is called. If you don't want that to happen, don't call it there.
I think you are searching for Services: http://developer.android.com/guide/components/services.html
They are very similar to an Activity but do dot provide a user interface and can run in the background.

Categories