自定义Launcher

如果希望自定义启动器以便自行处理路由的目的地,您需要实现Launcher.Factory接口并将实现类添加到路由SDK的Launcher列表中。LauncherFactory的示例如下:

public class CustomLauncherFactory implements Launcher.Factory {

    public static final String NAME = "custom";

    @NonNull
    @Override
    public Launcher newLauncher(@NonNull Request request) {
        return new CustomLauncher(request);
    }

    @NonNull
    @Override
    public String name() {
        return NAME;
    }

    ...
}

Factory接口包含两个方法:name方法返回Launcher的名称,仅当Launcher的名称与Destination中定义的Launcher一致时才会将路由请求发送到对应的Launcher中进行处理;newLauncher方法则实现了如何创建Launcher的逻辑,需要返回一个Launcher实例来接收路由请求。

private static class CustomLauncher implements Launcher {

    public CustomLauncher(Request request) {
        this.mRequest = request;
    }

    private final Request mRequest;

    @Override
    public void launch(Callback callback) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mRequest.context())
                .setTitle("提示")
                .setMessage("此为动态注册Launcher弹出的消息")
                .setPositiveButton("确认", (dialog, which) -> {
                    dialog.cancel();
                });
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(builder::show);

        callback.onComplete(Response.create(Response.STATUS_SUCCESS).build());
    }
}

Launcher是路由真正执行的末端。当目的地的类型匹配到对应Launcher时将调用launch方法来完成目的地的启动,应当在此处实现自定义的业务逻辑。无论目的地启动成功与否,都应当调用参数callback中的 onComplete 方法或是 onError 方法,以便通知路由请求方路由执行的结果。

定义好LauncherFactory后,需要将LauncherFactory注册到路由SDK中:

Portal.registerLauncher(new CustomLauncherFactory());

如果需要移除LauncherFactory,只需要提供LauncherFactory的名字即可:

Portal.unregisterLauncher(CustomLauncherFactory.NAME);

说明:当存在多个同名Launcher时,新注册的Launcher将会覆盖掉旧的Launcher(包括SDK原有的Launcher)。当移除Launcher时则会优先移除新注册的Launcher,此时旧Launcher将会重新生效。

Copyright © 2013-2023 Tencent Cloud. all right reserved,powered by GitbookUpdate Time 2023-08-31 14:46:07

results matching ""

    No results matching ""