コメント
コメントの投稿
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。
namespace AppName.Services
{
public interface IDeviceService
{
void SetScreenBrightness(float value);
float GetScreenBrightness();
}
}
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
using System;
using Android.App;
using Android.Provider;
using Android.Views;
using Xamarin.Forms;
using AppName.Droid.Services;
using AppName.Services;
[assembly: Dependency(typeof(DeviceService))]
namespace AppName.Droid.Services
{
public class DeviceService : IDeviceService
{
/// <summary>
/// 画面の明るさを設定する
/// </summary>
/// <param name="value"></param>
public void SetScreenBrightness(float value)
{
//現在のアプリの画面の明るさを設定する
var activity = Forms.MainActivity; Window wm = activity.Window; WindowManagerLayoutParams param = wm.Attributes; param.ScreenBrightness = value; wm.Attributes = param;
}
/// <summary>
/// 画面の明るさを取得する
/// </summary>
/// <returns></returns>
public float GetScreenBrightness()
{
var activity = (Activity)Forms.Context;
//アプリの画面の明るさを取得する
var attributesWindow = new WindowManagerLayoutParams();
Window wm = activity.Window;
attributesWindow.CopyFrom(wm.Attributes);
if (attributesWindow.ScreenBrightness >= 0)
{
return attributesWindow.ScreenBrightness;
}
//OSの画面の明るさを取得する
string brightness = Settings.System.GetString(activity.ContentResolver, Settings.System.ScreenBrightness);
float ret = 0f;
if (!String.IsNullOrEmpty(brightness) &&
float.TryParse(brightness, out ret))
{
return ret / 255;
}
return ret;
}
}
}
using System;
using UIKit;
using Xamarin.Forms;
using AppName.iOS.Services;
using AppName.Services;
[assembly: Dependency(typeof(DeviceService))]
namespace AppName.iOS.Services
{
public class DeviceService : IDeviceService
{
/// <summary>
/// 画面の明るさを設定する
/// </summary>
/// <param name="value"></param>
public void SetScreenBrightness(float value)
{
UIScreen.MainScreen.Brightness = value;
}
/// <summary>
/// 画面の明るさを取得する
/// </summary>
/// <returns></returns>
public float GetScreenBrightness()
{
return (float)(UIScreen.MainScreen.Brightness);
}
}
}
using AppName.Services;
using Xamarin.Forms;
public class TestPage : ContentPage
{
private float _screenBrithness = 0f;
void SetScreenBrightness_Click(object sender, EventArgs e)
{
//画面の明るさを設定する(0~1の間で)
_screenBrithness = DependencyService.Get<IDeviceService>().GetScreenBrightness();
DependencyService.Get<IDeviceService>().SetScreenBrightness(0f);
}
void ClearScreenBrightness_Click(object sender, EventArgs e)
{
//画面の明るさを元に戻す
DependencyService.Get<IDeviceService>().SetScreenBrightness(_screenBrithness);
}
}
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。