Search code examples
androidandroid-intentandroid-webviewandroid-sharing

How to stop Activity from reloading when using Intent.createChooser() to launch a sharing menu?


I have a WebView which has an sharing icon at the bottom of the page.

When the user presses the icon, it launches a sharing menu:

chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), "Share via");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, SHARING_MENU);

After the sharing menu pops up, if the user presses Back button or clicks outside the sharing menu, it closes down but the Activity restarts and the webpage reloads inside the webview.

I want to stop it. I tried to implement to the following code inside onActivityResult, but it is not working

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request we're responding to
        if (requestCode == SHARING_MENU) {
            // Make sure the request was successful
            if (resultCode == RESULT_CANCELED) {
                webviewObj.stopLoading();
                this.finishActivity(SHARING_MENU);
            }
        }
    }

I tried adding - android:launchMode="singleInstance" in the manifest file, but it does not work.

Please help !!!


Solution

  • I found a simple solution to this problem.

    In the WebView's Activity, I added the UI initialization code inside the :-

    @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.webview);
    
            if(savedInstanceState == null) {
                initUI();
            }           
        }
    

    And this solved my problem :)