I was searching how to change the brightness of the screen programmatically and I found this it is very good solution and it works nice, but it works only while my app is active. After my application is shutdown then the brightness is returned back the the same value as before I start my app.
I want to be able to change the brightness just like when I press on the brightness button from my power widget. In the power widget that comes from android there are 3 states. One very bright one very dark and one in between. Is it possible to change the brightness just like when someone press on this widget ?
Edit1:
I created this and I added permision to my manifest but when the app is started I do not see any changes to the brightness, I tried with 10 with 100 and now with 200 but no changes
any suggestions ?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
android.provider.Settings.System.putInt(this.getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, 200);
}
This is the complete code I found to be working:
Settings.System.putInt(this.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 20);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness =0.2f;// 100 / 100.0f;
getWindow().setAttributes(lp);
startActivity(new Intent(this,RefreshScreen.class));
The code from my question does not work because the screen doesn't get refreshed. So one hack on refreshing the screen is starting dummy activity and than in on create of that dummy activity to call finish() so the changes of the brightness take effect.
Use Tor-Morten's solution in that link, but also set the system brightness setting like so:
android.provider.Settings.System.putInt(getContext().getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, bright);
Where bright is an integer ranging from 1 to 255.
I have solved this problem today.
As the first you have to put a permission into your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Where is the exact place to put it in the file?
<manifest>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<application>
<activity />
</application>
</manifest>
This permission says, that you are allowed to change settings that affect other applications too.
Now you can set brightness automatic mode on and off
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); //this will set the automatic mode on
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); //this will set the manual mode (set the automatic mode off)
Is the automatic mode turned on or off right now? You can get the information
int mode = -1;
try {
mode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE); //this will return integer (0 or 1)
} catch (Exception e) {}
So, if you want to change brightness manually, you are supposed to set the manual mode first and after that you can change the brightness.
note: SCREEN_BRIGHTNESS_MODE_AUTOMATIC is 1
note: SCREEN_BRIGHTNESS_MODE_MANUAL is 0
You should use this
if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
//Automatic mode
} else {
//Manual mode
}
instead of this
if (mode == 1) {
//Automatic mode
} else {
//Manual mode
}
Now you can change the brightness manually
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness); //brightness is an integer variable (0-255), but dont use 0
and read brightness
try {
int brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); //returns integer value 0-255
} catch (Exception e) {}
Now everything is set properly, but... you can't see the change yet.
You need one more thing to see the change!
Refresh the screen... so do this:
try {
int br = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); //this will get the information you have just set...
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = (float) br / 255; //...and put it here
getWindow().setAttributes(lp);
} catch (Exception e) {}
Don't forget the permission...
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Passing the context of the activity while setting up the parameters would also get the job done without any need to start another activity.
The following worked for me-
WindowManager.LayoutParams lp = this.getWindow().getAttributes();
lp.screenBrightness =0.00001f;// i needed to dim the display
this.getWindow().setAttributes(lp);
i had this piece of code inside onSensorChanged() method which dimmed the display whenever it was triggered.
COMPLEX EXAMPLE:
try {
//sets manual mode and brightnes 255
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); //this will set the manual mode (set the automatic mode off)
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 255); //this will set the brightness to maximum (255)
//refreshes the screen
int br = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = (float) br / 255;
getWindow().setAttributes(lp);
} catch (Exception e) {}
Related
I was trying to switch between 'full brightness' and 'phones normal brightness' by using a switch button in my main activity.
I successfully handled the switching of brightness by using this code:
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);
} else {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
getWindow().setAttributes(params);
}
}
});
if (switchButton.isChecked()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);
} else {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
getWindow().setAttributes(params);
}
The problem is,
after switching to 'full Brightness', when I change the activity, the brightness goes normal.
Now, How can I keep track of the 'brightness setting' from 'main activity' and apply it to the other activities of the app?
N.B. I don't want to change system brightness. Brightness will only change while using the app.
Thanks In Advance.
ok.
Finally solved my problem.
I have created a class having the logic of brightness controlling using SharedPreferences to Handle the state.
code:
if (br.getString("set", "").equals("1")) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);
} else {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
getWindow().setAttributes(params);
}
Then extend the class with the activities and initialize SharedPreferences in onCreate method.
br = getSharedPreferences("br", Activity.MODE_PRIVATE);
Thank you #0X0nosugar for the idea.
You need to hold a SCREEN_BRIGHT_WAKE_LOCK if you want it to have an effect beyond your activity. The method you are using above applies to the foreground window, and when you activity goes away that no longer applies.
Note Android generally frowns on use of wake locks because it's easy to screw up and not release them, wasting the devices battery. They recommend the window param version for the vary reason that it automatically releases when the user leaves the activity.
I want to set the brightness of my android application only and not my phone. How do I change the brightness of my android application such that it does not effect my mobile phone brightness?
No need to give any permission only set Following Params in your Seekbar's Method
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
float BackLightValue = (float)arg1/100;
BackLightSetting.setText(String.valueOf(BackLightValue)); // BackLignt is Textview to display value
WindowManager.LayoutParams layoutParams = getWindow().getAttributes(); // Get Params
layoutParams.screenBrightness = BackLightValue; // Set Value
getWindow().setAttributes(layoutParams); // Set params
}
Get and Save the current brightness of your device, then change the brightness of the device(when your app starts running), and when your application closes revert back to the original brightness using the saved brightness level.
To Get Screen Brightness Level:
int curBrightnessValue = android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS);
To Set Screen Brightness Level:
android.provider.Settings.System.putInt(getContext().getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, value); //<-- 1-225
App manifest permissions:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
or
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = curBrightnessValue/100.0f; //<-- your value here
getWindow().setAttributes(layoutParams);
here is a tutorial link
Another SO Post Link
P.S: you will have to handle all events like onPause(), onResume(), onBackPressed() etc
I have an activity in which I'm using ProgressDialog.
After performing dialog.dismiss(), the screen remains grey until the user press the screen and then it gets light.
How can I make the screen light after the dialog.dismiss() command ?
int brightnessMode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = 0.5F; // set 50% brightness
getWindow().setAttributes(layoutParams);
Here's a pseudo code to detect screen rotate event, and decide to retain or changes the screen orientation.
public boolean onOrientationChanges(orientation) {
if(orientation == landscape)
if(settings.get("lock_orientation"))
return false; // Retain portrait mode
else
return true; // change to landscape mode
return true;
}
How do I make similar things in Android?
EDIT:
I'm actually looking answer on Where to handle orientation changes. I do not want to fix the orientation by adding screenOrientation="portrait".
I need something, similar to onConfigurationChanges(), where I can handle the orientation, but do no need me to manually redraw the view.
You need a Display instance firstly:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
Then orientation may be called like this:
int orientation = display.getOrientation();
Check orientation as your way and use this to change orientation:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
I hope it helps.
Update:
Okay, let's say you've an oAllow var which is Boolean and default value is False.
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
if(!oAllow) {
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
break;
case Configuration.ORIENTATION_LANDSCAPE:
if(!oAllow) {
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
break;
}
}
You can add more choices.
I didn't try this sample, but at least tells you some clues about how to solve. Tell me if you got any error.
UPDATE
getOrientation() is already deprecated see here. Instead Use getRotation(). To check if the device is in landscape mode you can do something like this:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
.getDefaultDisplay();
int orientation = display.getRotation();
if (orientation == Surface.ROTATION_90
|| orientation == Surface.ROTATION_270) {
// TODO: add logic for landscape mode here
}
Try running
getResources().getConfiguration().orientation
From your context object to figure out what is the screen orientation at runtime, the possible values are documented here
In order to catch the orientation change event you can find the answer in the Android Dev Guide: Handling the Configuration Change Yourself
From the guide :
For example, the following manifest code declares an activity that
handles both the screen orientation change and keyboard availability
change:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.
...
if (this.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
// portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
.getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
// landscape
}
You don't need to intercept the event and then override it. Just use:
// Allow rotation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
// Lock rotation (to Landscape)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
Points to note here are, if on Jellybean and above this will allow a 180 degree rotation when locked. Also when unlocked this only allows rotation if the user's master settings is to allow rotation. You can forbid 180 degree rotations and override the master settings and allow rotation, and much much more, so check out the options in ActivityInfo
In addition, if you have pre-set that there is to be no rotation, then your activity will not be destroyed and then restarted, just for you to set the orientation back which will again cause the activity to be restarted; Thus setting what you want in advance can be much more efficient.
Pre Jellybean use ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE -- no 180 degree rotation with this.
Check your android screen orientation at Runtime:
ListView listView = (ListView) findViewById(R.id.listView1);
if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
//do work for landscape screen mode.
listView.setPadding(0, 5, 0, 1);
} else if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
//Do work for portrait screen mode.
listView.setPadding(1, 10, 1, 10);
}
Another solution to determine screen orientation:
public boolean isLandscape() {
return Resources.getSystem().getDisplayMetrics().widthPixels - Resources.getSystem().getDisplayMetrics().heightPixels > 0;
}
I'm using the following to set the system auto brightness mode and level:
android.provider.Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
android.provider.Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, y.brightness1);
I can change auto-brighess on and off, and set different levels. The settings seem to be applied properly -- I can go to into Settings --> Display --> Brightness, and whanever setting I set is actually shown correctly. However, the actual screen isn't changing its brightness. If i just tap on the slider in Display Settings, then everything gets applied.
I shoudl mention that I'm running an app withat a main activity, and these settings are getting applied in the BroadcastReceiver. I did try to create a dummy activity and tested the stuff there, but got the same results.
OK, found the answer here:
Refreshing the display from a widget?
Basically, have to make a transparent activity that processes the brightness change. What's not mentioned in the post is that you have to do:
Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS_MODE, 0);
Settings.System.putInt(y.getContentResolver(),Settings.System.SCREEN_BRIGHTNESS, brightnessLevel);
then do
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);
And if you call finish() right after applying the changes, brightness will never actually change because the layout has to be created before the brightness settings is applied. So I ended up creating a thread that had a 300ms delay, then called finish().
I'm doing something similar with screen brightness in one of my apps, and I'm doing it through the WindowManager and it works. I'm using the following code to get the current screen brightness (and save it for later) and set it to full:
WindowManager.LayoutParams lp = getWindow().getAttributes();
previousScreenBrightness = lp.screenBrightness;
float brightness = 1;
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);
Use the answer given by "user496854" above
If you are taking max screenBrightness =255 then while doing
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness; getWindow().setAttributes(lp);
divide screenBrightness by 255 like
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness/(float)255;
getWindow().setAttributes(lp);
I created a static method in my Application class which I invoke from all my Activity.onResume() methods.
MyApplication extends Application {
...
public static void setBrightness(final Activity context) {
// get the content resolver
final ContentResolver cResolver = context.getContentResolver();
// get the current window
final Window window = context.getWindow();
try {
// get the current system brightness
int brightnessLevel = System.getInt(cResolver,System.SCREEN_BRIGHTNESS);
// get the current window attributes
LayoutParams layoutpars = window.getAttributes();
// set the brightness of this window
layoutpars.screenBrightness = brightnessLevel / (float) 255;
// apply attribute changes to this window
window.setAttributes(layoutpars);
} catch (SettingNotFoundException e) {
// throw an error cuz System.SCREEN_BRIGHTNESS couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
}
}
MyActivity extends Activity {
...
public void onResume() {
super.onResume();
Log.d(TAG, "onResume()");
MyApplication.setBrightness(this);
}
}