Change main Android screen orientation? - java

I have had a device, which apparently had something broken with the orientation, because after reboot, for about an hour, it would rotate the screen in response to a change of orientation - and then it would stop responding, both on the "desktop" level and application level.
So, I found Change Screen Orientation programmatically using a Button, and I assumed I can create a "icon button only" app, which when pressed, would not run a new application, but instead just try to change the orientation.
The skeleton for the "icon/button-only" app is a copy of Lock screen (it.reyboz.screenlock). I posted this project on a gist - but since it is hard to have folders (and binary files) by default in a gist, this is the procedure you can use to get the code:
git clone https://gist.github.com/e6422677cababc17526d0cb57aceb76a.git dl_archive_git
cd dl_archive_git
bash run-me-to-unpack.sh
# check upacked dir:
tree rotate-btn-droid
cd rotate-btn-droid/
# change your SDK path (ASDKPATH) in buildme.sh, and then:
bash buildme.sh
# if your java install is not in the path, then call the last command with JAVA_HOME prepended:
# JAVA_HOME=/path/to/jdkXXX bash buildme.sh
Basically, I'm just trying to do the following in MainActivity.java:
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
// OR: orientation = getRequestedOrientation(); // inside an Activity
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation (Build.VERSION.SDK_INT < 9 ?
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE :
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation (Build.VERSION.SDK_INT < 9 ?
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT :
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
break;
}
... however, nothing happens when I click the app icon and run this code.
So, my question is - is it possible in principle to force a change of the device orientation on a "desktop" level? If so, is it dependent on Android version (possibly vendor branded) or not - and how?

Was just curious so tried out Sam's solution and made some changes :
Would need this permission in Manifest
Permission <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Also this permissions is a dangerous permission but if you are installing the app from Play store you need not worry about that.
I made a window service something like this :
public class MyServiceNew extends Service {
private View view;
public MyServiceNew() {
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int flag = intent.getExtras().getInt("Flag");
WindowManager.LayoutParams layout;
if (flag == 1) {
layout = generateLayoutLandscape();
} else {
layout = generateLayoutPortrait();
}
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(view, layout);
return super.onStartCommand(intent, flags, startId);
}
private WindowManager.LayoutParams generateLayoutPortrait() {
Toast.makeText(this, "Port", Toast.LENGTH_LONG).show();
view = new View(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSPARENT);
params.alpha = 0f;
params.width = 0;
params.height = 0;
//The orientation to force
params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
return params;
}
private WindowManager.LayoutParams generateLayoutLandscape() {
Toast.makeText(this, "Land", Toast.LENGTH_LONG).show();
view = new View(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSPARENT);
params.alpha = 0f;
params.width = 0;
params.height = 0;
//The orientation to force
params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
return params;
}
}
And from your Activity while development make sure you include ACTION_MANAGE_OVERLAY_PERMISSION ; again you don't need to worry this for users who will install the app through Google Play Store. Here using the below code to allow permission for devices above M :
public void requestSystemAlertPermission(int requestCode) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
return;
final String packageName = getPackageName();
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + packageName));
startActivityForResult(intent, requestCode);
}
And now just start your service and pass extras for Portrait or Landscape
I am using 1 for Landscape and 2 for Portrait
Intent intentLand = new Intent(SoNew.this, MyServiceNew.class);
intentLand.putExtra("Flag", 2); //or change 1 for Port
startService(intentLand);
Hope this helps :)

Related

How To Display A Floating Icon In Home Screen

I am building a lock screen app. I want to place a floating icon on Homescreen, which when clicked will lock the phone. I was able to implement the functionality of Locking the Phone using Device Manager API. Now I want to add a Floating Icon on Homescreen.
I tried using the solution recommended here:
What APIs are used to draw over other apps (like Facebook's Chat Heads)?
But this does not seem to be working in my case. It is not diplaying an icon on the homescreen ever after gaining SYSTEM OVERLAY Permission.
LockButtonService.java
public class LockButtonService extends Service {
private WindowManager windowManager;
private ImageView chatHead;
#Override public IBinder onBind(Intent intent) {
// Not used
return null;
}
#Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.lock);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatHead != null) windowManager.removeView(chatHead);
}
}
MainActivity.java
add_homescreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Code For Adding Shortcut Icon On Home Screen
// if (ShortcutManagerCompat.isRequestPinShortcutSupported(getApplicationContext())) {
// ShortcutInfoCompat shortcutInfo = new ShortcutInfoCompat.Builder(getApplicationContext(), "#1")
// .setIntent(new Intent(getApplicationContext(), LockActivity.class).setAction(Intent.ACTION_MAIN)) // !!! intent's action must be set on oreo
// .setShortLabel("Lock Screen")
// .setIcon(IconCompat.createWithResource(getApplicationContext(), R.drawable.lock))
// .build();
// ShortcutManagerCompat.requestPinShortcut(getApplicationContext(), shortcutInfo, null);
// } else {
// Toast.makeText(MainActivity.this,"launcher does not support short cut icon",Toast.LENGTH_LONG).show();
// }
//Code For Requesting System Overlay
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(getApplicationContext())) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 12345);
}
else {
//Code To Execute If The Permission Is Granted
Toast.makeText(getApplicationContext(),"Permission Granted",Toast.LENGTH_LONG);
startService(new Intent(getApplicationContext(), LockButtonService.class));
}
}
}
I figured out the issue. It seems like I forgot to declare this service in Android Manifest. I was using WindowManager.LayoutParams.TYPE_PHONE in LockButtonService.java.
I have now changed it into WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, and my icon is displaying on homescreen and all other activities.

How to detect touch events outside the view in background service?

I was trying to detect touch events in background service so that I can get all the touch events when user is using any apps.
What's I've done is using WindowManager to add a small view and when running the app in the background, this small view can still be on the screen. I also set the view as an onTouchListener so when user touch inside the view, I can get the touch event.
My problem is that is there any way to detect touch events outside this small view.
Here is my code.
public class GlobalTouchService extends Service implements View.OnTouchListener {
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutParams;
private MyView myView;
private boolean flag = true;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mWindowManager = (WindowManager)getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mLayoutParams.format = PixelFormat.TRANSLUCENT;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.x = 0;
mLayoutParams.y = 0;
mLayoutParams.height = 300;
mLayoutParams.width = 300;
myView = new MyView(this);
myView.setOnTouchListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (flag) {
flag = false;
mWindowManager.addView(myView, mLayoutParams);
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getRawX();
float y = motionEvent.getRawY();
Log.d("x,y", "X" + x + " Y" + y);
return false;
}
You can't. Android explicitly does not allow you to get touch events when you aren't the foreground app for security reasons. What you're trying to do is explicitly against what the OS wants, and if you find a way Google will plug the hole as quick as you find it. The only way to do this is on a rooted device, which means it won't work over the play store (and the way to do it there is by reading touch data from the linux device layer).

Creating an Activity as instance?

I have created an pop up window that I can use to show important messages in my app. The code for this are written in PopActivity.
Here is my code:
public class PopActivity extends Activity {
private WorkOutClass the_workout_class = new WorkOutClass();
private TextView repTextField, setsTextField;
private Button den_knappen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop);
repTextField = (TextView) findViewById(R.id.repetitionID);
setsTextField = (TextView) findViewById(R.id.setsID);
den_knappen = (Button) findViewById(R.id.buttonID);
repTextField.setText("Reps : " + String.valueOf(the_workout_class.getReps()));
setsTextField.setText("Sets: " +String.valueOf(the_workout_class.getSets()));
DisplayMetrics thePopUpWindow = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(thePopUpWindow);
int width = thePopUpWindow.widthPixels;
int height = thePopUpWindow.heightPixels;
getWindow().setLayout((int)(width*.8), (int)(height*.7));
WindowManager.LayoutParams params = getWindow().getAttributes();
params.gravity = Gravity.CENTER;
params.x = 0;
params.y = 20;
getWindow().setAttributes(params);
den_knappen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
the_workout_class.increaseReps();
repTextField.setText("Reps : " + String.valueOf(the_workout_class.getReps()));
setsTextField.setText("Sets: " +String.valueOf(the_workout_class.getSets()));
}
});
}}
My question is though: If i want to use the same type of pop-up window somewhere else in my app which provide a different message, is there a way I can just copy this to use it? Or do I need to create new file such as PopActivity2, PopActivity3 etc etc.?
Thanks for answer.
Sounds to me that what you really need is a Dialog. You can create your own layout and texts for a dialog, and then use it where ever you need it. These links can help you with that:
https://developer.android.com/guide/topics/ui/dialogs
How do I display an alert dialog on Android?
How to set dialog to show in full screen?
You can pass your data via Intent when you start your Activity like
// in previous activity
Intent intent = new Intent(this, PopActivity.class);
intent.putExtra("first", "your message")
startActivity(intent);
// in PopActivity
String message = getIntent().getStringExtra("first")
and use this as the message your need. You can pass more data if you want. Best would be to define a constant for the name ("first") with a better name and use this on both Activities ;-)

android 4.2 how to adjust the screen brightness

I have an android device, it can only run a app (like ATM screen). Now I want to implement the following feature:
If the device is not in use for over 30 minutes, I will adjust the screen brightness to the lowest. At this time, if I touch the screen, I should adjust the screen brightness to the maximum. The user can not see any Android system menu, application, etc. They only can use this app (can't close it). This app will run in this device from the power on it and power off it.
I don't how to implement this feature.
Thanks.
You can use a class that extends service and can dim the screen brightness. Use AlarmManager to check the time that the user never touches the screen. I will give you an example of using the Service class:
public class DimScreen extends Service {
public static int ID_NOTIFICATION = 2018;
private WindowManager windowManager;
private LinearLayout saverScreen;
private PopupWindow pwindo;
boolean mHasDoubleClicked = false;
long lastPressTime;
private Boolean _enable = true;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
saverScreen = new LinearLayout(this);
saverScreen.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
Bitmap sample = Bitmap.createBitmap(100, 100, Config.ARGB_8888);
saverScreen.setBackground(new BitmapDrawable(this.getResources(),
convertColorIntoBlackAndWhiteImage(sample)));
saverScreen.setClickable(false);
saverScreen.setFocusable(false);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.FILL_PARENT,
WindowManager.LayoutParams.FILL_PARENT,
PixelFormat.TRANSLUCENT);
params.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN
|WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
|WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
|WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
|WindowManager.LayoutParams.FLAG_DIM_BEHIND;
params.dimAmount = (float) 0.6;
params.screenBrightness = (float) 0.3;
params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
windowManager.addView(saverScreen, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if (saverScreen != null) windowManager.removeView(saverScreen);
}
private Bitmap convertColorIntoBlackAndWhiteImage(Bitmap orginalBitmap) {
ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(2);
ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
colorMatrix);
Bitmap blackAndWhiteBitmap = orginalBitmap.copy(
Bitmap.Config.ARGB_8888, true);
Paint paint = new Paint();
paint.setColorFilter(colorMatrixFilter);
Canvas canvas = new Canvas(blackAndWhiteBitmap);
canvas.drawBitmap(blackAndWhiteBitmap, 0, 0, paint);
return blackAndWhiteBitmap;
}
}
In your Activity class call
startService(new Intent(this,DimScreen.class));
You only have to implement the AlarmManager now. If the user never touches the screen, launch the Service class. If the user Interrupt with the app, then call stopService.
Try this
WindowManager.LayoutParams localLayoutParams = getWindow()
.getAttributes();
localLayoutParams.screenBrightness = 0.12F;
getWindow().setAttributes(localLayoutParams);

Change the System Brightness Programmatically

I want to change the system brightness programmatically. For that purpose I am using this code:
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);
because I heard that max value is 255.
but it does nothing. Please suggest any thing that can change the brightness.
Thanks
You can use following:
// Variable to store brightness value
private int brightness;
// Content resolver used as a handle to the system's settings
private ContentResolver cResolver;
// Window object, that will store a reference to the current window
private Window window;
In your onCreate write:
// Get the content resolver
cResolver = getContentResolver();
// Get the current window
window = getWindow();
try {
// To handle the auto
Settings.System.putInt(
cResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL
);
// Get the current system brightness
brightness = Settings.System.getInt(
cResolver, Settings.System.SCREEN_BRIGHTNESS
);
} catch (SettingNotFoundException e) {
// Throw an error case it couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
Write the code to monitor the change in brightness.
then you can set the updated brightness as follows:
// Set the system brightness using the brightness variable value
Settings.System.putInt(
cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness
);
// Get the current window attributes
LayoutParams layoutpars = window.getAttributes();
// Set the brightness of this window
layoutpars.screenBrightness = brightness / 255f;
// Apply attribute changes to this window
window.setAttributes(layoutpars);
Permission in manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
For API >= 23, you need to request the permission through Settings Activity, described here:
Can't get WRITE_SETTINGS permission
You can set the screenBrightness attribute of the window, like so:
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
This code/technique is adapted from a blog entry by Almond Joseph Mendoza on January 5, 2009, entitled "Changing the Screen Brightness Programatically" (archived on the Wayback Machine).
The screenBrightness attribute is a floating-point value ranging from 0 to 1, where 0.0 is 0% brightness, 0.5 is 50% brightness, and 1.0 is 100% brightness.
Note that this doesn't affect the brightness for the entire system, only for that particular window. However, in most cases, for most applications, this is probably all you need. In particular, it has the advantage of not requiring elevated permissions, which would be required to change a global system setting.
I had the same problem.
Two solutions:
here, brightness =(int) 0 to 100 range as i am using progressbar
1 SOLUTION
float brightness = brightness / (float)255;
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);
2 SOLUTION
I just used dummy activity to call when my progress bar stop seeking.
Intent intent = new Intent(getBaseContext(), DummyBrightnessActivity.class);
Log.d("brightend", String.valueOf(brightness / (float)255));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this is important
//in the next line 'brightness' should be a float number between 0.0 and 1.0
intent.putExtra("brightness value", brightness / (float)255);
getApplication().startActivity(intent);
Now coming to the DummyBrightnessActivity.class
public class DummyBrightnessActivity extends Activity{
private static final int DELAYED_MESSAGE = 1;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(msg.what == DELAYED_MESSAGE) {
DummyBrightnessActivity.this.finish();
}
super.handleMessage(msg);
}
};
Intent brightnessIntent = this.getIntent();
float brightness = brightnessIntent.getFloatExtra("brightness value", 0);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = brightness;
getWindow().setAttributes(lp);
Message message = handler.obtainMessage(DELAYED_MESSAGE);
//this next line is very important, you need to finish your activity with slight delay
handler.sendMessageDelayed(message,200);
}
}
don't forget to register DummyBrightnessActivity to manifest.
hope it helps!!
In my case, I only want to light up the screen when I display a Fragment and not change the system wide settings. There is a way to only change the brightness for your Application/Activity/Fragment. I use a LifecycleObserver to adjust the screen brightness for one Fragment:
class ScreenBrightnessLifecycleObserver(private val activity: WeakReference<Activity?>) :
LifecycleObserver {
private var defaultScreenBrightness = 0.5f
init {
activity.get()?.let {
defaultScreenBrightness = it.window.attributes.screenBrightness
}
}
#OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun lightUp() {
adjustScreenBrightness(1f)
}
#OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun lightDown() {
adjustScreenBrightness(defaultScreenBrightness)
}
private fun adjustScreenBrightness(brightness: Float) {
activity.get()?.let {
val attr = it.window.attributes
attr.screenBrightness = brightness
it.window.attributes = attr
}
}
}
And add the LifecycleObserver such as this in your Fragment:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// ...
lifecycle.addObserver(ScreenBrightnessLifecycleObserver(WeakReference(activity)))
// ...
return binding.root
}
I tried several solutions that others posted and none of them worked exactly right. The answer from geet is basically correct but has some syntactic errors. I created and used the following function in my application and it worked great. Note this specifically changes the system brightness as asked in the original question.
public void setBrightness(int brightness){
//constrain the value of brightness
if(brightness < 0)
brightness = 0;
else if(brightness > 255)
brightness = 255;
ContentResolver cResolver = this.getApplicationContext().getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
}
Complete Answer
I did not wanted to use Window Manager to set brightness. I wanted the brighness to reflect on System level as well as on UI. None of the above answer worked for me. Finally this approach worked for me.
Add Write setting permission in Android Manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
Write Settings is a Protected settings so request user to allow Writing System settings:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}
}
Now you can set Brightness easily
ContentResolver cResolver = getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
brighness value should be in range of 0-255 so if you have aslider with range (0-max) than you can normalize the value in range of (0-255)
private float normalize(float x, float inMin, float inMax, float outMin, float outMax) {
float outRange = outMax - outMin;
float inRange = inMax - inMin;
return (x - inMin) *outRange / inRange + outMin;
}
Finally you can now change Brightness in of 0-100% from 0-255 range like this:
float brightness = normalize(progress, 0, 100, 0.0f, 255.0f);
Hope it will save your time.
this worked for me till kitkat 4.4 but not in android L
private void stopBrightness() {
Settings.System.putInt(this.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS, 0);
}
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 10; // range from 0 - 255 as per docs
getWindow().setAttributes(params);
getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
This worked for me. No need of a dummy activity. This works only for your current activity.
This is the complete code on how to change system brightness
private SeekBar brightbar;
//Variable to store brightness value
private int brightness;
//Content resolver used as a handle to the system's settings
private ContentResolver Conresolver;
//Window object, that will store a reference to the current window
private Window window;
/** Called when the activity is first created. */
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Instantiate seekbar object
brightbar = (SeekBar) findViewById(R.id.ChangeBright);
//Get the content resolver
Conresolver = getContentResolver();
//Get the current window
window = getWindow();
brightbar.setMax(255);
brightbar.setKeyProgressIncrement(1);
try {
brightness = System.getInt(Conresolver, System.SCREEN_BRIGHTNESS);
} catch (SettingNotFoundException e) {
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
brightbar.setProgress(brightness);
brightbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
System.putInt(Conresolver, System.SCREEN_BRIGHTNESS, brightness);
LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = brightness / (float) 255;
window.setAttributes(layoutpars);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress <= 20) {
brightness = 20;
} else {
brightness = progress;
}
}
});
}
Or you may check this tutorial for complete code
happy coding:)
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
progress);
private SeekBar Brighness = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lcd_screen_setting);
initUI();
setBrightness();
}
private void setBrightness() {
Brighness.setMax(255);
float curBrightnessValue = 0;
try {
curBrightnessValue = android.provider.Settings.System.getInt(
getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
int screen_brightness = (int) curBrightnessValue;
Brighness.setProgress(screen_brightness);
Brighness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress = 0;
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
progress = progresValue;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Do something here,
// if you want to do anything at the start of
// touching the seekbar
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
progress);
}
});
}
initUI(){
Brighness = (SeekBar) findViewById(R.id.brightnessbar);
}
Add this in manifest
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions"/>
Please Try this , it's May help you. Worked fine for me
According to my experience
1st method.
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 75 / 100.0f;
getWindow().setAttributes(lp);
where the brightness value very according to 1.0f.100f is maximum brightness.
The above mentioned code will increase the brightness of the current window. If we want to increase the brightness of the entire android device this code is not enough, for that we need to use
2nd method.
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, 192);
Where 192 is the brightness value which very from 1 to 255. The main problem of using 2nd method is it will show the brightness in increased form in android device but actually it will fail to increase android device brightness.This is because it need some refreshing.
That is why I find out the solution by using both codes together.
if(arg2==1)
{
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 75 / 100.0f;
getWindow().setAttributes(lp);
android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS, 192);
}
It worked properly for me
You need to create the variable:
private WindowManager.LayoutParams mParams;
then override this method (to save your previous params):
#Override
public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
mParams = params;
super.onWindowAttributesChanged(params);
}
than where you wish to change the screen brightness (on the app) just use:
mParams.screenBrightness = 0.01f; //use a value between 0.01f for low brightness and 1f for high brightness
getWindow().setAttributes(mParams);
tested on api version 28.
Was just looking into this for Android 10 and this still works for me on there. But requires getting the calling Activity instance inside the fragment which is less than optimal since we only get the context from onAttach now. Setting it to -1.0f sets it to the system value (the one from brightness settings slider), 0.0f to 1.0f sets brightness values from min to max at your leisure.
WindowManager.LayoutParams lp = myactivity.getWindow().getAttributes();
lp.screenBrightness = brightness;
myactivity.getWindow().setAttributes(lp);
myactivity.getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
I'm using this utils class works for Android 9
public class BrightnessUtil {
public static final int BRIGHTNESS_DEFAULT = 190;
public static final int BRIGHTNESS_MAX = 225;
public static final int BRIGHTNESS_MIN = 0;
public static boolean checkForSettingsPermission(Activity activity) {
if (isNotAllowedWriteSettings(activity)) {
startActivityToAllowWriteSettings(activity);
return false;
}
return true;
}
public static void stopAutoBrightness(Activity activity) {
if (!isNotAllowedWriteSettings(activity)) {
Settings.System.putInt(activity.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
public static void setBrightness(Activity activity, int brightness) {
if (!isNotAllowedWriteSettings(activity)) {
//constrain the value of brightness
if (brightness < BRIGHTNESS_MIN)
brightness = BRIGHTNESS_MIN;
else if (brightness > BRIGHTNESS_MAX)
brightness = BRIGHTNESS_MAX;
ContentResolver cResolver = activity.getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
}
}
private static void startActivityToAllowWriteSettings(Activity activity) {
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
#SuppressLint("ObsoleteSdkInt")
private static boolean isNotAllowedWriteSettings(Activity activity) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(activity);
}
}
There you go, short and sweet; Kotlin version.
/**
* This can be used to override the user's preferred brightness of the screen.
* A value of less than 0, the default, means to use the preferred screen brightness.
* 0 to 1 adjusts the brightness from dark to full bright!
*/
fun Fragment.screenBrightness(x: Float) = activity?.screenBrightness(x)
fun Activity.screenBrightness(x: Float) = window?.apply {
attributes = attributes?.apply { screenBrightness = x.coerceIn(-1f..1f) } }
Kdoc'd also!

Categories