简体   繁体   English

模拟器上的webview启动画面问题

[英]splash screen issue with webview on emulator

My app works totally fine until I added a splash screen feature to my app. 在我向应用程序添加了初始屏幕功能之前,我的应用程序运行良好。 I tried to follow some solutions available on internet. 我试图遵循一些互联网上可用的解决方案。 The problem occurs when I execute my app in android emulator for very few seconds it shows me an alert box showing the following statement 当我在android模拟器中执行我的应用几秒钟时,就会出现问题,它向我显示一个警告框,其中显示以下语句

Waiting for Debugger 等待调试器

Application TestApp (process com.testapp.mytestapp) is waiting for the debugger to attach. 应用程序TestApp(进程com.testapp.mytestapp)正在等待调试器附加。

Force Close button 强制关闭按钮

And after it my app runs absolutely fine. 之后,我的应用程序运行完全正常。 I am still not sure whether its and error or something else because of my poor coding skills and I made a mistake in my code or missed something. 我仍然不确定是由于错误的编码技巧而导致错误,错误还是其他原因,并且我在代码中犯了错误或遗漏了某些内容。 Also I wanted to increase the duration of the Splash Image (somehow possible) because sometimes the splash image disappears before complete loading of the webpage but as I am new to android development I am unable to figure out a proper solution or reference to following. 我也想增加启动画面的持续时间(以某种方式可能),因为有时启动画面在完全加载网页之前就消失了,但是由于我是Android开发的新手,所以我无法找出合适的解决方案或参考以下内容。 Further my emulator version is Nexus 4 API 22 此外,我的模拟器版本是Nexus 4 API 22

Here is my Main MyActivity class 这是我的主要MyActivity课程

package com.testapp.mytestapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import java.io.File;
import static com.testapp.mytestapp.R.*;


public class MyActivity extends Activity {
    private WebView webView;
    private FrameLayout customViewContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private View mCustomView;
    private myWebChromeClient mWebChromeClient;
    private myWebViewClient mWebViewClient;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
        webView = (WebView) findViewById(R.id.webView);
        ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

        if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {

            AlertDialog alertDialog;
            alertDialog = new AlertDialog.Builder(this, style.AlertDialogCustom).create();
            alertDialog.setTitle("Communication Error");
            alertDialog.setMessage("Please make sure that internet connection is active.");
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            alertDialog.show();
        } else {
            AppRater appRater = new AppRater(this);
            appRater.setDaysBeforePrompt(1);
            appRater.setLaunchesBeforePrompt(3);
            appRater.setPhrases("Rate This App",
                    "If you like our App don't forget to rate our application on Google Play. Thanks for your support!",
                    "Rate Now", "Later", "Ignore");
            appRater.setTargetUri("https://play.google.com/store/apps/details?id=" + getApplicationContext().getPackageName());
            appRater.show();
            customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
            webView = (WebView) findViewById(R.id.webView);
            mWebViewClient = new myWebViewClient();
            webView.setWebViewClient(mWebViewClient);
            mWebChromeClient = new myWebChromeClient();
            webView.setWebChromeClient(mWebChromeClient);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setAppCacheEnabled(true);
            webView.getSettings().setSaveFormData(true);
            webView.loadUrl("https://custom-domain-name.com");
            webView.setWebViewClient(new MyAppWebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    //hide loading image
                    findViewById(R.id.imageLoading1).setVisibility(View.GONE);
                    //show webview
                    findViewById(R.id.customViewContainer).setVisibility(View.VISIBLE);
                }
            });
        }
    }

    public boolean inCustomView() {
        return (mCustomView != null);
    }

    public void hideCustomView() {
        mWebChromeClient.onHideCustomView();
    }

    @Override
    protected void onPause() {
        super.onPause();    //To change body of overridden methods use File | Settings | File Templates.
        webView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();    //To change body of overridden methods use File | Settings | File Templates.
        webView.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();    //To change body of overridden methods use File | Settings | File Templates.
        if (inCustomView()) {
            hideCustomView();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (inCustomView()) {
                hideCustomView();
                return true;
            }

            if ((mCustomView == null) && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    class myWebChromeClient extends WebChromeClient {
        private Bitmap mDefaultVideoPoster;
        private View mVideoProgressView;

        @Override
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
           onShowCustomView(view, callback);    //To change body of overridden methods use File | Settings | File Templates.
        }

        @Override
        public void onShowCustomView(View view,CustomViewCallback callback) {

            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            mCustomView = view;
            webView.setVisibility(View.GONE);
            customViewContainer.setVisibility(View.VISIBLE);
            customViewContainer.addView(view);
            customViewCallback = callback;
        }

        @Override
        public View getVideoLoadingProgressView() {

            if (mVideoProgressView == null) {
                LayoutInflater inflater = LayoutInflater.from(MyActivity.this);
                mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
            }
            return mVideoProgressView;
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView();    //To change body of overridden methods use File | Settings | File Templates.
            if (mCustomView == null)
                return;

            webView.setVisibility(View.VISIBLE);
            customViewContainer.setVisibility(View.GONE);

            // Hide the custom view.
            mCustomView.setVisibility(View.GONE);

            // Remove the custom view from its container.
            customViewContainer.removeView(mCustomView);
            customViewCallback.onCustomViewHidden();

            mCustomView = null;
        }
    }

    class myWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return super.shouldOverrideUrlLoading(view, url);    //To change body of overridden methods use File | Settings | File Templates.
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            trimCache(); //if trimCache is static
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void trimCache() {
        try {
            File dir = getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        }
        return false;
    }


}

Here is my MyAppWebViewClient Class 这是我的MyAppWebViewClient

package com.testapp.mytestapp;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyAppWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(Uri.parse(url).getHost().endsWith("custom-domain-name.com")) {
            return false;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }
}

Here is my AndroidManifest.xml 这是我的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.testapp.mytestapp" >
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
    <application android:label="@string/app_name" android:icon="@drawable/ic_launcher"
            android:hardwareAccelerated="true">
        <activity android:name=".MyActivity"
                  android:configChanges="orientation|keyboardHidden"
                  android:hardwareAccelerated="true"
                  android:label="@string/app_name"
                    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Here is my layout's main.xml 这是我的布局的main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <ImageView android:id="@+id/imageLoading1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:visibility="visible"
        android:src="@drawable/splash_me2"
        android:scaleType = "centerCrop" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <WebView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/webView"
            android:layout_gravity="center"
            />
    <FrameLayout
            android:id="@+id/customViewContainer"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:visibility="gone"
            />
</LinearLayout>

Here is my Log from LogCat 这是我的LogCat日志

11-30 16:10:06.709: E/Launcher(1465): Unable to launch. tag=ApplicationInfo(title=TestApp  P=UserHandle{0}) intent=Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.testapp.mytestapp/.MyActivity (has extras) }
11-30 16:10:06.709: E/Launcher(1465): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.testapp.mytestapp/com.testapp.mytestapp.MyActivity}; have you declared this activity in your AndroidManifest.xml?
11-30 16:16:20.860: E/InputDispatcher(1244): channel '2fc7fe4c com.testapp.mytestapp/com.testapp.mytestapp.MyActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

This is not an error message, it only indicates you are running your app in debug mode and it takes a second for the debugger to get attached. 这不是错误消息,仅表示您在调试模式下运行应用程序,调试器需要一秒钟的时间才能连接。 The button with the grey bug is to run in debug mode, if you just want to run the app use the other green play button 带有灰色错误的按钮将在调试模式下运行,如果您只想运行应用程序,请使用另一个绿色播放按钮

该图显示了Android Studio中的调试按钮

You can ignore that message from the debugger sometimes it just take a little time to run in the emulator. 您可以忽略来自调试器的消息,有时仅需要一点时间即可在仿真器中运行。

You could track the progress on your WebChromeClient and check when it's 100. 您可以在WebChromeClient上跟踪进度,并检查进度为100。

webView.setWebChromeClient(new myWebChromeClient() { 

    public void onProgressChanged(WebView view, int progress) { 

      if (progress == 100) { 
         //...page is fully loaded. 
         findViewById(R.id.imageLoading1).setVisibility(View.GONE); 
        //show webview 
        findViewById(R.id.customViewContainer).setVisibility(View.VISIBLE); 
       } 
    } 
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM