我是这个Android开发领域的新手。这些天我正在开发一个应用程序,我想在打开应用程序后将屏幕亮度设置为最高级别,并在退出应用程序后将其设置回上一级别。有人能想出完整的源代码吗?我读了几乎关于这个问题的stackoverflow中的每个线程。我无法理解在哪里提出这些建议的代码。但如果你能提出完整的代码,那么我就能理解一切。谢谢!
答案 0 :(得分:3)
您可以使用此
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);
}
}
清单中最重要的许可
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
在API 23中要求写入设置权限
private boolean checkSystemWritePermission() {
boolean retVal = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
retVal = Settings.System.canWrite(this);
Log.d(TAG, "Can Write Settings: " + retVal);
if(retVal){
Toast.makeText(this, "Write allowed :-)", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this, "Write not allowed :-(", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + getActivity().getPackageName()));
startActivity(intent);
}
}
return retVal;
}
答案 1 :(得分:2)
我的一位朋友发给我一个更好,更简单的代码来解决他从互联网上找到的这个问题
对于业余爱好者(像我一样),你必须在“setContentView(R.layout.activity_main);”之后输入以下代码。在“MainActivity.java中的protected void onCreate(Bundle savedInstanceState){”方法中
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
顺便说一下,谢谢你@AbdulKawee的时间和你给我的代码支持。非常感谢:)
答案 2 :(得分:0)
Sankha Rathnayake 的回答的 Kotlin 版本:
unsigned int