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;
}
}
Related
Unable to override Here SDK to disable sound effect on the onSpeedExceeded event.
Using the Here Developer tutorial, (https://developer.here.com/blog/android-premium-sdk-speed-limit-warning-example), I succeeded in running the sample app. But...
While driving, when I exceed the speed limit, there is a doot doot doot. I want to override this behaviour as I intend to use my own sounds.
I guessed that I might override the code by creating a NavigationManager.SpeedWarningListener. Unfortunately I can not disable or defeat the 'onSpeedExceeded' sound effects.
NavigationManager.SpeedWarningListener speedWarningListener = new NavigationManager.SpeedWarningListener() {
#Override
public void onSpeedExceeded(String s, float v) {
//super.onSpeedExceeded(s, v);
//Log.v(Global.TAG, "onSpeedExceeded");
Global.SpeedLimitExceeded = true;
}
#Override
public void onSpeedExceededEnd(String s, float v) {
//super.onSpeedExceededEnd(s, v);
//Log.v(Global.TAG, "onSpeedExceededEnd");
Global.SpeedLimitExceeded = false;
}
};
EDITED ANSWER: This method needs to be amended to stop the speed warning:
private void startNavigationManager() {
NavigationManager.Error navError = NavigationManager.getInstance().startTracking();
// added by suggestion from stackoverflow
NavigationManager.getInstance().stopSpeedWarning();
if (navError != NavigationManager.Error.NONE) {
Log.d(Global.TAG, "NavigationManager: false");
//handle error navError.toString());
} else {
//Log.d(Global.TAG, "NavigationManager: true");
}
}
Please set speedWarningEnabled accordingly for NMANavigationManager
navigationManager:didUpdateSpeedingStatus:forCurrentSpeed:speedLimit: will be sent to the delegate when speeding is detected or when a correction is made.
Also refer http://developer.here.com/documentation/ios-premium/api_reference_jazzy/Classes/NMANavigationManager.html
I want to get the real brightness value from the background. I have tried several ways:
1.
curBrightnessValue =android.provider.Settings.System.getInt(
getContext().getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS);
But if the screen brightness is on Auto mode the value remain constant.
Reading the sys/class/backlight/brightness/
This is a good way but I want a way without reading a file.
Use the following code to get the brightness of the background (This will also allow you to change the value of brightness if you wish to):
Settings.System.putInt(
cResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
brightness =
Settings.System.getInt(
cResolver,
Settings.System.SCREEN_BRIGHTNESS);
System.out.println("Current Brightness level " + brightness);
To my knowledge, it cannot be done any other way in Auto mode. See this answer.
Method 1 as described using Settings.System.getInt() in auto mode doesn't work for older Android versions like 'N'. But it works for 'P' and it's the same value as that in the file /sys/class/backlight/panel0-backlight/brightness.
Some sample code I tried in Processing
import android.provider.Settings; // for global system settings
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
Activity act;
Context context;
void setup() {
act = this.getActivity();
context = act.getApplicationContext();
}
void draw() {
text("brightness = " + getBrightness());
}
float getBrightness() {
float brightness;
if(!Settings.System.canWrite(context)) {
// Enable write permission
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
context.startActivity(intent);
} else {
// Get system brightness
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); // enable auto brightness
brightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, -1); // in the range [0, 255]
}
return brightness;
}
I'm trying to determine when a screen is rotated (in Android) using the XLabs method detailed here How to handle screen rotation/orientation in Xamarin Forms? and I'm having trouble with it.
I override the OnConfigurationChanged method in MainActivity
public override void OnConfigurationChanged (Android.Content.Res.Configuration newConfig)
{
base.OnConfigurationChanged (newConfig);
var xapp = Resolver.Resolve<IXFormsApp> ();
if (xapp == null)
return;
switch (newConfig.Orientation) {
case Android.Content.Res.Orientation.Landscape:
xapp.Orientation = XLabs.Enums.Orientation.Landscape;
break;
case Android.Content.Res.Orientation.Portrait:
//xapp.Orientation = XLabs.Enums.Orientation.Portrait;
break;
default:
break;
}
}
I'm having trouble with the Orientation variable in IXFormsApp i.e. xapp.Orientation. The XLabs documentation lists this as 'protected set', as does the compiler:
MainActivity.cs(109,5,109,21): error CS0200: Property or indexer 'XLabs.Platform.Mvvm.IXFormsApp.Orientation' cannot be assigned to -- it is read only
and it doesn't get set automagically (when I check where it is used, it is always set to 'None'), so I was wondering how to make use of it, and indeed, how to use the XLabs/IXFormsApp to determine rotation?
On a related note, I was also trying to set the Rotation handler (not sure why, but I thought I'd give it a go) with unusual results.
xapp.Rotation += (sender, args) =>
{
switch (args.Value)
{
case XLabs.Enums.Orientation.Landscape:
//xapp.Orientation = XLabs.Enums.Orientation.Landscape;
...
break;
case XLabs.Enums.Orientation.Portrait:
...
break;
default:
break;
}
};
If I try in the Android code I get the following error:
MainActivity.cs(60,4,60,22): error CS0019: Operator '+=' cannot be applied to operands of type 'System.EventHandler<XLabs.EventArgs<XLabs.Enums.Orientation>>' and 'lambda expression'
however, if I set it in the Forms code (where the results are used), it is fine (altho the handler never seems to actually be called). Does anyone know whay this would be the case?
There are two different solutions I have used in the past.
The first is by making a PageBase class which all my pages inherit from, and PageBase inherits from a regular Page.
My PageBase has two abstract methods (so the children of it have to fill it in), which are UpdateLandscape and UpdatePortait. Children will fill these methods in for how to layout the page depending on whether it is being laid out in landscape or portrait mode.
Pages have a method OnSizeAllocated, as Daniel said. I made PageBase override it and make it call UpdateLandscape and UpdatePortait accordingly.
If, as you said, you are only looking to check when it has rotated, the above works just fine, as OnSizeAllocated gets called for a page whenever you rotate your phone.
If you are checking for landscape vs portait because you want your code to be able to check at any time, then the second solution below works too.
The second way I solved it is to use dependency services to fill in an IDeviceInfo interface, and write all dynamic things by checking if DeviceInfo.IsPortait() is true or false (and this way I also let DeviceInfo have a Width and Height, so I can request the screen dimensions at any point).
On Android, I filled in my Android code as so:
[assembly: Dependency (typeof(Namespace.DeviceInfoProvider))]
namespace Namespace
{
public class DeviceInfoProvider : IDeviceInfoProvider
{
public bool IsPortait () { return DeviceInfoManager.Width < DeviceInfoManager.Height; }
public int GetWidth () { return DeviceInfoManager.Width; }
public int GetHeight () { return DeviceInfoManager.Height; }
}
public static class DeviceInfoManager
{
public static MainActivity MainActivity { get; set; }
public static int Width { get { return MainActivity.GetWidth (); } }
public static int Height { get { return MainActivity.GetHeight (); } }
}
}
Then in MainActivity I gave it these methods:
public int GetWidth() {
return (int)(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
}
public int GetHeight() {
return (int)(Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
}
And on the iOS side, I filled it in as so:
[assembly: Dependency (typeof(Namespace.DeviceInfoProvider))]
namespace Namespace {
public class DeviceInfoProvider : IDeviceInfoProvider {
public bool IsPortait() { return UIScreen.MainScreen.Bounds.Width < UIScreen.MainScreen.Bounds.Height; }
public int GetWidth() { return (int)UIScreen.MainScreen.Bounds.Width; }
public int GetHeight() { return (int)UIScreen.MainScreen.Bounds.Height; }
}
}
Personally, I am more of a fan of writing it the second way and making it check "if we are in portait mode, here are the differences". That way those things that are not different between portait and landscape only have to be written once, only the differences are written twice.
You can use OnSizeAllocated method override to detect orientation change;
double previousWidth;
double previousHeight;
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (previousWidth != width || previousHeight != height)
{
previousWidth = width;
previousHeight = height;
if (width > height)
{
// landscape mode
}
else
{
// portrait mode
}
}
}
I'm working with FlashBuilder 4.6 to develop Android app.
In the application there is a requirement of setting some values when device orientation changes. i.e. setting the values when the screen/device orientation changes from Landscape to Portrait and vice-verse.
Although Initially my application has LandScape orientation. And this requirement is on specific view.
I want every time when the screen/device orientation changes the values must be set there.
I am not getting the desired result.
Please guide me and tell me if I am at wrong in code or how can i achieve this.
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" title="{data}"
xmlns:mx="library://ns.adobe.com/flex/mx"
viewActivate="view1_viewActivateHandler(event)"
creationComplete="view1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void
{
if(Accelerometer.isSupported)
{
accl = new Accelerometer();
accl.addEventListener(AccelerometerEvent.UPDATE,update); //accl.addEventListener(AccelerometerEvent.UPDATE,adjustImage);
}
}
private function update(event:AccelerometerEvent):void
{
this.stage.autoOrients = true;
//in the below line I am attaching StageOrienationEvent that will adjust the
//values.
stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGE,adjust);
}
private function adjust(event:StageOrientationEvent):void
{
if(event.afterOrientation == StageOrientation.ROTATED_LEFT)
{
testVal.text ="After OR is LEFT";
}
else if(event.afterOrientation == StageOrientation.ROTATED_RIGHT)
{
testVal.text ="After OR is RIGHT";
}
else if(StageAspectRatio.LANDSCAPE)
{
testVal.text ="StageAspectRatio is Landscape";
}
else if(StageAspectRatio.PORTRAIT)
{
testVal.text="StageAspectRatio is Portrait";
}
}
</fx:Script>
Thanks.
Finally found the solution after spending two days on this.
in update function add OrientationChanging Event in stage.addEventListner.
private function update(event:AccelerometerEvent):void
{
this.stage.autoOrients = true;
stage.addEventListener(StageOrientationEvent.ORIENTATION_CHANGING,adjust);
}
private function adjust(event:StageOrientationEvent):void
{
switch(event.afterOrientation)
{
case StageOrientation.DEFAULT:
//Do Something here. The Portrait Position.
break;
case StageOrienatation.ROTATED_LEFT:
//Do Something here when you rotate your phone portrait to left side.
break;
case StageOrienatation.ROTATED_RIGHT:
//Do something here when you rotate your phone portrait to right side.
break;
}
}
Many thanks to all who viewed this question and try put their efforts for solution. :)
i am not a experimented coder! but : private function update(event:AccelerometerEvent):void should be : private function accl(event:AccelerometerEvent):void ?? or something like this in below code if(stage[not event].afterOrientation == ??? its just a opinion!
I'm developing an Android application that might be used at night. Therefor, I need to turn off the buttons' backlight. How can I do this? On my own phone the backlight turns off after a while, but on the Motorola Droid I don't think this happens.
I'm using a wakelock to keep the screen on. Should I use another flag or how can I do this?
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, WAKE_LOCK_TAG);
mWakeLock.acquire();
Thank you very much!
//Kaloer
There is a hack:
private void setDimButtons(boolean dimButtons) {
Window window = getWindow();
LayoutParams layoutParams = window.getAttributes();
float val = dimButtons ? 0 : -1;
try {
Field buttonBrightness = layoutParams.getClass().getField(
"buttonBrightness");
buttonBrightness.set(layoutParams, val);
} catch (Exception e) {
e.printStackTrace();
}
window.setAttributes(layoutParams);
}
I see that this is an old question that was mostly answered in a comment link, but to make it clear to anyone else who comes across this question, here's my own answer.
It's built-in since API 8. (doc)
float android.view.WindowManager.LayoutParams.buttonBrightness
This is a somewhat modified/simplified version of what I'm using in one of my apps (excluding irrelevant code). The inner class is required to prevent a crash at launch on older platforms that don't support it.
private void nightMode() {
Window win = getWindow();
LayoutParams lp = win.getAttributes();
if (prefs.getBoolean("Night", false))
changeBtnBacklight(lp, LayoutParams.BRIGHTNESS_OVERRIDE_OFF);
else changeBtnBacklight(lp, LayoutParams.BRIGHTNESS_OVERRIDE_NONE);
win.setAttributes(lp);
}
private void changeBtnBacklight(LayoutParams lp, float value) {
if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
try {
new BtnBrightness(lp, value);
} catch (Exception e) {
Log.w(TAG, "Error changing button brightness");
e.printStackTrace();
}
}
}
private static class BtnBrightness {
BtnBrightness(LayoutParams lp, float v) {
lp.buttonBrightness = v;
}
}
AFAIK, there is no API to control the backlight of the buttons -- sorry!