本文共 6001 字,大约阅读时间需要 20 分钟。
Bolts 是一个由 Parse 和 Facebook 设计并内部使用的低级库集合。为了方便其他开发者使用,我们决定对这些库进行开源。使用 Bolts 不需要依赖任何 Parse 服务,也不需要拥有 Parse 或 Facebook 开发者账号。
在移动应用开发中,异步操作是必不可少的。然而,传统的异步编程方法(如 callbacks 和 AsyncTask)往往会导致代码嵌套、资源占用和金字塔式代码结构。Task 类提供了更高效的解决方案:
Task 提供了 continueWith 方法,用于接收 Continuation 对象。Continuation 的 then 方法将在 Task 完成时调用,可以检查 Task 是否成功、取消或失败,并获取结果。
TasksaveAsync(ParseObject obj) { return ParseObject.saveAsync(obj).continueWith( new Continuation () { @Override public Void then(Task task) throws Exception { if (task.isCancelled()) { // 任务已被取消 } else if (task.isFaulted()) { // 任务失败 Exception error = task.getError(); } else { // 任务成功 ParseObject object = task.getResult(); } return null; } });}
如果只需要处理成功回调,可以使用 onSuccess 方法:
TasksaveAsync(ParseObject obj) { return ParseObject.saveAsync(obj).onSuccess( new Continuation () { @Override public Void then(Task task) throws Exception { // 任务成功 return null; } } );}
Task 的强大组合能力使得代码更加简洁。通过 continueWithTask 和 onSuccessTask,可以轻松实现链式任务:
ParseQueryquery = ParseQuery.getQuery("Student");query.orderByDescending("gpa");final Task findTask = ParseObject.findAsync(query);Task thenTask = findTask.continueWithTask( new Continuation >() { @Override public Task then(Task task) throws Exception { // 获取查询结果 ParseObject student = task.getResult(); // 执行后续操作 return saveAsync(student.put("valedictorian", true)); } } ); // 处理最终结果 thenTask.continueWith( new Continuation () { @Override public Void then(Task task) throws Exception { return null; } } );
Task 提供了丰富的错误处理方式。通过 Continuation,可以在任务完成时处理错误或取消状态:
TaskfindAsync(ParseQuery query) { return query.findAsync() .continueWithTask( new Continuation >() { @Override public Task then(Task task) throws Exception { if (task.isFaulted()) { throw new RuntimeException("查询失败"); } return task; } } );}
除了内置的异步方法(如 saveAsync 和 findAsync),开发者还可以手动创建 Task:
public static TasksucceedAsync() { TaskCompletionSource source = new TaskCompletionSource<>(); source.setResult("成功结果"); return source.getTask();}public static Task failAsync() { TaskCompletionSource source = new TaskCompletionSource<>(); source.setError(new RuntimeException("错误信息")); return source.getTask();}
Task 提供了高度可定制的执行器(Executor),允许开发者控制任务执行的线程池:
// 创建自定义线程池static final Executor NETWORK_EXECUTOR = Executors.newCachedThreadPool();static final Executor DISK_EXECUTOR = Executors.newCachedThreadPool();// 使用指定的 executorTaskrequestTask = Task.call( new Callable () { @Override public HttpResponse call() throws Exception { return client.execute(request); } }, NETWORK_EXECUTOR).continueWith( new Continuation >() { @Override public Task then(Task task) throws Exception { return processResponseAsync(task.getResult()); } }).continueWithTask( new Continuation >() { @Override public Task then(Task task) throws Exception { return writeToDiskAsync(task.getResult()); } }, DISK_EXECUTOR );
App Links 提供了一个简单的 API,允许开发者定义和发布多层链接,其他应用可以通过它实现深度链接。
在 Activity 中使用 AppLinks 工具类解析传入的 Intent:
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Uri targetUrl = AppLinks.getTargetUrlFromInboundIntent(getIntent()); if (targetUrl != null) { Bundle applinkData = AppLinks.getAppLinkData(getIntent()); String id = applinkData.getString("id"); Bundle referrerAppData = applinkData.getBundle("referer_app_link"); Bundle extras = AppLinks.getAppLinkExtras(getIntent()); String fbAccessToken = extras.getString("fb_access_token"); } else { // 处理非 App Link 的情况 }} 通过 App Link 简化导航流程:
AppLinkNavigation navigate = new AppLinkNavigation( link, extras, appLinkData);navigate.navigate();
Bolts 允许开发者自定义解析器,优化 App Link 的处理:
public class CustomAppLinkResolver implements AppLinkResolver { @Override public AppLinkNavigation resolveAppLink(Uri uri, Context context) { // 自定义解析逻辑 return super.resolveAppLink(uri, context); }}AppLinkNavigation.setDefaultResolver(new CustomAppLinkResolver());AppLinkNavigation.navigateInBackground(url); Bolts 提供了测量事件,帮助开发者分析 App Link 的使用情况。通过监听 al_nav_in 和 al_nav_out 事件,可以获取详细的导航数据。
al_nav_in:
al_nav_out:
通过这些事件,开发者可以深入分析 App Link 的使用效果,优化用户体验。
转载地址:http://dala.baihongyu.com/