1

我有一个应用程序,我在其中使用我的用户名和密码登录,然后切换到包含 web 视图的页面。webview 识别这个用户名和密码并加载内容(通过 sharedpreferences),但问题是,它只加载一次,当我导航到我的应用程序的其他部分并返回时,它显示一个空白屏幕,最终加载页面不能显示在网络视图中。有没有办法解决这个问题,让 webview 识别用户名并在你每次导航到页面并加载内容时传递。这是相同的代码:包含 webview 的页面:

public class AnswersFragmentWebView extends Fragment implements  MainActivity.BackPressListener<Fragment>  {

    private static final String SYMBOL = "symbol";
    private static final String SYMBOL_TYPE = "symbol_type";
    public  static final String CONTAINER_ID = "container_id";
    public static final String TAG_QUOTES_FRAGMENT_WEBVIEW = "AnswersFragmentWebView";
    public static void removeInstance(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment == null) {
            return;
        }

        final FragmentStackManager stackManager = FragmentStackManager.getInstance();
        if (stackManager.getTopFragment() instanceof AnswersFragmentWebView) {
            stackManager.popTopFragment();
        }
    }

    private boolean goingBack = false;
    private boolean onBackPressClearStack = true;
    private WebView webView;
    private final static String URL = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=dark&uuid=PADACT-002&userAgent=iphone";
    //private final static String URL = "https://www.google.com";
    SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
    private final  String USERNAME =manager.getLoginUsername(); 
    private final  String PASSWORD = manager.getDecryptedLoginPassword();
    private final static String HOST = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
    private final static String REALM = "Users Only";

    public void setOnBackPressClearStack(boolean b){
        onBackPressClearStack = b;
    }
    public boolean webViewSteppedBack() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();

            return true;
        }
        return false;
    }

    @Override
    public boolean backPressed(final MainActivity mainActivity) {
        if (webViewSteppedBack()) {
            return true;
        }

        if (onBackPressClearStack) {
            goingBack = true;
            FragmentUtils.onBackPressedKnockFragsOffStack(mainActivity, this);
        }
        return false;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId, final int inAnimation, final int outAnimation, final int popInAnimation, final int popOutAnimation) {
        final Bundle bundle = new Bundle();
        bundle.putString(AnswersFragmentWebView.SYMBOL, searchAutoSuggestSymbol);
        bundle.putString(AnswersFragmentWebView.SYMBOL_TYPE, symbolType);
        bundle.putInt(AnswersFragmentWebView.CONTAINER_ID, containerViewId);
        fragment.setArguments(bundle);

        FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, containerViewId);
        fragmentInfo.setAnimation(inAnimation, outAnimation);
        fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
        fragmentInfo.setFragmentTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.nav_option_quotes));
        FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);

        return fragment;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId, R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }


    private static void clearWebView(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment != null && fragment instanceof AnswersFragmentWebView) {
            ((AnswersFragmentWebView)fragment).clearWebView();
        }
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container);
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType, int containerViewId) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final FragmentManager manager, final String searchAutoSuggestSymbol,  final String symbolType, int containerViewId) {
        AnswersFragmentWebView fragment =  __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
        fragment.setOnBackPressClearStack(false);
        return fragment;
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final AnswersFragmentWebView fragment, final FragmentManager manager, final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        fragment.setOnBackPressClearStack(false);
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceForSearch(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        AnswersFragmentWebView fragment = __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container, R.anim.no_animation, R.anim.slide_out_to_right, R.anim.slide_in_from_right, R.anim.slide_out_to_right);
        return fragment;
    }

    public void clearWebView() {
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
            webView = null;
        }
    }



    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (goingBack) {
            return null;
        }
        final MainActivity activity = (MainActivity) getActivity();

        activity.setBackPressListener(this);


        final View view = inflater.inflate(R.layout.fragment_search_answers, container, false);

        if (!NetworkUtils.isOnline()) {
            LayoutUtils.showNoResult(view, R.id.quotes_webview_container);
            return view;

        }

        // setup webview
        webView = (WebView) view.findViewById(R.id.webview);


        webView.setVisibility(View.VISIBLE);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setBackgroundColor(0);
        webView.requestFocus();
        webView.reload();
        webView.getSettings().setSavePassword(true);
        webView.getSettings().setSaveFormData(true);
        webView.getSettings().getSaveFormData();
        webView.getSettings().getSavePassword();
        //WebViewDatabase.getInstance(getActivity()).clearHttpAuthUsernamePassword();
        WebViewDatabase.getInstance(getActivity()).hasHttpAuthUsernamePassword();
        webView.setHttpAuthUsernamePassword(HOST, REALM, USERNAME, PASSWORD);
        webView.setWebViewClient(new AnswersWebView(this,webView));
        webView.loadUrl(URL);



        return view;
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getArguments().getString(AnswersFragmentWebView.SYMBOL);
    }


}

网络视图客户端:

public class AnswersWebView extends WebViewClient {

    private String loginCookie;
    private Context mContext;
    private WebView mWebView;

    public AnswersWebView(AnswersFragmentWebView answersFragmentWebView, WebView webview) {
        super();

        //mContext = answersFragmentWebView;
        mWebView = webview;
    }

    @Override
    public void onPageStarted( WebView view, String url, Bitmap favicon ) {
    }

    @Override
    public void onPageFinished( WebView view, String url ) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie(url, loginCookie);
    }

    @Override
    public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
        Toast.makeText(view.getContext(), "ÉyÅ[ÉWì«Ç›çûÇ›ÉGÉâÅ[", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLoadResource( WebView view, String url ){
        CookieManager cookieManager = CookieManager.getInstance();
        loginCookie = cookieManager.getCookie(url);
    }

    @Override
    public boolean shouldOverrideUrlLoading( WebView view, String url ) {
        return false;
    }

    @Override
    public void onReceivedSslError( WebView view, SslErrorHandler handler, SslError error ) {
        handler.proceed();
    }

    @Override
    public void onReceivedHttpAuthRequest( WebView view, final HttpAuthHandler handler, final String host, final String realm ){
        SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
        String userName = manager.getLoginUsername();
        String userPass = manager.getDecryptedLoginPassword();

        if (handler.useHttpAuthUsernamePassword() && view != null) {
            String[] haup = view.getHttpAuthUsernamePassword(host, realm);
            if (haup != null && haup.length == 2) {
                userName = haup[0];
                userPass = haup[1];
            }
        }

        if (userName != null && userPass != null) {
            handler.proceed(userName, userPass);
        }
        else {
            showHttpAuthDialog(handler, host, realm, null, null, null);
        }
    }

    private void showHttpAuthDialog( final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password ) {
        LinearLayout llayout = new LinearLayout((Activity)mContext);
        final TextView textview1 = new TextView((Activity)mContext);
        final EditText edittext1 = new EditText((Activity)mContext);
        final TextView textview2 = new TextView((Activity)mContext);
        final EditText edittext2 = new EditText((Activity)mContext);
        llayout.setOrientation(LinearLayout.VERTICAL);
        textview1.setText("username:");
        textview2.setText("password:");
        llayout.addView(textview1);
        llayout.addView(edittext1);
        llayout.addView(textview2);
        llayout.addView(edittext2);

        final Builder mHttpAuthDialog = new AlertDialog.Builder((Activity)mContext);
        mHttpAuthDialog.setTitle("Basic Authentication")
        .setView(llayout)
        .setCancelable(false)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                EditText etUserName = edittext1;
                String userName = etUserName.getText().toString();
                EditText etUserPass = edittext2;
                String userPass = etUserPass.getText().toString();

                mWebView.setHttpAuthUsernamePassword(host, realm, name, password);

                handler.proceed(userName, userPass);
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                handler.cancel();
            }
        })
        .create().show();
    }

}

谢谢!贾斯汀

4

4 回答 4

1

好的。

您必须在 onResume 而不是 OnCreate 中添加用户名/密码

就像在本文档中解释 http://developer.android.com/reference/android/app/Activity.html

于 2013-08-22T16:13:12.427 回答
0

在我之前的项目中,我遇到了一些类似的问题。我用这种方法解决了 - 在onCreate中实例化空白/默认布局,然后从 sharedPref 加载配置并在onResume中设置布局的参数值。并在离开页面之前将配置更改(如果发生)保存在onPause中。如果这看起来不错,您可以检查一下您的情况。

于 2013-08-30T09:55:42.933 回答
0

这就是cookie管理的问题。

案例:~ 1 如果您正在访问其他网站(facebook、gmail 等)。要解决此问题,您必须维护通过 vebView 传来的 cookie 文件。

并将其发送回下一次新页面请求。

案例:~ 2 如果您正在访问自己的网站,那么还有另一个问题解决方案是您可以检查服务器端(在您的网站中)设备信息并将其与登录时的设备信息进行比较。

或者您可以在隐藏标签中发送隐藏数据并在您的应用中验证它。

于 2013-08-30T07:27:16.533 回答
0

将 SharedPref 代码移动到 onClick 并在此处报告...

于 2013-08-25T10:42:44.633 回答