|
| 1 | +package com.foxdebug.acode.rk.customtabs; |
| 2 | + |
| 3 | +import android.content.ActivityNotFoundException; |
| 4 | +import android.content.Intent; |
| 5 | +import android.net.Uri; |
| 6 | +import android.graphics.Color; |
| 7 | + |
| 8 | +import androidx.browser.customtabs.CustomTabsIntent; |
| 9 | + |
| 10 | +import org.apache.cordova.CallbackContext; |
| 11 | +import org.apache.cordova.CordovaPlugin; |
| 12 | +import org.json.JSONArray; |
| 13 | +import org.json.JSONObject; |
| 14 | + |
| 15 | +public class CustomTabsPlugin extends CordovaPlugin { |
| 16 | + |
| 17 | + @Override |
| 18 | + public boolean execute( |
| 19 | + String action, |
| 20 | + JSONArray args, |
| 21 | + CallbackContext callbackContext |
| 22 | + ) { |
| 23 | + |
| 24 | + if ("open".equals(action)) { |
| 25 | + try { |
| 26 | + final String url = args.getString(0); |
| 27 | + final JSONObject options = args.optJSONObject(1) != null |
| 28 | + ? args.optJSONObject(1) |
| 29 | + : new JSONObject(); |
| 30 | + |
| 31 | + cordova.getActivity().runOnUiThread(() -> { |
| 32 | + try { |
| 33 | + openCustomTab(url, options); |
| 34 | + callbackContext.success(); |
| 35 | + } catch (Exception e) { |
| 36 | + callbackContext.error(e.getMessage()); |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + return true; |
| 41 | + |
| 42 | + } catch (Exception e) { |
| 43 | + callbackContext.error(e.getMessage()); |
| 44 | + return true; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + private void openCustomTab(String url, JSONObject options) { |
| 52 | + CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); |
| 53 | + |
| 54 | + String toolbarColor = options.optString("toolbarColor", null); |
| 55 | + if (toolbarColor != null && !toolbarColor.isEmpty()) { |
| 56 | + builder.setToolbarColor(Color.parseColor(toolbarColor)); |
| 57 | + } |
| 58 | + |
| 59 | + CustomTabsIntent customTabsIntent = builder.build(); |
| 60 | + |
| 61 | + if (options.optBoolean("showTitle", true)) { |
| 62 | + customTabsIntent.intent.putExtra(CustomTabsIntent.EXTRA_TITLE_VISIBILITY_STATE, CustomTabsIntent.SHOW_PAGE_TITLE); |
| 63 | + } |
| 64 | + |
| 65 | + try { |
| 66 | + customTabsIntent.launchUrl( |
| 67 | + cordova.getActivity(), |
| 68 | + Uri.parse(url) |
| 69 | + ); |
| 70 | + } catch (ActivityNotFoundException e) { |
| 71 | + // Fallback to default browser |
| 72 | + Intent fallback = new Intent( |
| 73 | + Intent.ACTION_VIEW, |
| 74 | + Uri.parse(url) |
| 75 | + ); |
| 76 | + cordova.getActivity().startActivity(fallback); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments