コメント
コメントの投稿
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。
namespace AppName.Services
{
public interface IDeviceService
{
//バッテリー残量を取得する
int GetBatteryLevel();
}
}
using System;
using Android.App;
using Android.Content;
using Android.OS;
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>
/// <returns>残量(%)</returns>
public int GetBatteryLevel()
{
IntentFilter ifilter = new IntentFilter(Intent.ActionBatteryChanged);
//Intent batteryStatus = Forms.Context.RegisterReceiver(null, ifilter);
Intent batteryStatus = Android.App.Application.RegisterReceiver(null, ifilter);
return batteryStatus.GetIntExtra(BatteryManager.ExtraLevel, -1);
}
}
}
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>
/// <returns>残量(%)</returns>
public int GetBatteryLevel()
{
// バッテリーのモニタリングをenableにする
UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;
float level = UIDevice.CurrentDevice.BatteryLevel;
if (level == -1)
{
//残量が取得できない場合
return -1;
}
else
{
//残量が取得できた場合
return Convert.ToInt32(level * 100);
}
}
}
}
using AppName.Services;
using Xamarin.Forms;
public class TestPage : ContentPage
{
/// <summary>
/// バッテリー残量を取得する
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
async void btnBatteryLevel_Click(object sender, EventArgs e)
{
int level = DependencyService.Get<IDeviceService>().GetBatteryLevel();
await DisplayAlert("バッテリー残量", "バッテリーの残量はあと" + level.ToString() + "%です。", AppResources.OK);
}
}
※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。
入力されていないコメントには返信しませんのであらかじめご了承くださいませ。