Sha*_*ank 1 android screen-brightness android-6.0-marshmallow
我正在开发一个以编程方式更改屏幕亮度的Android应用程序.我有一个适用于5.1.1的设置亮度方法,但是当我在6.0上运行应用程序时,它会出错并关闭应用程序.请帮忙.
以下是我的方法:
public void setBrightness(View view,int brightness){
//Just a loop for checking whether the brightness changes
if(brightness <46)
brightness = 255;
else if(brightness >150)
brightness=45;
ContentResolver cResolver = this.getApplicationContext().getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
}
public void setDisplay(View view)
{
ContentResolver cResolver = getContentResolver();
Window window = getWindow();
int brightness=0;
try
{ 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);
}
catch (Exception e)
{
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
setBrightness(view,brightness);
}
Run Code Online (Sandbox Code Playgroud)
小智 8
显然,您需要明确要求用户在运行Android 6.0+的设备上获得许可.
请尝试以下代码:(我已经为您修改过)
@TargetApi(Build.VERSION_CODES.M)
public void setBrightness(View view,int brightness){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(getApplicationContext()))
{
if (brightness < 46)
brightness = 255;
else if (brightness > 47)
brightness = 0;
ContentResolver cResolver = this.getApplicationContext().getContentResolver();
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
} else
{
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您还需要清单中的WRITE_SETTINGS权限.
小智 6
如果要指定活动/片段,请尝试以下操作:
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 70 / 100.0f;
getWindow().setAttributes(lp);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5460 次 |
| 最近记录: |