巧用Fragment解耦onActivityResult

weixin_33785972發表於2018-08-05

最近在研究jsbridge, 一直在想怎麼樣才能讓需要startActivityForResult比如開啟相機拍照這樣的操作在webView中能更簡單一點, 直到我發現了這篇文章
兩個類,讓你再也不用實現onActivityResult()

看了之後, 馬上模仿了文中的程式碼實現了一下.
Fragment:

public class OnActResultEventDispatcherFragment extends Fragment{
    public static final String TAG = "on_act_result_event_dispatcher";

    public  int mRequestCode = 0x11;

    private SparseArray<ActResultRequest.Callback> mCallbacks = new SparseArray<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    public void startForResult(Intent intent, ActResultRequest.Callback callback) {
        // mRequestCode與callback需要一一對應
        mCallbacks.put(mRequestCode, callback);
        startActivityForResult(intent, mRequestCode);
        mRequestCode++;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ActResultRequest.Callback callback = mCallbacks.get(requestCode);
        mCallbacks.remove(requestCode);

        if (callback != null) {
            callback.onActivityResult(resultCode, data);
        }
    }

}

ActResultRequest:

public class ActResultRequest {

    private OnActResultEventDispatcherFragment fragment;

    public ActResultRequest(FragmentActivity activity) {
        fragment = getEventDispatchFragment(activity);
    }

    private OnActResultEventDispatcherFragment getEventDispatchFragment(FragmentActivity activity) {
        FragmentManager fragmentManager = activity.getSupportFragmentManager();


        OnActResultEventDispatcherFragment fragment = findEventDispatchFragment(fragmentManager);
        if (fragment == null) {
            fragment = new OnActResultEventDispatcherFragment();
            fragmentManager
                    .beginTransaction()
                    .add(fragment, OnActResultEventDispatcherFragment.TAG)
                    .commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        return fragment;
    }

    private OnActResultEventDispatcherFragment findEventDispatchFragment(FragmentManager manager) {
        return (OnActResultEventDispatcherFragment) manager.findFragmentByTag(OnActResultEventDispatcherFragment.TAG);
    }

    public void startForResult(Intent intent, Callback callback) {
        fragment.startForResult(intent, callback);
    }

    public interface Callback {

        void onActivityResult(int resultCode, Intent data);
    }
}

MainActivity:

public class MainActivity extends AppCompatActivity {
    
    private static final String TAG = "MainActivity";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    public void start(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        ActResultRequest request = new ActResultRequest(this);
        request.startForResult(intent, new ActResultRequest.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent data) {
                Log.d(TAG, "resultCode = " + resultCode);
                String name = data.getStringExtra("name");
                Log.d(TAG, "name = " + name);
                Toast.makeText(MainActivity.this, "name = " + name + ", resultCode = " + resultCode,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

SecondActivity

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

    }

    public void returnResult(View view) {
        Intent intent = new Intent();
        intent.putExtra("name", "mundane");
        setResult(RESULT_OK, intent);
        finish();

    }
}

按照這樣的思路, 如果需要簡化jsbridge中startActivityForResult的操作, 我們只需要把Fragment和WebView繫結在一起.比如給這個Fragment取名叫WebViewFragment, 它的佈局中只有一個我們封裝好的WebView, 這個WebView需要監聽jsbridge的所有事件我們都在fragment中寫好, 包括onActivityResult中的事件, 當然也可以在這個fragment中用一個專門的管理類來管理註冊的事件.以後Activity中有用到WebView的地方我們就直接用這個WebViewFragment就好了.也就是說, 把這個WebViewFragment, 當成我們之前的WebView.

github地址:

EasyOnActivityResult

相關文章