Handle onActivityResult on a Service

后端 未结 3 1985
野趣味
野趣味 2021-02-13 17:13

So i have a simple Question , it is Possible to Handle the Method onActivityResult() in a Service if this Activity was Started from the Same Service (Using Intent) ?

In

3条回答
  •  被撕碎了的回忆
    2021-02-13 17:44

    I recently stumbled upon the same issue, how to wire onActivityResult() outcome to a Service for an Activity started from the aforementioned Service. I did not want to store the Activity in a static variable given that Activity leak is a bad practice. So I added a static listener in the Activity handling onActivityResult() that implements an appropriate Interface and instantiated this listener as a private member of the Service class.

    The code in a simplified form looks like this:

    public class MyActivity extends FragmentActivity {
    
        public Interface ResultListener {
           onPositiveResult();
           onNegativeResult();
        }
    
        private static ResultListener mResultListener;
    
        public static setListener(ResultListener resultListener) {
            mResultListener = resultListener;
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (resultCode == Activity.RESULT_OK && mResultListener != null) {
                mResultListener.onPositiveResult(); 
            } else if (resultCode == Activity.RESULT_CANCELED && mResultListener != null) {
                mResultListener.onNegativeResult(); 
            }
            mResultListener = null;
        }
    }
    
    public class MyService {
    
        private MyActivity.ResultListener mListener = new MyActivity.ResultListener() {
            onPositiveResult() { 
                // do something on RESULT_OK
           }
           onNegativeResult() {
                // do something on RESULT_CANCELED 
           }
        }
    
        private void startActivityForResultFromHere() {
            MyActivity.setListener(mListener);
            Intent intent = new Intent();
            intent.setClass(this, MyActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } 
    }
    

    As you can see I could not avoid static references due to device rotation issues, but I think this solution is more appropriate; albeit verbose.

提交回复
热议问题