简体   繁体   English

如何在Android中从自定义浏览器导航到应用?

[英]How to navigate from custom browser to app in Android?

I integrated custom browser in my app for PayU integration. 我在应用程序中集成了自定义浏览器以实现PayU集成。 I am not sending any parameters to PayU URL ( https://secure.payu.in/_payment ). 我没有向PayU URL( https://secure.payu.in/_payment )发送任何参数。 I am doing (sending parameters to PayU) this at server side. 我正在服务器端执行此操作(将参数发送到PayU)。 I need only customization of browser, that's why I am using this one. 我只需要自定义浏览器,这就是为什么我要使用该浏览器。 This is working fine to me, but after payment success it is showing empty white screen. 这对我来说很好,但是付款成功后,它会显示空白屏幕。 How to navigate to my app after this white empty screen. 白色的空白屏幕后,如何导航到我的应用程序。

How can I get URL of the custom browser? 如何获取自定义浏览器的URL?

ref link: https://github.com/payu-intrepos/Android-Custom-Browser/wiki/v5.2.2 引用链接: https : //github.com/payu-intrepos/Android-Custom-Browser/wiki/v5.2.2

dependency: 依赖性:

compile 'com.payu.custombrowser:payu-custom-browser:5.2.2'

code: 码:

custombrowserxl: custombrowserxl:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/r_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">
    <FrameLayout
        android:id="@+id/parent"
        android:visibility="gone"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:id="@+id/trans_overlay"
        android:layout_height="match_parent"
        android:orientation="horizontal"
       >
    </LinearLayout>
</RelativeLayout>

custombrowser.java custombrowser.java

 try {
            Class.forName("com.payu.custombrowser.Bank");
            final Bank bank = new Bank() {
                @Override
                public void registerBroadcast(BroadcastReceiver broadcastReceiver, IntentFilter filter) {
                    mReceiver = broadcastReceiver;
                    registerReceiver(broadcastReceiver, filter);
                }

                @Override
                public void unregisterBroadcast(BroadcastReceiver broadcastReceiver) {
                    if(mReceiver != null){
                        unregisterReceiver(mReceiver);
                        mReceiver = null;
                    }
                }

                @Override
                public void onHelpUnavailable() {
                    findViewById(R.id.parent).setVisibility(View.GONE);
                    findViewById(R.id.trans_overlay).setVisibility(View.GONE);
                }

                @Override
                public void onBankError() {
                    findViewById(R.id.parent).setVisibility(View.GONE);
                    findViewById(R.id.trans_overlay).setVisibility(View.GONE);
                }

                @Override
                public void onHelpAvailable() {
                    findViewById(R.id.parent).setVisibility(View.VISIBLE);
                }

            };
            Bundle args = new Bundle();
            args.putInt("webView", R.id.webview);
            args.putInt("tranLayout",R.id.trans_overlay);
            args.putInt("mainLayout",R.id.r_layout);
            args.putBoolean("showCustom", true);
            bank.setArguments(args);
            findViewById(R.id.parent).bringToFront();
            try {
                getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.cb_fade_in, R.anim.cb_face_out).add(R.id.parent, bank).commit();
            }catch(Exception e)
            {
                e.printStackTrace();
                finish();
            }

            webView.setWebChromeClient(new PayUWebChromeClient(bank));
            webView.setWebViewClient(new PayUWebViewClient(bank));
        } catch (ClassNotFoundException e) {
            webView.getSettings().setSupportMultipleWindows(true);
            webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

            webView.addJavascriptInterface(new Object() {
                @JavascriptInterface
                public void onSuccess() {

                    onSuccess("");
                }

                @JavascriptInterface
                public void onSuccess(final String result) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.putExtra("result", result);
                            setResult(RESULT_OK, intent);
                            finish();

                        }
//                }
                    });
                }

                @JavascriptInterface
                public void onFailure() {
                    onFailure("");
                }

                @JavascriptInterface
                public void onFailure(final String result) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.putExtra("result", result);
                            setResult(RESULT_CANCELED, intent);
                            finish();
                        }
                    });
                }
            }, "PayU");

            webView.setWebChromeClient(new WebChromeClient() {

            });
            webView.setWebViewClient(new WebViewClient());
        }

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);

     String   PostData="UserUniqueID=" + UUUID + "&OrderID=" + orderid + "&PFID=" + pid + "&ReloadCash=" + reloadcash + "&DeviceID=" + DEVICEID ;

        webView.postUrl(WebUrl.Bankurl, PostData.getBytes());
      //Weburl.posturl is my server side bank url.
    }


    @Override
    public void onBackPressed(){
        boolean disableBack = false;
        if(cancelTransaction){
            cancelTransaction = false;
            Intent intent = new Intent();
            intent.putExtra("result", "Transaction canceled due to back pressed!");
            setResult(RESULT_CANCELED, intent);
            super.onBackPressed();
            return;
        }
        try {
            Log.v("TAG_PAUSEURLL", "" + "PAUSEURL");
            Bundle bundle = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA).metaData;
            disableBack = bundle.containsKey("payu_disable_back") && bundle.getBoolean("payu_disable_back");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if(!disableBack) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.setCancelable(false);
            alertDialog.setMessage("Do you really want to cancel the transaction ?");
            alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelTransaction = true;
                    dialog.dismiss();
                    onBackPressed();
                }
            });
            alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        webView.clearCache(true);
        webView.clearHistory();
        webView.destroy();
    }

Prefer this code 首选此代码

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


    btnBuy.setOnClickListener(new OnClickListener() {

        @SuppressLint({ "SetJavaScriptEnabled", "ShowToast" }) @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(f_nm && f_pn  && f_email )
            {
                webview.setVisibility(View.VISIBLE);
                Integer randomNum = randInt(0, 9999999);
                txnid=randomNum.toString();
                firstname=etName.getText().toString();
                email=etEmail.getText().toString();
                amount=study_material_price;
                productinfo=study_material_name;
                phone=etPhone.getText().toString();
                String hashSequence = merchant_key+"|"+txnid+"|"+amount+"|"+productinfo+"|"+firstname+"|"+email+"|||||||||||"+salt;
                hash = hashCal("SHA-512", hashSequence);
                webview.addJavascriptInterface(new PayUJavaScriptInterface(), "PayUMoney");
                String json ="txnid="+txnid+"&key="+merchant_key+"&amount="+amount+"&hash="+hash+"&productinfo="+productinfo+"&surl="+SURL+"&furl="+FURL+"&firstname="+firstname+"&email="+email+"&phone="+phone+"&service_provider=payu_paisa";
                webview.getSettings().setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
                webview.getSettings().setDomStorageEnabled(true);
                webview.getSettings().setJavaScriptEnabled(true);
                webview.getSettings().setSupportMultipleWindows(true);
                webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
                webview.getSettings().setSupportZoom(true);       //Zoom Control on web (You don't need this
                //if ROM supports Multi-Touch
                webview.getSettings().setBuiltInZoomControls(true);
                webview.setWebViewClient(new WebViewClient());
                webview.setWebViewClient(
                        new SSLTolerentWebViewClient()
                        );
                webview.postUrl("https://secure.payu.in/_payment", EncodingUtils.getBytes(json, "BASE64"));

                try {

                    webview.setWebViewClient(new WebViewClient() {
                        @Override
                        public void onReceivedError(WebView view, int errorCode,
                                String description, String failingUrl) {
                            Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
                        }

                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            // handle different requests for different type of files
                            // this example handles downloads requests for .apk and .mp3 files
                            // everything else the webview can handle normally
                            if (url.endsWith(".mp3")||url.endsWith(".zip") || url.endsWith(".pdf") || url.endsWith(".jpg")|| url.endsWith(".doc")|| url.endsWith(".png")|| url.endsWith(".docx")|| url.endsWith(".xml")|| url.endsWith(".gif")) {
                                String urlSplit[] = url.split("/");
                                String fileName = urlSplit[urlSplit.length-1];
                                Uri source = Uri.parse(url);
                                // Make a new request pointing to the .apk url
                                DownloadManager.Request request = new DownloadManager.Request(source);
                                // appears the same in Notification bar while downloading
                                request.setDescription("Description for the DownloadManager Bar");
                                request.setTitle(fileName);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                }
                                // save the file in the "Downloads" folder of SDCARD
                                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,fileName);
                                // get download service and enqueue file
                                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                                manager.enqueue(request);
                            }
                            // if there is a link to anything else than .apk or .mp3 load the URL in the webview
                            else view.loadUrl(url);
                            return true;                
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                Toast.makeText(getApplicationContext(), "Please fill all the fields.", 1000).show();
            }
        }
    });
}   

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode)
        {
        case KeyEvent.KEYCODE_BACK:
            if(webview.canGoBack()){
                webview.goBack();
            }else{
                finish();
            }
            return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

private final class PayUJavaScriptInterface {
    PayUJavaScriptInterface() {
    }

    /**
     * This is not called on the UI thread. Post a runnable to invoke
     * loadUrl on the UI thread.
     */
    @JavascriptInterface
    public void success(long id, final String pId) {
        mHandler.post(new Runnable() {
            public void run() {
                mHandler = null;
                Toast.makeText(getApplicationContext(), "Your Transaction is Successful", 1000).show();
                status="Success";
                paymentId=pId;
                new StoreTransactionData().execute();
                Intent intent = new Intent();
                intent.putExtra("status", "success");
                intent.putExtra("transaction_id", paymentId);
                setResult(RESULT_OK, intent);
                studyDownloadPaid();
                finish();
            }
        });
    }



    @JavascriptInterface
    public void failure(final String id, String error) {
        Log.d("transaction data fail id", id +"   " +study_material_name);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                paymentId=id;
                status="Faluire";
                new StoreTransactionData().execute();
                cancelPayment();
            }
        });
    }

    @JavascriptInterface
    public void failure() {
        failure("");
    }

    @JavascriptInterface
    public void failure(final String params) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                paymentId=params;
                status="Faluire";
                new StoreTransactionData().execute();
                Log.d("transaction data fail param", params);
                Intent intent = new Intent();
                intent.putExtra("status", params);
                setResult(RESULT_CANCELED, intent);
                finish();
            }
        });
    }

}

private void cancelPayment() {
    Intent intent = new Intent();
    intent.putExtra("status", "cancel");
    //mWebView.destroy();
    setResult(RESULT_CANCELED, intent);
    finish();
}

public static String hashCal(String type, String str) {
    byte[] hashseq = str.getBytes();
    StringBuffer hexString = new StringBuffer();
    try {
        MessageDigest algorithm = MessageDigest.getInstance(type);
        algorithm.reset();
        algorithm.update(hashseq);
        byte messageDigest[] = algorithm.digest();
        for (int i = 0; i < messageDigest.length; i++) {
            String hex = Integer.toHexString(0xFF & messageDigest[i]);
            if (hex.length() == 1) {
                hexString.append("0");
            }
            hexString.append(hex);
        }
    } catch (NoSuchAlgorithmException nsae) {
    }
    return hexString.toString();
}

public static int randInt(int min, int max) {
    // Usually this should be a field rather than a method variable so
    // that it is not re-seeded every call.
    Random rand = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}


private class SSLTolerentWebViewClient extends WebViewClient {

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        handler.proceed(); // Ignore SSL certificate errors
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如果从浏览器安装在手机上,如何导航移动应用程序 - How to Navigate Mobile app if installed on your Phone from Browser Android Fragment如何从自定义listview baseadapter导航到Fargment? - Android Fragment How to navigate from custom listview baseadapter to Fargment? OA自定义URL方案拒绝工作/如何在OAuth之后导航回Android应用程序 - Android Custom URL Scheme Refuses To Work / How to Navigate Back to Android App After OAuth 如何使用自定义协议从android浏览器打开Microsoft Outlook应用程序? - How to open Microsoft outlook app from android browser using custom protocol? 使用自定义广告系列参数从浏览器意图打开 Android 应用 - Open Android app from browser intent with custom campaign parameter 从Google Chrome浏览器调用自定义Android应用 - Calling custom android app from a google chrome browser Android:如何从浏览器中获取应用程序? - Android: How to lauch an app from browser? 如何从Android应用程序打开特定的浏览器 - How to open a specific browser from an android app Android-从“系统设置”导航回应用 - Android - Navigate back to app from System Settings 如何在Android Web浏览器和我的自定义应用程序之间进行通信 - How to communicate between Android web browser and my custom app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM