Change screen brightness with native Android features

Asked 2 years ago, Updated 2 years ago, 83 views

I have a question.

About native Android features in the manifest
uses-permission android:name="android.permission.WRITE_SETTINGS"Relationship does not work.(For example, changing or retrieving screen brightness, and not being able to change font size, etc.)
There are no specific errors, and there are other methods that simply retrieve strings from Android JavaClass.

//sample.java
public void changeAppBrightness(Context context, int brightness) {
  if (context != null) {
    Window window = ((Activity) context).getWindow();
    WindowManager.LayoutParams lp = window.getAttributes();
    if (brightness == -1) {
      lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
    } else {
      lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
    }
    window.setAttributes(lp);
  }
}
//sample.cs
private void hoge() {
  AndroidJavaClass unityPlayer=new AndroidJavaClass("com.unity3d.player.UnityPlayer"); 
  AndroidJavaObject context=unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  AndroidJavaClass screenMgr = new AndroidJavaClass ("hoge");
  screenMgr.Call("changeAppBrightness", context,100);
}

android unity3d

2022-09-30 21:31

2 Answers

Complete with Unity + Manifest

uses-permission android:name="android.permission.WRITE_SETTINGS"
Add

// sample.cs

private void SetBrightness(floatbrightness){
# if UNITY_ANDROID & !UNITY_EDITOR
        varunityPlayer=new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        varactivity=unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
        activity.Call("runOnUiThread", new AndroidJavaRunable()=>{
            var window=activity.Call<AndroidJavaObject>("getWindow");
            varlp=window.Call<AndroidJavaObject>("getAttributes");
            lp.Set ("screenBrightness", brightness.Value);
            window.Call("setAttributes",lp);

            intb=1+(int) (Math.Min(1, Math.Max(0, brightness.Value))*254f);//1<=b<=255
            var system=new AndroidJavaClass("android.provider.Settings.System");
            var contentResolver=activity.Call<AndroidJavaObject>("getContentResolver");
            system.CallStatic("putInt", contentResolver, system.CallStatic<string>("SCREEN_BRIGHTNESS_MODE"), 0);
            system.CallStatic("putInt", contentResolver, system.CallStatic<string>("SCREEN_BRIGHTNESS"), b);
        }));
#endif
}


2022-09-30 21:31


See here (https://qiita.com/GeneralD/items/5e77121cf0b26a103d38) I was able to complete it only with Unity and Manifest.


2022-09-30 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.