7

我是这个android开发领域的新手。这些天我正在开发一个应用程序,我想在打开应用程序后将屏幕亮度设置为最大级别,并在我退出应用程序后将其设置回之前的级别。有人可以为此提供完整的源代码吗?关于这个问题,我几乎阅读了 stackoverflow 中的每个线程。而且我不明白将这些建议的代码放在哪里。但是如果你能想出完整的代码,那么我就能理解一切。谢谢!

4

3 回答 3

10

我的一个朋友给我发了一个更好、更简单的代码来解决他从互联网上找到的这个问题

对于业余爱好者(如我),您必须在“setContentView(R.layout.activity_main);”之后输入以下代码 在 MainActivity.java 中的“protected void onCreate(Bundle savedInstanceState) {”方法中

    WindowManager.LayoutParams layout = getWindow().getAttributes();
    layout.screenBrightness = 1F;
    getWindow().setAttributes(layout);

顺便说一句,感谢@AbdulKawee 您的时间以及您为我提供代码的支持。真的很感激:)

于 2017-04-27T06:55:44.973 回答
5

你可以用这个

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;
}
于 2017-04-26T17:19:12.830 回答
2

Sankha Rathnayake 回答的 Kotlin 版本:

val attributes = window.attributes
attributes.screenBrightness = 1f
window.attributes = attributes
于 2021-05-30T21:30:45.110 回答