gpt4 book ai didi

android - 事件总线能否在Android应用中完全替代Intents?

转载 作者:搜寻专家 更新时间:2023-11-01 08:49:33 26 4
gpt4 key购买 nike

是否有可能在 Android 应用程序中完全摆脱 Intent 系统并仅使用事件总线(Otto、greenrobot)?例如,是否可以仅使用事件总线实现这一点,而根本没有 Intent:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();

如果我使用事件总线,它会自动恢复正确的 Activity 并将其置于最前面,就像使用 Intents 那样吗?

最佳答案

到目前为止我找到的唯一解决方案是一组实用方法,它是来自 greenrobot 的 Intents 和 EventBus 的混合:

public class ActivityUtils {
public static void startForResult(Activity context, Class<?> destinationActivity, Object param) {
Intent intent = new Intent(context, destinationActivity);
EventBus.getDefault().postSticky(param);
context.startActivityForResult(intent, 0);
}

public static void returnSuccessfulResult(Activity context, Object result) {
Intent returnIntent = new Intent();
EventBus.getDefault().postSticky(result);
context.setResult(Activity.RESULT_OK, returnIntent);
context.finish();
}

public static <T> T getParameter(Class<T> type) {
return EventBus.getDefault().removeStickyEvent(type);
}
}

在我的 FirstActivity 中,我调用了类似这样的东西:

ActivityUtils.startForResult(this, SecondActivity.class, new MyParam("abc", 123));

之后在 SecondActivity 中调用:

MyParam param = ActivityUtils.getParameter(MyParam.class);

当我完成 SecondActivity 时:

ActivityUtils.returnSuccessfulResult(this, new MyResult("xyz"));

然后在 FirstAcivity 中:

MyResult result = ActivityUtils.getParameter(MyResult.class);

关于android - 事件总线能否在Android应用中完全替代Intents?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24904955/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com