简体   繁体   中英

Windows UWP C# code works on desktop, not on mobile

I'm trying to change the background wallpaper of a desktop and Windows mobile with C#. Everything works on a desktop, but not in Windows Mobile. I simply have a button with a click event that executes 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);
    }
}

When I press the button on Windows Mobile, the app gets stuck. The button stays in a hovered state, and the wallpaper doesn't change.

What am I doing wrong?

Edit: I rewrote the code to fix problems with CopyAsync. The code looks like this now:

    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;
    }

On Windows 10 it shows success, on Windows 10 Mobile it shows failed.

Just write your code naturally using await in the ChangeBackground function; there is no need to use Task.Run and then get the Result of it (which is causing a deadlock).

As I said yesterday, I can't figure out why CopyAsync() method get stuck in your first code when it is run on mobile. It is right to use Http to download the picture, but there is some problems in your second code, it can't work even on PC by my side.

It's clear you can't use httpClient.SendAsync() to get data form uri. Here is my code:

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
            {
            }
        }
    }
}

By the way, I'm using Windows.Web.Http API, not System.Net.Http API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM