How do I call an intent in Retrofit Callback?

后端 未结 2 560
谎友^
谎友^ 2021-02-10 06:54

I want to display a new activity on success callback of my WebService called by Retrofit. And I have difficulties to find examples on how to use Retrofit callback result to laun

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-10 07:41

    You can implement Callback with weak reference to Context

    public class MyCallback implements Callback {
    
        WeakReference mContextReference;
    
        public MyCallback(Context context) {
            mContextReference = new WeakReference(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
        }
    
    }  
    

    Just remember - this solution will not work if Context lost occurred while request in progress but you may don't worry about potential memory leak which may be if you keep strong reference to Context object.

提交回复
热议问题