Set Lock Screen Wallpaper (Android) [duplicate] - android

I'm just getting started with android programming, and want to see if there is a way to programmatically set the lock screen image. I've found various ways of setting the wallpaper in the API, but I can't seem to find the equivalent ways of setting the lock screen image.
I've seen various posts saying that customising the lock screen by adding widgets or bits of applications is not possible, but surely there must be a way to set the image programmatically?
Cheers,
Robin

As of API Level 24 they have added new methods (and updated the documentation) and flags to the WallpaperManager which allow you to set a Wallpaper not only to the home screen but also to the Lockscreen
To set a Wallpaper to the Lockscreen use the new flag WallpaperManager.FLAG_LOCK, and one of the methods which take int which
WallpaperManager.getInstance(this).setStream(inputStream, null, true, WallpaperManager.FLAG_LOCK);
You can also use one of the following methods
int setStream (InputStream bitmapData, Rect visibleCropHint, boolean allowBackup, int which)
int setResource (int resid, int which)
int setBitmap (Bitmap fullImage, Rect visibleCropHint, boolean allowBackup, int which)
A nice addition is that you can now also check if you are allowed to set the wallpaper via isSetWallpaperAllowed, and get the current set wallpaper via getWallpaperFile
Check out the updated documentation for the WallpaperManager.

There is no "lock screen image" in Android. There most certainly is no "lock screen image" concept that is the same between stock Android, HTC Sense, MOTOBLUR, etc. This simply is not part of the Android SDK.
The project that Mr. Rijk points to is a security violation that pretends to be a lock screen replacement.

There is a way to do it on Samsung devices. In the intent you can put an extra.
intent.putExtra("SET_LOCKSCREEN_WALLPAPER", true);
startActivity(intent);
I've only tested this on some Samsung phones and there's no guarantee that this won't break some time in the future. Use with caution.

You can use these three methods of WalpaperManager class but it will only work for nought version devices or above it:-
public int setBitmap (Bitmap fullImage,
Rect visibleCropHint,
boolean allowBackup,
int which)
public int setResource (int resid,
int which)
public int setStream (InputStream inputStreamData,
Rect visibleCropHint,
boolean allowBackup,
int which)
Parameter of these three methods:-
Bitmap/resid/inputStreamData :-this parameter accept data
visibleCropHint:-this parameter accept Rect object which is mainly used for Cropping functionality, for more information refer to Android developer reference website, you can also pass null if u don't want cropping functionality
allowBackup:-boolean: true if the OS is permitted to back up this wallpaper image for restore to a future device; false otherwise.
which:-It is one of the most important parameter which helps you to configure wallpaper for lock screen and home wallpaper. for lock screen use WalpaperManager.FLAG_LOCK and for home wallpaper use FLAG_SYSTEM
I am giving one example to make you understand how to use it:-
WalaperManager wm = WalaperManager.getInstance();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
wm.setBitmap(bitmap,null,true,WalpaperManager.FLAG_LOCK);//For Lock screen
Toast.makeText(context.context, "done", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context.context, "Lock screen walpaper not supported",
Toast.LENGTH_SHORT).show();
}
} catch (e: Exception) {
Toast.makeText(context.context, e.message, Toast.LENGTH_SHORT).show();
}
for more information visit Android developer wallpaper manager reference

There is another way to do this. at first ,you need save the pic which you wanna set in lockedscreen in a folder(suppose it's called "appName").and then ,use following code to open gallery, after gallery has opened.lead user to open "appName" folder ,and choose the pic in gallery of system. in the gallery,user can set a pic as wallpaper or lockscreen paper.
// this code to open gallery.
startActivity(new Intent(Intent.ACTION_SET_WALLPAPER));

Bitmap icon = BitmapFactory.decodeResource(getViewContext().getResources(), R.drawable.wall);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getViewContext());
try {
wallpaperManager.setBitmap(icon, null, true, WallpaperManager.FLAG_LOCK);
} catch (IOException e) {
e.printStackTrace();
}

usage for api30+
public void onWallpaperChanged(Bitmap bitmap, boolean onHomeScreen, boolean onLockScreen) {
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
if(onHomeScreen) {
myWallpaperManager.setBitmap(bitmap);// For Home screen
}
if(onLockScreen) {
myWallpaperManager.setBitmap(bitmap,null,true, WallpaperManager.FLAG_LOCK);//For Lock screen
}
} catch (IOException e) {
e.printStackTrace();
}
}

Since API level 24, you can set wallpaper to your home screen, lock screen, or both:
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// home screen
wallpaperManager.setBitmap(mBitmap, null, true, WallpaperManager.FLAG_SYSTEM);
// lock screen
wallpaperManager.setBitmap(mBitmap, null, true, WallpaperManager.FLAG_LOCK);
// home screen & lock screen
wallpaperManager.setBitmap(mBitmap, null, true, WallpaperManager.FLAG_LOCK | WallpaperManager.FLAG_SYSTEM);
} else {
wallpaperManager.setBitmap(mBitmap);
}
source

Related

What is the use of setTouchExplorationPassthroughRegion() in android accessibility API?

I am developing an Android application that uses accessibility-service, and I want to disable explore-by-touch when the user opens specific applications like Piano, Games, etc.
I read API documentation of setTouchExplorationPassthroughRegion()
public void setTouchExplorationPassthroughRegion (int displayId,
Region region)
When AccessibilityServiceInfo#FLAG_REQUEST_TOUCH_EXPLORATION_MODE is
enabled, this function requests that touch interactions starting in
the specified region of the screen bypass the touch explorer and go
straight to the view hierarchy. There can only be one-touch
exploration passthrough region per display. Requesting a new touch
explorationpassthrough region clears the existing one. To disable this
passthrough and return to the original behaviour, pass in an empty
region. When
AccessibilityServiceInfo.FLAG_REQUEST_TOUCH_EXPLORATION_MODE is
disabled this function has no effect.
So I tried the above function in Android-11 but explore-by-touch is not getting disabled.
What can I do to disable explore-by-touch in some applications.
Note: The user might be running his own Accessibility-Service like TalkBack screen reader which also uses the Explore-By-Touch feature.
This function is working in Android 11 and above with proper context and region
//Disabling explore by touch
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
setTouchExplorationPassthroughRegion(
Display.DEFAULT_DISPLAY, getRegionOfFullScreen(name_of_the_view.getContext()));
}
private Region getRegionOfFullScreen(Context context) {
final DisplayMetrics metrics = new DisplayMetrics();
final Display display;
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
display = dm.getDisplay(Display.DEFAULT_DISPLAY);
if (display == null) {
return new Region();
} else {
display.getRealMetrics(metrics);
return new Region(0, 0, metrics.widthPixels, metrics.heightPixels);
}
}
Don't forget to enable Explore-By-Touch if your view is not active or removed using following code
//Enabling explore by touch
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
setTouchExplorationPassthroughRegion(Display.DEFAULT_DISPLAY, new Region());
}

Stop pre-installed screen recording apps from recording screen in android

I am using flutter and have disabled normal apps from recording the screen.
Here is the code
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
The problem is there are some phones where screen recordings apps are pre-installed and above code can't stop them from recording the screen.
So is there any other way to stop these apps from recording the screen?
On other answers I saw that this was not possible but there are some apps on playstore which successfully achieve this. So there must be a way.
I was thinking, as screen recording apps are drawn over , they might be detected through a piece of code hence we can show a pop up while screen recording app is drawn over.
Is it possible ? If yes how can we detect if the app is drawn over our app.
Thanks.
As far as I'm aware, there is no official way to universally prevent screen grabs/recordings.
This is because FLAG_SECURE just prevents capturing on non-secure displays:
Window flag: treat the content of the window as secure, preventing it from appearing in screenshots or from being viewed on non-secure displays.
But apps that have elevated permissions can create a secure virtual display and use screen mirroring to record your screen, which does not respect the secure flag.
Read this article for more info:
That would mean that an Android device casting to a DRM-protected display like a TV would always display sensitive screens, since the concept of secure really means “copyrighted”. For apps, Google forestalled this issue by preventing apps not signed by the system key from creating virtual “secure” displays
Regarding how some apps still manage to do it, you could try these:
Check if there are any external/virtual displays connected, and hide/show your content based on that. see this
Don't show your content on rooted devices
Adding this code to my MainActivity.java solved the problem:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!this.setSecureSurfaceView()) {
Log.e("MainActivity", "Could not secure the MainActivity!");
}
}
private final boolean setSecureSurfaceView() {
ViewGroup content = (ViewGroup) this.findViewById(android.R.id.content);
//Intrinsics.checkExpressionValueIsNotNull(content, "content");
if (!this.isNonEmptyContainer((View) content)) {
return false;
} else {
View splashView = content.getChildAt(0);
//Intrinsics.checkExpressionValueIsNotNull(splashView, "splashView");
if (!this.isNonEmptyContainer(splashView)) {
return false;
} else {
View flutterView = ((ViewGroup) splashView).getChildAt(0);
//Intrinsics.checkExpressionValueIsNotNull(flutterView, "flutterView");
if (!this.isNonEmptyContainer(flutterView)) {
return false;
} else {
View surfaceView = ((ViewGroup) flutterView).getChildAt(0);
if (!(surfaceView instanceof SurfaceView)) {
return false;
} else {
((SurfaceView) surfaceView).setSecure(true);
this.getWindow().setFlags(8192, 8192);
return true;
}
}
}
}
}
private final boolean isNonEmptyContainer(View view) {
if (!(view instanceof ViewGroup)) {
return false;
} else {
return ((ViewGroup) view).getChildCount() >= 1;
}
}
Import the required things.

Show extended string (weather temperature) permanently on the Status Bar over a transparent background with all characters right size and visible

I'm Appy Weather's developer, and looking at giving its users the ability to show the temperature permanently on the Status Bar. Unfortunately, it doesn't appear to be straightforward, and I'm not even sure possible (though the fact other apps allow for this makes me think it must be somehow).
Please note the following:
1) the app targets Android 8.0 upwards
2) this is a Xamarin.Android app
Using TextDrawable, I've managed to dynamically create a Drawable that's converted to a Bitmap showing the current temperature that is accepted by the Notification.Builder's SetSmallIcon():
Notification.Builder builder = new Notification.Builder(context, channelId)
.SetContentText(text)
.SetOngoing(true);
var bld = Android.Ui.TextDrawable.TextDrawable.TextDrwableBuilder.BeginConfig().FontSize(72).UseFont(Typeface.Create("sans-serif-condensed", TypefaceStyle.Normal)).EndConfig();
var drawable = bld.BuildRect(title, Color.Red);
builder.SetSmallIcon(Icon.CreateWithBitmap(Helper_Icon_Droid.drawableToBitmap(drawable)));
This works:
But it isn't perfect because:
1) text size would ideally be the maximum possible in the Status Bar i.e. same as the clock's
2) width available means if the temperature is 100°+, or -10° or less, and possibly certain double digit number pairings, then it wouldn't fit and gets cut-off
3) the text will only be visible if the background's set to a colour that isn't black, white or transparent, which is not good because it's important for this to not have a solid background colour
UPDATE 1
So, as Raimo commented below, SetTicker() isn't the correct solution. Not that I've discovered it yet, but Saamer's WindowManager tip has resulted in me hopefully getting closer to the desired outcome.
I've added the following permissions to the Manifest:
<uses-permission android:name="android.permission.ACTION_MANAGE_OVERLAY_PERMISSION" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
I request permission within my Settings activity:
// permissions
public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 5469;
private string[] _permissions =
{
Manifest.Permission.SystemAlertWindow
};
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE)
{
if ( Android.Provider.Settings.CanDrawOverlays(MainApplication.Context) )
{
JobManager.Instance().Scheduler().setJobTemp();
}
}
}
public void checkDrawOverlayPermission()
{
try
{
// check if we already have permission to draw over other apps
// if we don't, we need to get system permission
if ( !Android.Provider.Settings.CanDrawOverlays(MainApplication.Context) )
{
var intent = new Intent(Android.Provider.Settings.ActionManageOverlayPermission, Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName));
StartActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
// otherwise, set up the job
else
{
JobManager.Instance().Scheduler().setJobTemp();
}
}
catch (Exception ex)
{
}
}
I'm taken correctly to the phone's relevant settings permission screen, and when I grant permission and return to Settings it will run the method seen below that schedules an hourly Job (using an internal helper method I created that works fine) when the user ticks the relevant setting, as well as pushing it to the status bar directly and immediately outside the job:
public void setJobTemp()
{
try
{
if (_scheduler.GetPendingJob(Helper_Notification._NOTIFICATION_ID_TEMP) == null)
{
_jobTemp = _context.CreateJobBuilderUsingJobId<Job_Temp>(Helper_Notification._NOTIFICATION_ID_TEMP);
bool success = Helper_Job.ScheduleJob(_context, _jobTemp, 60, 5);
// besides setting the hourly job above, we want to immediately push it out too
Helper_Notification.Push( ViewModel._instance._http.Response.Hourly.Data[ViewModel._instance._http.Response.Hourly._indexStartFrom].Temperature );
}
}
catch (Exception ex)
{
}
}
This is the Resource.Layout.StatusBar_Temp resource layout file I've created to be used (using a placeholder value for the TextView for testing purposes):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/root"
style="#style/LayoutWrap">
<TextView
android:id="#+id/value"
style="#style/TextWrap"
android:text="abc"/>
</LinearLayout>
And finally, this is the method used to push out the update to the Status Bar:
public static void Push( string text )
{
IWindowManager windowManager = MainApplication.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
var temp = LayoutInflater.From(MainApplication.Context).Inflate(Resource.Layout.StatusBar_Temp, null);
var layoutParams = new WindowManagerLayoutParams(1, 1, WindowManagerTypes.ApplicationOverlay, WindowManagerFlags.NotFocusable, Format.Translucent);
layoutParams.Gravity= GravityFlags.Top | GravityFlags.Left;
layoutParams.X = 0;
layoutParams.Y = 0;
windowManager.AddView(temp, layoutParams);
}
I'm using WindowManagerTypes.ApplicationOverlay because the other system types that seem to have been suggested in the past can no longer be used from 8.0 up anyway (was hitting exceptions when I tried them originally).
At the moment, with the above code, I'm not running into any exceptions, and everything appears to run smoothly both when the Job runs as well as on the initial push. However, there's a big problem: nothing appears to be drawn. For what it's worth, originally I attempted this by creating a LinearLayout containing a TextView programmatically (as opposed to using an existing layout), but that had the same issue with nothing being visible.
Any ideas?
Have you tried to use SetTicker()? So your code would look something like this (might have to use unicode 00B0 for the degree symbol)
Notification.Builder builder = new Notification.Builder(context, channelId)
.SetContentText(text)
.SetOngoing(true);
.SetTicker("17°");
There's an alternate way of figuring out the StatusBarHeight and the LayoutParams, and then adding a TextView to a LinearLayout which is then added to the WindowManager using all the information.

hasSystemFeature(PackageManager.FEATURE_CAMERA) returns true for device with no camera

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

How to toggle auto brightness on and off? (not a repeat)

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;
}
}

Categories

Resources