我正在嘗試使用C#更改桌面和Windows移動版的背景牆紙。一切工作在桌面上,但不在Windows Mobile中。我只是有一個點擊事件執行ChangeBackground的按鈕:Windows UWP C#代碼在桌面上運行,而不是在手機上
private async void ChangeBackgroundButton_Click(object sender, RoutedEventArgs e)
{
await ChangeBackground();
updateTask();
}
private static async Task ChangeBackground()
{
if (UserProfilePersonalizationSettings.IsSupported())
{
StorageFile file = Task.Run(async() => {
Uri uri = new Uri("https://source.unsplash.com/random/1080x1920");
StorageFile f = await StorageFile.CreateStreamedFileFromUriAsync("background.jpg", uri, RandomAccessStreamReference.CreateFromUri(uri));
return await f.CopyAsync(ApplicationData.Current.LocalFolder, "background.jpg", NameCollisionOption.ReplaceExisting);
}).Result;
UserProfilePersonalizationSettings settings = UserProfilePersonalizationSettings.Current;
await settings.TrySetWallpaperImageAsync(file);
}
}
當我按下Windows Mobile上的按鈕,應用程序卡住了。該按鈕處於懸停狀態,牆紙不會更改。
我在做什麼錯?
編輯:我重寫了代碼以解決CopyAsync的問題。代碼如下所示:
private static async Task<StorageFile> ChangeBackground()
{
if (UserProfilePersonalizationSettings.IsSupported())
{
Uri uri = new Uri("https://source.unsplash.com/random/1920x1080");
string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await fs.FlushAsync();
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
UserProfilePersonalizationSettings settings = UserProfilePersonalizationSettings.Current;
if (!await settings.TrySetWallpaperImageAsync(file))
{
Debug.WriteLine("Failed");
} else
{
Debug.WriteLine("Success");
}
return file;
}
return null;
}
在Windows 10上它顯示成功,在Windows 10 Mobile上顯示失敗。
那麼,爲什麼你使用'Task.Run()'和'async' /'await'?另外,'settings.TrySetWallpaperImageAsync()'中的API應該是用於移動的? –