Windows UWP C# 代码适用于桌面,不适用于移动设备
Windows UWP C# code works on desktop, not on mobile
我正在尝试使用 C# 更改桌面和 Windows 移动设备的背景墙纸。在桌面上一切正常,但在 Windows 移动设备上却不行。我只有一个带有执行 ChangeBackground 的单击事件的按钮:
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 移动设备上按下按钮时,应用程序卡住了。按钮保持悬停状态,壁纸不变。
我做错了什么?
编辑:我重写了代码以修复 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 上显示失败。
只需在 ChangeBackground
函数中使用 await
自然地编写您的代码;没有必要使用 Task.Run
然后获取它的 Result
(这会导致死锁)。
正如我昨天所说,我无法弄清楚为什么 CopyAsync()
方法在移动设备上 运行 时会卡在您的第一个代码中。使用Http下载图片是对的,但是你的第二段代码有问题,我这边的pc上也不能用
很明显您不能使用 httpClient.SendAsync()
从 uri 获取数据。这是我的代码:
private static async Task ChangeBackground()
{
if (UserProfilePersonalizationSettings.IsSupported())
{
Uri uri = new Uri("https://source.unsplash.com/random/1920x1080");
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(uri);
if (response != null && response.StatusCode == HttpStatusCode.Ok)
{
string filename = "background.jpg";
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream stream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await response.Content.WriteToStreamAsync(stream);
}
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
UserProfilePersonalizationSettings settings = UserProfilePersonalizationSettings.Current;
if (!await settings.TrySetWallpaperImageAsync(file))
{
Debug.WriteLine("Failed");
}
else
{
Debug.WriteLine("Success");
}
}
}
catch
{
}
}
}
}
顺便说一下,我使用的是 Windows.Web.Http API,而不是 System.Net.Http API。
我正在尝试使用 C# 更改桌面和 Windows 移动设备的背景墙纸。在桌面上一切正常,但在 Windows 移动设备上却不行。我只有一个带有执行 ChangeBackground 的单击事件的按钮:
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 移动设备上按下按钮时,应用程序卡住了。按钮保持悬停状态,壁纸不变。
我做错了什么?
编辑:我重写了代码以修复 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 上显示失败。
只需在 ChangeBackground
函数中使用 await
自然地编写您的代码;没有必要使用 Task.Run
然后获取它的 Result
(这会导致死锁)。
正如我昨天所说,我无法弄清楚为什么 CopyAsync()
方法在移动设备上 运行 时会卡在您的第一个代码中。使用Http下载图片是对的,但是你的第二段代码有问题,我这边的pc上也不能用
很明显您不能使用 httpClient.SendAsync()
从 uri 获取数据。这是我的代码:
private static async Task ChangeBackground()
{
if (UserProfilePersonalizationSettings.IsSupported())
{
Uri uri = new Uri("https://source.unsplash.com/random/1920x1080");
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(uri);
if (response != null && response.StatusCode == HttpStatusCode.Ok)
{
string filename = "background.jpg";
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream stream = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await response.Content.WriteToStreamAsync(stream);
}
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
UserProfilePersonalizationSettings settings = UserProfilePersonalizationSettings.Current;
if (!await settings.TrySetWallpaperImageAsync(file))
{
Debug.WriteLine("Failed");
}
else
{
Debug.WriteLine("Success");
}
}
}
catch
{
}
}
}
}
顺便说一下,我使用的是 Windows.Web.Http API,而不是 System.Net.Http API。