2016-02-08 59 views
1

我正在嘗試使用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上顯示失敗。

+0

那麼,爲什麼你使用'Task.Run()'和'async' /'await'?另外,'settings.TrySetWallpaperImageAsync()'中的API應該是用於移動的? –

回答

0

正如我昨天所說的,我無法弄清楚爲什麼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。

+0

非常感謝。我不得不將文件名更改爲獨特的文件名,因爲您不能將背景更改爲具有相同名稱的文件,但除此之外它可以工作。 – Mrten

1

只需在ChangeBackground函數中使用await自然編寫代碼;沒有必要使用Task.Run然後得到它的Result(這是造成死鎖)。

+0

這是一個很好的資源:https://msdn.microsoft.com/en-us/magazine/jj991977.aspx –

+0

沒有它它也不起作用。該按鈕不會卡住,但壁紙不會改變。 – Mrten

+1

剛剛測試它,在移動它實際上堅持這個代碼'StorageFile文件=等待f.CopyAsync(ApplicationData.Current.LocalFolder,「background.jpg」,NameCollisionOption.ReplaceExisting);',不明白爲什麼在這裏。 –

相關問題