Search code examples
javascriptandroidwebviewback

Android "Back Button" causes javascript to stop


I'm developing an app with a webview. I have a fileupload element and my app enables choosing "camera" or "gallery" by displaying an AlertDialog in the "openfilechooser" method. Here is what i'm doing:

-I tap on the fileupload element
-An AlertDialog pops up to read my choice of "camera" or "gallery"
-I change my mind and give up choosing a file and click "Android Back Button"

When i click the back button, all javascript stops and my page stops responding.

Is there a reason for javascript to stop? Thanks in advance


Solution

  • I tried several tricks and finally found the solution.

    FileUpload element needs a "ValueCallback" after all these method calls.So "onActivityResult" has to return a result to the fileupload element. But the "onActivityResult" method can not be called when user cancels the alert dialog. This causes fileupload element to generate error.

    I added "setOnCancelListener" to my alert dialog like this:

    .setOnCancelListener(new DialogInterface.OnCancelListener() {
    
        @Override
        public void onCancel(DialogInterface dialog) {
         mUploadMessage.onReceiveValue(null);
         mUploadMessage = null;
        }
    })
    

    You have to return at least "null" to the file upload element in order to keep operating . Otherwise fileupload stalls and this causes all javascript to stall.

    I also catched another case that makes fileupload stall:
    - User taps on the fileupload element
    - Chooses a choice (Cam or Galller doesn't matter)
    - Cam or Gallery shows up and user presses the "Back Button"

    This returns a RESULT_CANCELED code to the "onActivityResult" method and you have to handle it like this:

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        try {
            super.onActivityResult(requestCode, resultCode, intent);
    
            if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK
                    && intent != null)
                mUploadMessage.onReceiveValue(intent.getData());
            else
                mUploadMessage.onReceiveValue(null);
        } catch (Exception e) {
            Log.e("Error", e.getLocalizedMessage());
            mUploadMessage.onReceiveValue(null);
        } finally {
            mUploadMessage = null;
        }
    }
    

    mUploadMessage is defined like this:

        private ValueCallback<Uri> mUploadMessage;