需求:在 A 應用內啟動 B 應用,如果 B 應用未安裝則跳轉應用商店搜索。
啟動方式使用 Uri 啟動,本文使用盡可能簡單,并且能拿來直接用的代碼。不涉及啟動后的應用數據交互,如需深入了解,請戳 MSDN:https://docs.microsoft.com/zh-cn/windows/uwp/launch-resume/launch-app-with-uri
1. 獲取 B 應用 Uri 以及 B 應用激活事件
如果 B 應用已注冊 Uri 的話,那很好,記住它備用,可以跳過看第2點了。如果沒有,接著看下面。
那么如何為 B 應用注冊 Uri 呢?
打開 B 應用程序清單 Package.appxmanifest ,在“聲明”選卡項中添加一個新的“協議”聲明(如果你做過后臺任務的話那一定很熟悉)。在“名稱”(name)那一欄中填寫你需要注冊的 Uri (隨便編)。填寫完成后保存,這樣就完成了 Uri 的注冊。
Uri 啟動應用是以激活的形式啟動的應用,和磁貼與Toast通知的激活啟動一樣,需要在 App.xaml.cs 文件里重寫 OnActivated() 事件。Uri 激活時會賦一個 ID,在 OnActivated() 事件中可以進行一些處理,比如跳轉其他不同頁面,下面的代碼是像 OnLaunched() 事件一樣直接跳轉到 MainPage.xaml。
protected override void OnActivated(IActivatedEventArgs args) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Window.Current.Content = rootFrame; } rootFrame.Navigate(typeof(MainPage)); Window.Current.Activate(); }
2. A 應用啟動 B 應用
知道了 B 應用的 Uri 后,下面就要在 A 應用中啟動 B 應用了。和 MSDN 的“推薦設置”方法不同,這里采用的是先判斷 B 應用在設備上存不存在,如果存在直接啟動,不存在啟動商店搜索。下面直接給出代碼,注意把 Uri 換成相應的 Uri 即可。 Uri 內的 ProductID 是一定要寫的,不然會報錯。
var result = await Windows.System.Launcher.QueryUriSupportAsync(new Uri("link.qtz:?ProductId=1"), Windows.System.LaunchQuerySupportType.Uri); if (result == LaunchQuerySupportStatus.Available) { await Windows.System.Launcher.LaunchUriAsync(new Uri("link.qtz:?ProductId=1")); } else { await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-windows-store://pdp/?productid=9nblggh4t3t0")); }
文章列表