之前到安卓8以後已經有一種寫法了,太煩瑣了,
好在最近又有update了
今天把它記錄下來,以免下次又要找到天窮碧落下黃泉之窘境了
------------------------------------------------------
using Xamarin.Essentials;
...
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
...
}
//-----以下整碗做你捧去,我也是copy改出來的-------
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults) {
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
public async Task<Xamarin.Essentials.PermissionStatus> CheckAndRequestPermissionAsync<T>(T permission)
where T : Xamarin.Essentials.Permissions.BasePermission {
var status = await permission.CheckStatusAsync();
if (status != Xamarin.Essentials.PermissionStatus.Granted) {
status = await permission.RequestAsync();
}
return status;
}
//以下以存檔權限為例,請自己改其他權限來用
public async Task ExportToExcelnAsync() {
var status = await CheckAndRequestPermissionAsync(new Xamarin.Essentials.Permissions.StorageWrite());
if (status != Xamarin.Essentials.PermissionStatus.Granted) {
// Notify user permission was denied
return;
}
await 你預訂得到權限後要做的事();
}
//-----Code海無邊,回頭是岸-----
--------------------------------
為什麼要寫出套件全名?因為很不巧一個叫「Plugin」的套件也有類似的權限套件
為了不被混淆,就全名標示了
本文技巧出處參考這裡
PS. 拜託安卓跟蘋果:你們可以不要再改了嗎?每次一版我就要重學,很累的耶,能不能像大話西遊一樣「如果非要在這些架構套件開發技術上加一個期限,我希望是……一萬年」啊