public class MainActivity extends AppCompatActivity {
private int brightness=255;
//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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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 (Settings.SettingNotFoundException e)
{
//Throw an error case it couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
//Get the current window attributes
WindowManager.LayoutParams layoutpars = window.getAttributes();
//Set the brightness of this window
layoutpars.screenBrightness = brightness / (float)100;
//Apply attribute changes to this window
window.setAttributes(layoutpars);
}
}
4条答案
按热度按时间db2dz4w81#
我的一个朋友发给我一个更好的,简单的代码来解决这个问题,他已经从互联网上找到
对于业余爱好者(比如我),你必须在“setContentView(R.layout.activity_main);“in“protected void onCreate(Bundle savedInstanceState){”method in yourMainActivity.java
顺便说一句,感谢@AbdulKawee的时间和支持,你给了我你的代码。真的很感激:)
0yycz8jy2#
你可以用这个
还有舱单里最重要的许可
在API 23中请求写入设置权限
8gsdolmq3#
Sankha Rathnayake的Kotlin版本的答案:
rsl1atfo4#
如果你只想在你的应用中使用它,那么每个应该是全亮度的Activity只需要在它的
onCreate()
中实现以下代码。每当您切换活动或切换回其他应用程序-亮度将再次由用户定义
使用Kotlin,你可能想使用
apply()
,只需要很少的代码: