Settings the developer's flag "Stay awake" might result in constant battery drain of your debugging device. So, how can you easily keep the device screen on ONLY while debugging?
try this
try
{
if( BuildConfig.DEBUG && Debug.isDebuggerConnected() )
{
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
else
{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
catch(Exception e)
{
e.printStackTrace();
}
this is for vertical
//vetical position
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Make to run your application only in portrait mode
this is for screen always screen on
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Related
I have a application which uses camera functionality in it but part of its functionality can also run without camera feature. SO I have put this in my manifest.
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false"/>
and in my code I check whether the device has camera or not using this
final boolean deviceHasCameraFlag = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
Now I am testing my code on a tablet which runs Android 4.0(ICS) and has no camera. But still I get True value for the deviceHasCameraFlag. Is this weird or am I missing something.
I tried different things and even tried the same thing on Bluetooth feature as Tablet even doesn't have Bluetooth feature. It works fine for Bluetooth but gives me true for camera.
Which device is it? The answer you get is a bug, and 4.0 is very old nowadays. Many tablets that still run this version were not crafted correctly, both hardware and software featuring multiple problems.
Regardless, you should always be prepared to handle failure on Camera.open() or Camera.open(0): for example, in some cases other software on your device will not release the camera gracefully.
So, in your case you have a false positive, you try to open the camera, it fails, and you continue as if there is no camera on the device, even if PackageManager thinks that PackageManager.FEATURE_CAMERA is availabe.
Though I have accepted Alex's answer I still want to put this one collectively as what can be the best solution in such condition.
What I found was in case of some low standard android devices
pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)
returns true even if camera doesn't exist and that seems to be a device bug for me which in unchecked.
So whenever there is scenario that you need to check if camera exists for a device or not best practice is something that I am putting below (best practice as per my knowledge if there is something more interesting and best solution that this you are welcome to put it here on this post)
int numberOfCameras = Camera.getNumberOfCameras();
context = this;
PackageManager pm = context.getPackageManager();
final boolean deviceHasCameraFlag = pm.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if( !deviceHasCameraFlag || numberOfCameras==0 )
{
Log.e(TAG, "Device has no camera" + numberOfCameras);
Toast.makeText(getApplicationContext(), "Device has no camera", Toast.LENGTH_SHORT).show();
captureButton.setEnabled(false);
}
else
{
Log.e(TAG, "Device has camera" + deviceHasCameraFlag + numberOfCameras);
}
In this I am checking both number of cameras as well as device has camera feature Boolean , so in any case it would not fail my condition.
In my case I had this code:
public boolean hasCameraSupport() {
boolean hasSupport = false;
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) { //<- this constant caused problems
hasSupport = true;
}
return hasSupport;
}
and it kept returning false on a Genymotion device running Android 4.1.1 (API 16). Once I changed the constant PackageManager.FEATURE_CAMERA_ANY to PackageManager.FEATURE_CAMERA, my problems went away. I am guessing that not all devices/API levels support PackageManager.FEATURE_CAMERA_ANY.
I got it you will try this one definitely it will work....
import android.hardware.Camera;
int numCameras = Camera.getNumberOfCameras();
if (numCameras > 0) {
System.out.println("camera");
} else {
System.out.println("No Camera");
}
For CameraX, if the FEATURE_CAMERA_ANY method is still returning true when there is no Camera on device, you can add the below method. So whether FEATURE_CAMERA_ANY returns true or false when CameraX is getting initialized, Below method will make sure to do what you want if a camera is actually not available on device.
private CameraSelector cameraSelector;
private ProcessCameraProvider cameraAvailableCheck;
private ListenableFuture<ProcessCameraProvider> cameraAvailableCheckFuture;
private void checkIfAnyCameraExist()
{
cameraAvailableCheckFuture = ProcessCameraProvider.getInstance(context);
cameraAvailableCheckFuture.addListener(new Runnable() {
#Override
public void run() {
try {
cameraAvailableCheck = cameraAvailableCheckFuture.get();
if ((cameraAvailableCheck.hasCamera(cameraSelector.DEFAULT_BACK_CAMERA) || cameraAvailableCheck.hasCamera(cameraSelector.DEFAULT_FRONT_CAMERA) ))
{
//Do what you want if at least back OR front camera exist
}
else
{
//Do what you want if any camera does not exist
}
}
catch (ExecutionException | InterruptedException | CameraInfoUnavailableException e)
{
// No errors need to be handled for this Future.
// This should never be reached.
}
}
}, ContextCompat.getMainExecutor(this));
}
Please try this code:
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
Still it does't work then please let me know
I am wondering when exactly the NFC Service is started and stopped.
The source code for android 4.0.3 seems to state that the polling is dependent on a single constant (located in NfcService.java)
/** minimum screen state that enables NFC polling (discovery) */
static final int POLLING_MODE = SCREEN_STATE_ON_UNLOCKED;
I would interpret this as "the screen light is on, therefore the nfc service is active".
BUT when the screen is locked, a NFC Tag wont be recognized, altough the screen is lit.
So I am curious: Is the NFC Service already deactivated when the lock screen appears, or is it still running but not processing the Tags?
Actually, I do not think that NFC Service is deactivated. When the screen has lower value then SCREEN_STATE_ON_UNLOCKED a device stops to ask NFC tags around. You can see this from this code:
// configure NFC-C polling
if (mScreenState >= POLLING_MODE) {
if (force || !mNfcPollingEnabled) {
Log.d(TAG, "NFC-C ON");
mNfcPollingEnabled = true;
mDeviceHost.enableDiscovery();
}
} else {
if (force || mNfcPollingEnabled) {
Log.d(TAG, "NFC-C OFF");
mNfcPollingEnabled = false;
mDeviceHost.disableDiscovery();
}
}
But NFC-EE routing is enabled util screen state is higher then SCREEN_STATE_ON_LOCKED:
// configure NFC-EE routing
if (mScreenState >= SCREEN_STATE_ON_LOCKED &&
mEeRoutingState == ROUTE_ON_WHEN_SCREEN_ON) {
if (force || !mNfceeRouteEnabled) {
Log.d(TAG, "NFC-EE ON");
mNfceeRouteEnabled = true;
mDeviceHost.doSelectSecureElement();
}
} else {
if (force || mNfceeRouteEnabled) {
Log.d(TAG, "NFC-EE OFF");
mNfceeRouteEnabled = false;
mDeviceHost.doDeselectSecureElement();
}
}
The service itself is started and stopped in other parts of this class.
See related http://forum.xda-developers.com/showthread.php?t=1712024&page=14
I'm simply trying to toggle auto brightness on and off.
I started with this code (inside the onCreate method)
final ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.brightToggle);
// display auto brightness state
final ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.autoToggle);
autoOnOrOff.setText(String.valueOf(getAutoBrightnessMode()));
autoBrightToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (autoBrightToggle.isChecked()) {
setAutoBright(true);
} else {
setAutoBright(false);
}
}
}); // end anonymous OnClickListener function
// toggle the brightness mode
private void setAutoBright(boolean mode) {
if (mode) {
Settings.System.putInt(cr, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
autoOnOrOff.setText(String.valueOf(getAutoBrightnessMode()));
} else {
Settings.System.putInt(cr, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
autoOnOrOff.setText(String.valueOf(getAutoBrightnessMode()));
}
}
Which doesn't seem to work. The setAutoBrightnessMode() method is also called again in onResume() but with the same non-results.
Anyway, I'm sorry if someone feels this question is redundant but the other posts did not get me where I need to go!
(FWIW - I'm testing this on my old Droid X and my Galaxy Nexus, not the Emulator)
EDITED - UPDATE ON THIS:
I'm 99% sure now that I am not seeing any changes to the Auto-Brightness mode reflected in the Settings panel and desktop widgets - even though I may actually be changing it's value.
part of the problem is that I don't know how exactly to determine if Auto-Brightness is on or not!
For instance, does the screen quickly and visibly change? I've been expecting immediate visible changes in brightness according to environment - but perhaps the changes are subtle? and over a longer period? or perhaps it takes 30 seconds or more of environment change before brightness changes?
Can someone suggest how I can track this? I've tried querying the Settings.System.SCREEN_BRIGHTNESS_MODE constant - hooking this method up to a textfield:
private int getAutoBrightnessMode() {
try {
int brightnessMode = Settings.System.getInt(cr, SCREEN_BRIGHTNESS_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
int brightnessMode = -10000;
}
return brightnessMode;
}
But it always reads 0, even after an onResume(). :-((
I know this is a simple procedure, but I'm trying to learn this stuff on my own, and have had almost no formal CS training... So all I can say is I'm very frustrated by this and feel like I've worked myself into a corner and at this point I'm so annoyed I can't think straight anymore.
So help would be great.
I use following approach in my application. Tested on HTC Desire HD and pair of noname chinese tablets.
Add to manifest permission:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
And use below code to toggle auto brightness. There is one trick in the code: we need to "refresh" brightness of app manually, because it doesn't changes automatically. May be it is the problem in your case.
void setAutoBrightness(boolean value) {
if (value) {
Settings.System.putInt(getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
} else {
Settings.System.putInt(getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
}
// After brightness change we need to "refresh" current app brightness
if (isChecked) {
refreshBrightness(-1);
} else {
refreshBrightness(getBrightnessLevel());
}
}
private void refreshBrightness(float brightness) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
if (brightness < 0) {
lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
} else {
lp.screenBrightness = brightness;
}
getWindow().setAttributes(lp);
}
int getBrightnessLevel() {
try {
int value = Settings.System.getInt(getContentResolver(), SCREEN_BRIGHTNESS);
// convert brightness level to range 0..1
value = value / 255;
return value;
} catch (SettingNotFoundException e) {
return 0;
}
}
i created the toglle button for automatic brightness setting changed.here i want to know about the automatic brightness is ON or OFF state if it is on state the togglebutton will be off ,if it is on toggle button will be off ,how to do here
please help me
int brightnessmode;
getBrightMode();
if(brightnessmode==1){
//below code will off the auto mode
android.provider.Settings.System.putInt(contentresolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
//Here perform any action you want
}
if(brightnessmode==0){
//below code will on the auto mode
android.provider.Settings.System.putInt(contentresolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
//Here perform any action you want
}
//This method will give brightness mode
//if brigthnessmode=0 means Auto mode is currently off
//if brightnessmode=1 means Auto mode is currently on
protected void getBrightMode() {
// TODO Auto-generated method stub
try {
brightnessmode = System.getInt(contentresolver, System.SCREEN_BRIGHTNESS_MODE);
} catch (Exception e) {
Log.d("tag", e.toString());
}
}
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
using SCREEN_BRIGHTNESS_MODE mode
http://developer.android.com/reference/android/provider/Settings.System.html
You should be able to read this from the Settings.System, look for SCREEN_BRIGHTNESS_MODE
I am trying to write an app that requires the LED flash to go into torch mode. The problem is, Android 2.1 does not support this mode and therefore I cannot support the platform yet. Wouldn't be an issue, but I am writing it for my fiance and her Epic 4G only has 2.1 right now. I found some code samples that use some undocumented API calls and therefore work on the Motorola Droid and such, but they do not work on the Epic. Does anyone have some suggestions on where to look to find code that should help me get this working?
I'm finding that torch mode is generally working fine on 2.1 but I had the same problem with the Samsung Epic and found a hack around it.
Looking at the params returned by Camera.getParameters() when run on the Samsung Epic, I noticed that the flash-modes it claims to support are: flash-mode-values=off,on,auto;
torch-mode is not listed, implying it's not supported.
However, I found that this model would still accept that mode and WOULD turn the LED on! The bad news was that when later setting the flash-mode back to auto or off left the LED still lit! It will not turn off until you call Camera.release().
I guess that's why Samsung dont include it in the list of supported!?!
So...the method I use to toggle torch in a CameraHelper class is...
/***
* Attempts to set camera flash torch/flashlight mode on/off
* #param isOn true = on, false = off
* #return boolean whether or not we were able to set it
*/
public boolean setFlashlight(boolean isOn)
{
if (mCamera == null)
{
return false;
}
Camera.Parameters params = mCamera.getParameters();
String value;
if (isOn) // we are being ask to turn it on
{
value = Camera.Parameters.FLASH_MODE_TORCH;
}
else // we are being asked to turn it off
{
value = Camera.Parameters.FLASH_MODE_AUTO;
}
try{
params.setFlashMode(value);
mCamera.setParameters(params);
String nowMode = mCamera.getParameters().getFlashMode();
if (isOn && nowMode.equals(Camera.Parameters.FLASH_MODE_TORCH))
{
return true;
}
if (! isOn && nowMode.equals(Camera.Parameters.FLASH_MODE_AUTO))
{
return true;
}
return false;
}
catch (Exception ex)
{
MyLog.e(mLOG_TAG, this.getClass().getSimpleName() + " error setting flash mode to: "+ value + " " + ex.toString());
}
}
The activities that use this call it as follows...
private void toggleFlashLight()
{
mIsFlashlightOn = ! mIsFlashlightOn;
/**
* hack to fix an issue where the Samsung Galaxy will turn torch on,
* even though it says it doesnt support torch mode,
* but then will NOT turn it off via this param.
*/
if (! mIsFlashlightOn && Build.MANUFACTURER.equalsIgnoreCase("Samsung"))
{
this.releaseCameraResources();
this.initCamera();
}
else
{
boolean result = mCamHelper.setFlashlight(mIsFlashlightOn);
if (! result)
{
alertFlashlightNotSupported();
}
}
}
The magic that makes this work in releaseCameraResources() is that it calls Camera.release()....and then I have to reinitialize all my camera stuff for Samsung devices.
Not pretty but seems to be working for plenty of users.
Note that I do have a report of torch mode not working at all with this code on Nexus one but have been able to dig into it. It definitely works on HTC EVO and Samsung Epic.
Hope this helps.
In my case for Samsung devices I needed to set focus mode to infinity and it started to work
params.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
mCamera.setParameters(params);
mCamera.startPreview();