Xamarin.Essentials:启动器Xamarin.Essentials: Launcher

Launcher 类允许应用程序打开系统的 URI。The Launcher class enables an application to open a URI by the system. 通常在深入链接到另一个应用程序的自定义 URI 方案后使用此类。This is often used when deep linking into another application's custom URI schemes. 如果想要将浏览器打开到某个网站,则应引用浏览器 API。If you are looking to open the browser to a website then you should refer to the Browser API.

入门Get started

若要开始使用此 API,请阅读 Xamarin.Essentials 的入门指南以确保在项目中正确安装和设置库。To start using this API, read the getting started guide for Xamarin.Essentials to ensure the library is properly installed and set up in your projects.

使用 LauncherUsing Launcher

在你的类中添加对 Xamarin.Essentials 的引用:Add a reference to Xamarin.Essentials in your class:

using Xamarin.Essentials;

若要使用 Launcher 功能,请调用 OpenAsync 方法并传入要打开的 stringUriTo use the Launcher functionality call the OpenAsync method and pass in a string or Uri to open. (可选)CanOpenAsync 方法可用于检查是否可以由设备上的应用程序处理 URI 架构。Optionally, the CanOpenAsync method can be used to check if the URI schema can be handled by an application on the device.

public class LauncherTest
{
    public async Task OpenRideShareAsync()
    {
        var supportsUri = await Launcher.CanOpenAsync("lyft://");
        if (supportsUri)
            await Launcher.OpenAsync("lyft://ridetype?id=lyft_line");
    }
}

可以用 TryOpenAsync 将此合并为单个调用,此语法将检查是否可以打开该参数,如果可以打开则打开它。This can be combined into a single call with TryOpenAsync, which checks if the parameter can be opened and if so open it.

public class LauncherTest
{
    public async Task<bool> OpenRideShareAsync()
    {
        return await Launcher.TryOpenAsync("lyft://ridetype?id=lyft_line");
    }
}

文件Files

此功能使应用能够请求其他应用打开和查看文件。This features enables an app to request other apps to open and view a file. Xamarin.Essentials 将自动检测文件类型 (MIME) 并请求打开文件。Xamarin.Essentials will automatically detect the file type (MIME) and request the file to be opened.

以下是将文本写入磁盘并请求将其打开的示例:Here is a sample of writing text to disk and requesting it be opened:

var fn = "File.txt";
var file = Path.Combine(FileSystem.CacheDirectory, fn);
File.WriteAllText(file, "Hello World");

await Launcher.OpenAsync(new OpenFileRequest
{
    File = new ReadOnlyFile(file)
});

平台差异Platform Differences

立即完成从 CanOpenAsync 返回的任务。The Task returned from CanOpenAsync completes immediately.

APIAPI