如何在Retrofit Callback中调用intent?

Lab*_*abe 5 android android-intent android-activity retrofit

我想在Retrofit调用的WebService成功回调中显示一个新活动.我很难找到有关如何使用Retrofit回调结果来启动新活动的示例.这是一个很好的方法吗?我以前要清理一些东西吗?

public void validate(View view) {
    RetrofitWebServices.getInstance().webserviceMethod(params,new Callback<MyObject>() {
        @Override
        public void success(MyObject object, Response response) {
            Intent barIntent = new Intent(FooActivity.this, BarActivity.class);
            startActivity(barIntent);
        }

        @Override
        public void failure(RetrofitError error) {
            ...
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Via*_*lav 8

你可以Callback用弱引用来实现Context

public class MyCallback implements Callback<MyObject> {

    WeakReference<Context> mContextReference;

    public MyCallback(Context context) {
        mContextReference = new WeakReference<Context>(context);
    }

    @Override
    public void success(MyObject arg0, Response arg1) {
        Context context = mContextReference.get();
        if(context != null){
            Intent barIntent = new Intent(FooActivity.this, BarActivity.class);
            context.startActivity(barIntent);
        } else {
            // TODO process context lost
        }
    }

    @Override
    public void failure(RetrofitError arg0) {
        // TODO process error
    }

}  
Run Code Online (Sandbox Code Playgroud)

请记住 - 如果Context在进行请求时发生丢失,此解决方案将无效,但您可能不担心潜在的内存泄漏,如果您保持对Context对象的强引用.