我尝试使用C#更改桌面和Windows移动设备的背景墙纸。一切都在桌面上运行,但在Windows Mobile中则不行。我只是有一个按钮,其中包含执行ChangeBackground的click事件:
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上显示失败。
答案 0 :(得分:1)
只需使用await
函数中的ChangeBackground
自然编写代码即可;没有必要使用Task.Run
然后获取它的Result
(导致死锁)。
答案 1 :(得分:0)
正如我昨天所说,我无法弄清楚为什么 <handlers>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler">
<property name="apiImplementationType" value="ENDPOINT"/>
</handler>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerCacheExtensionHandler"/>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.common.SynapsePropertiesHandler"/>
</handlers>
方法在移动设备上运行时会卡在你的第一个代码中。使用Http下载图片是正确的,但是在你的第二个代码中存在一些问题,它甚至无法在我的PC上工作。
很明显,您无法使用CopyAsync()
从uri获取数据。这是我的代码:
httpClient.SendAsync()
顺便说一下,我使用的是Windows.Web.Http API,而不是System.Net.Http API。