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;
}
Related
What does setting android:screenOrientation in the activity of the AndroidManifest.xml actually do?
If I set it, I can still change my screen orientation - so my question is what is its purpose?
I have a Unity game in portrait, that in one section I want to enable rotation - I can do this from Unity without changing the manifest - so it doesn't appear to be preventing me from changing screen orientation - so what is the purpose of it?
Should my game be SensorPortrait, or FullSensor because I enable rotation at one point? What will the difference be?
The docs indicate that it's used for filtering purposes in the Play store, but surely it serves some other purpose?
The android:screenOrientation parameter in the manifest is intended to change the activity orientation.
The reason why it doesn't seem to do anything is because of Unity, it seems. This forum describes a similar problem and solution:
We currently do override the Android manifest with a custom one, which works well in most cases. However, I found that when I try to override the screenOrientation value, it doesn't seem to stick through the build pipeline. At some point, I think Unity overwrites the screenOrientation attribute depending on the PlayerSettings values. Unfortunately though, there doesn't seem to be a PlayerSettings configuration that allows us to use the "userPortrait" setting.
// as an android plugin through unity
public static int GetAutorotateSetting(Activity activity)
{
int setting = 0;
try
{
setting = Settings.System.getInt(activity.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION);
}
catch(Exception e)
{
Log.i("Unity", "Couldn't retrieve auto rotation setting: " + e.getMessage());
}
return setting;
}
// on the unity side:
public static bool AllowAutorotation()
{
bool doAutorotation = false;
#if !UNITY_EDITOR && UNITY_ANDROID
AndroidJavaClass unity = newAndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject unityActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
using(AndroidJavaClass andClass = new AndroidJavaClass("PUT YOUR JAVA CLASS HERE"))
{
int allowAutorotation = andClass.CallStatic<int>("GetAutorotateSetting", unityActivity);
if(allowAutorotation == 0)
{
doAutorotation = false;
}
else
{
doAutorotation = true;
}
}
#endif
return doAutorotation;
}
The person who suggested this solution also put a .unitypackage file on github.
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.
I'm developing an app with React Native for both iOS and Android, and I am trying to prevent device-specific scaling of the display in the app.
For text/font size scaling, putting the following code in the root-level App.js file solves the issue for both iOS and Android:
if (Text.defaultProps == null) {
Text.defaultProps = {};
}
Text.defaultProps.allowFontScaling = false;
However, Android devices have the following Display size setting that is still being applied:
I've tried (unsuccessfully) to piece together a variety of "solutions" to this issue that I've found in answers to the following questions:
Change the system display size programatically Android N
Disabling an app or activity zoom if Setting -> Display -> Display size changed to Large or small
how to prevent system font-size changing effects to android application?
I've often found references to a BaseActivity class that extends the Activity class. My understanding is that it is inside of that class where I would be writing a method (let's call it adjustDisplayScale) to make changes to the Configuration of the Context that I get from Resources, and that then I would be calling adjustDisplayScale within the onCreate() method after super.onCreate() in the MainApplication.java file.
As of now, in this directory I just have two files - MainApplication.java and MainActivity.java.
I've attempted creating a new Module and associated Package file to implement adjustDisplayScale following these instructions and it did not work:
https://facebook.github.io/react-native/docs/text.html
I've attempted placing implementing the functionality of adjustDisplayScale within the onCreate() like this and it did not work:
#Override
public void onCreate() {
super.onCreate();
Context context = getApplicationContext();
Resources res = context.getResources();
Configuration configuration = res.getConfiguration();
configuration.fontScale = 1f;
DisplayMetrics metrics = res.getDisplayMetrics();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
metrics.scaledDensity = 1f;
configuration.densityDpi = (int) res.getDisplayMetrics().xdpi;
context = context.createConfigurationContext(configuration);
SoLoader.init(this, /* native exopackage */ false);
}
A potentially promising answer included the following:
protected override void AttachBaseContext(Context #base) {
var configuration = new Configuration(#base.Resources.Configuration);
configuration.FontScale = 1f;
var config = Application.Context.CreateConfigurationContext(configuration);
base.AttachBaseContext(config);
}
But when I tried to utilize this, I got errors about not recognizing the symbol #base.
Some background... I've done 99% of my work on this project in JavaScript / React Native and I have almost no understanding about things like Resources, Context, Configuration, and DisplayMetrics associated with Android development AND the last time I wrote code in Java was 10 years ago. I've spent a number of agonizing hours trying to figure this out and any help would be greatly appreciated.
ps. I am well-aware that accessibility settings exist for a good reason so please spare me the diatribe I've seen in so many "answers" on why I need to fix my UI to work with accessibility settings rather than disable them.
NOTE
I strongly discourage applying such a solution. In a certain way, Screen Zoom just "emulates" different screen sizes and densities in the same device. So, if your app can't handle well a specific screen zoom level, it means that your app may not be displayed correctly on a real screen out there. If your app can't support screen changes, tell the user about it...
There are some docs about screen sizes in the Android Developer and that's how you should handle different screen sizes.
On Android 12, it seems this the context created via context.createConfigurationContext(configuration) is imuttable. So, you may have problems on Android 12 when rotating the device, for example. context.getResources().getxxxxx() may return portrait resources (because the context was created in portrait) instead of landscape resources (the new orientation)
Support Different Screen Sizes
supports-screens-element
The answer below is just a "hack" where I tried to circumvent the screen zoom feature. I don't use that on my apps and I strongly recommend dealing with the screen zoom in a more conventional way.
Answer
My first answer does not work if you change the screen resolution. On Samsung devices, you can change the screen zoom but you can also change the screen resolution on some models (Settings->Display->Screen Resolution-> HD, FHD, WQHD etc).
So, I came up with a different code which seems to work with that feature as well. Just, please, note I can't fully test this code since I don't have too many devices to test. On those devices I tested, it seems to work.
One additional note. Ideally, you don't need to use such kind of code to circumvent the screen zoom. In a certain way, the screen zoom is just "simulating" bigger or smaller screens. So, if your app properly supports different screen sizes, you don't need to completely "disable" the screen zoom.
public class BaseActivity extends AppCompatActivity {
#TargetApi(Build.VERSION_CODES.N)
private static final int[] ORDERED_DENSITY_DP_N = {
DisplayMetrics.DENSITY_LOW,
DisplayMetrics.DENSITY_MEDIUM,
DisplayMetrics.DENSITY_TV,
DisplayMetrics.DENSITY_HIGH,
DisplayMetrics.DENSITY_280,
DisplayMetrics.DENSITY_XHIGH,
DisplayMetrics.DENSITY_360,
DisplayMetrics.DENSITY_400,
DisplayMetrics.DENSITY_420,
DisplayMetrics.DENSITY_XXHIGH,
DisplayMetrics.DENSITY_560,
DisplayMetrics.DENSITY_XXXHIGH
};
#TargetApi(Build.VERSION_CODES.N_MR1)
private static final int[] ORDERED_DENSITY_DP_N_MR1 = {
DisplayMetrics.DENSITY_LOW,
DisplayMetrics.DENSITY_MEDIUM,
DisplayMetrics.DENSITY_TV,
DisplayMetrics.DENSITY_HIGH,
DisplayMetrics.DENSITY_260,
DisplayMetrics.DENSITY_280,
DisplayMetrics.DENSITY_XHIGH,
DisplayMetrics.DENSITY_340,
DisplayMetrics.DENSITY_360,
DisplayMetrics.DENSITY_400,
DisplayMetrics.DENSITY_420,
DisplayMetrics.DENSITY_XXHIGH,
DisplayMetrics.DENSITY_560,
DisplayMetrics.DENSITY_XXXHIGH
};
#TargetApi(Build.VERSION_CODES.P)
private static final int[] ORDERED_DENSITY_DP_P = {
DisplayMetrics.DENSITY_LOW,
DisplayMetrics.DENSITY_MEDIUM,
DisplayMetrics.DENSITY_TV,
DisplayMetrics.DENSITY_HIGH,
DisplayMetrics.DENSITY_260,
DisplayMetrics.DENSITY_280,
DisplayMetrics.DENSITY_XHIGH,
DisplayMetrics.DENSITY_340,
DisplayMetrics.DENSITY_360,
DisplayMetrics.DENSITY_400,
DisplayMetrics.DENSITY_420,
DisplayMetrics.DENSITY_440,
DisplayMetrics.DENSITY_XXHIGH,
DisplayMetrics.DENSITY_560,
DisplayMetrics.DENSITY_XXXHIGH
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("TESTS", "Dimension: " + getResources().getDimension(R.dimen.test_dimension));
}
#Override
protected void attachBaseContext(final Context baseContext) {
Context newContext = baseContext;
// Screen zoom is supported from API 24+
if(Build.VERSION.SDK_INT >= VERSION_CODES.N) {
Resources resources = baseContext.getResources();
DisplayMetrics displayMetrics = resources.getDisplayMetrics();
Configuration configuration = resources.getConfiguration();
Log.v("TESTS", "attachBaseContext: currentDensityDp: " + configuration.densityDpi
+ " widthPixels: " + displayMetrics.widthPixels + " deviceDefault: " + DisplayMetrics.DENSITY_DEVICE_STABLE);
if (displayMetrics.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE) {
// display_size_forced exists for Samsung Devices that allow user to change screen resolution
// (screen resolution != screen zoom.. HD, FHD, WQDH etc)
// This check can be omitted.. It seems this code works even if the device supports screen zoom only
if(Settings.Global.getString(baseContext.getContentResolver(), "display_size_forced") != null) {
Log.v("TESTS", "attachBaseContext: This device supports screen resolution changes");
// density is densityDp / 160
float defaultDensity = (DisplayMetrics.DENSITY_DEVICE_STABLE / (float) DisplayMetrics.DENSITY_DEFAULT);
float defaultScreenWidthDp = displayMetrics.widthPixels / defaultDensity;
Log.v("TESTS", "attachBaseContext: defaultDensity: " + defaultDensity + " defaultScreenWidthDp: " + defaultScreenWidthDp);
configuration.densityDpi = findDensityDpCanFitScreen((int) defaultScreenWidthDp);
} else {
// If the device does not allow the user to change the screen resolution, we can
// just set the default density
configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE;
}
Log.v("TESTS", "attachBaseContext: result: " + configuration.densityDpi);
newContext = baseContext.createConfigurationContext(configuration);
}
}
super.attachBaseContext(newContext);
}
#TargetApi(Build.VERSION_CODES.N)
private static int findDensityDpCanFitScreen(final int densityDp) {
int[] orderedDensityDp;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
orderedDensityDp = ORDERED_DENSITY_DP_P;
} else if(Build.VERSION.SDK_INT >= VERSION_CODES.N_MR1) {
orderedDensityDp = ORDERED_DENSITY_DP_N_MR1;
} else {
orderedDensityDp = ORDERED_DENSITY_DP_N;
}
int index = 0;
while (densityDp >= orderedDensityDp[index]) {
index++;
}
return orderedDensityDp[index];
}
}
ORIGINAL ANSWER
You can try following code (overriding attachBaseContext). This will "disable" the screen zoom in on your app. This is the way to re-scale the whole screen at once.
#Override
protected void attachBaseContext(final Context baseContext) {
Context newContext;
if(Build.VERSION.SDK_INT >= VERSION_CODES.N) {
DisplayMetrics displayMetrics = baseContext.getResources().getDisplayMetrics();
Configuration configuration = baseContext.getResources().getConfiguration();
if (displayMetrics.densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE) {
// Current density is different from Default Density. Override it
configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE;
newContext = baseContext.createConfigurationContext(configuration);
} else {
// Same density. Just use same context
newContext = baseContext;
}
} else {
// Old API. Screen zoom not supported
newContext = baseContext;
}
super.attachBaseContext(newContext);
}
On that code, I check if the current density is different from the Device's default density. If they are different,
I create a new context using default density (and not the current one). Then, I attach this modified context.
You must do that on every Activity. So, you can create a BaseActivity and add that code there. Then, you just need to update your activities in order to extend BaseActivity
public class BaseActivity extends AppCompatActivity {
#Override
protected void attachBaseContext(final Context baseContext) {
....
}
}
Then, in your activities:
public class MainActivity extends BaseActivity {
// Since I'm extending BaseActivity, I don't need to add the code
// on attachBaseContext again
// If you don't want to create a base activity, you must copy/paste that
// attachBaseContext code into all activities
}
I tested this code with:
Log.v("Test", "Dimension: " + getResources().getDimension(R.dimen.test_dimension));
Different Screen Zoom (using that code):
2019-06-26 16:38:17.193 16312-16312/com.test.testapplication V/Test: Dimension: 105.0
2019-06-26 16:38:35.545 16312-16312/com.test.testapplication V/Test: Dimension: 105.0
2019-06-26 16:38:43.021 16579-16579/com.test.testapplication V/Test: Dimension: 105.0
Different Screen Zoom (without that code):
2019-06-26 16:42:53.807 17090-17090/com.test.testapplication V/Test: Dimension: 135.0
2019-06-26 16:43:19.381 17090-17090/com.test.testapplication V/Test: Dimension: 120.0
2019-06-26 16:44:00.125 17090-17090/com.test.testapplication V/Test: Dimension: 105.0
So, using that code, I can get the same dimension in pixels regardless of the zoom level.
Edit
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
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;
}
}