Search code examples
javaandroidgoogle-chromechrome-custom-tabs

How to catch errors when using Chrome customTabs


I am trying to open a PDF file with Chrome customTab. However, I know that the PDF becomes available only during certain time periods and returns a 404 error at other times. So I started looking for some way to handle this 404 error being returned but I don't know where I can retrieve the HTML status code from.

This is my code:

     CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
            CustomTabsIntent intent = builder.build();
            builder.setToolbarColor(getResources().getColor(R.color.md_red_700));
            builder.setStartAnimations(WelcomeActivity.this, R.anim.slide_in_right, R.anim.slide_out_left);
            builder.setExitAnimations(WelcomeActivity.this, R.anim.slide_in_left, R.anim.slide_out_right);
            intent.launchUrl(WelcomeActivity.this, Uri.parse(completeUrl));

tl;dr: I want to manage a 404 error when opening chrome customTabs, how can I do this?


Solution

  • Before launch the PDF Url first you need to call HTTPURL Connection for the status. Below code helps you to check the status of the PDF URL.

    Once you get success code 200 then and then call CustomIntentTab.

    Below code helps you to check the status code.

    URL url = new URL("http://example.com");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("GET");
    connection.connect();
    
    int code = connection.getResponseCode();