2

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

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

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

如果我使用事件总线,它会自动恢复正确的活动并将其带到前面,就像使用 Intents 所做的那样?

4

1 回答 1

3

The only solution I've found so far is a set of utility methods, that is a mix of Intents and EventBus from greenrobot:

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);
    }
}    

In my FirstActivity I call somethig like:

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

After that in the SecondActivity I call:

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

When I finish the SecondActivity:

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

And then in the FirstAcivity:

MyResult result = ActivityUtils.getParameter(MyResult.class);
于 2014-07-29T05:11:04.433 回答