Webview 应用程序检查网络并在没有网络时显示“无互联网连接”,并在网络可用时重新加载

Posted

技术标签:

【中文标题】Webview 应用程序检查网络并在没有网络时显示“无互联网连接”,并在网络可用时重新加载【英文标题】:Webview app to check for network and display "no internet connection" if there is none and also reload when network is available 【发布时间】:2020-03-12 02:33:37 【问题描述】:

我创建了一个简单的 webview 应用程序,它在没有网络时显示来自资产的 error.html,但是一旦网络可用,用户就无法继续使用 webview。用户只是停留在 error.html 页面中。我现在一直在尝试做的是让 webview 应用程序检查网络并在没有网络时显示“没有互联网连接”,并在网络可用时重新加载。

Manifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mary">


    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Splash"
            android:label="@string/app_name"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

private WebView mWebView;

SwipeRefreshLayout swipe;



private void setFullScreen() 
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN
    );


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



   swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
   swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() 
       @Override
       public void onRefresh() 

           LoadWeb(mWebView.getUrl());
       
   );

    LoadWeb("http://m.mary.org");




public void  LoadWeb(String url)

    mWebView = (WebView) findViewById(R.id.activity_main_webview);
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setjavascriptEnabled(true);
    mWebView.loadUrl(url);
    swipe.setRefreshing(true);


    mWebView.setDownloadListener(new DownloadListener() 
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) 

            DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
            myRequest.allowScanningByMediaScanner();
            myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            DownloadManager myManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            myManager.enqueue(myRequest);

            Toast.makeText(MainActivity.this, "Your File is downloading....", Toast.LENGTH_SHORT).show();
        );

    mWebView.setWebViewClient(new com.example.mary.MyAppWebViewClient()

        public void onReceivedError(WebView view, int errorCode, String description,String failingUrl) 

            mWebView.loadUrl("file:///android_asset/error.html");
        

        public void onPageFinished(WebView view, String url) 
            //hide loading image

            swipe.setRefreshing(false);
            //show webview
            findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
        );



@Override
public void onBackPressed() 
    if(mWebView.canGoBack()) 
        mWebView.goBack();
     else 
        super.onBackPressed();
    


MyAppWebViewClient.java

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) 
    if(Uri.parse(url).getHost().endsWith("m.mary.org")) 
        return false;
    

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

【问题讨论】:

也许你可以在你的活动中编写一个广播接收器,一旦你连接并接收到广播,你就可以重新加载 webview。 (只是一个建议:请将您的 URL 存储在某个常量中。) 【参考方案1】:

创建广播接收器:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.HashSet;
import java.util.Set;

public class NetworkStateReceiver extends BroadcastReceiver 

protected Set<NetworkStateReceiverListener> listeners;
protected Boolean connected;

public NetworkStateReceiver() 
    listeners = new HashSet<NetworkStateReceiverListener>();
    connected = null;


public void onReceive(Context context, Intent intent) 
    if(intent == null || intent.getExtras() == null)
        return;

    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = manager.getActiveNetworkInfo();

    if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) 
        connected = true;
     else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) 
        connected = false;
    

    notifyStateToAll();


private void notifyStateToAll() 
    for(NetworkStateReceiverListener listener : listeners)
        notifyState(listener);


private void notifyState(NetworkStateReceiverListener listener) 
    if(connected == null || listener == null)
        return;

    if(connected == true)
        listener.networkAvailable();
    else
        listener.networkUnavailable();


public void addListener(NetworkStateReceiverListener l) 
    listeners.add(l);
    notifyState(l);


public void removeListener(NetworkStateReceiverListener l) 
    listeners.remove(l);


public interface NetworkStateReceiverListener 
    public void networkAvailable();
    public void networkUnavailable();


在你的活动中这样使用它:

private NetworkStateReceiver.NetworkStateReceiverListener networkStateReceiverListener = new NetworkStateReceiver.NetworkStateReceiverListener() 
    @Override
    public void networkAvailable() 
        //todo: refresh webview
    

@Override
public void networkUnavailable() 
  //todo: show error

;

清单中的权限:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

【讨论】:

以上是关于Webview 应用程序检查网络并在没有网络时显示“无互联网连接”,并在网络可用时重新加载的主要内容,如果未能解决你的问题,请参考以下文章

加载 Webview 时显示图像

手机微信连接网络时显示 连接失败 请检查微信链接WIFi参数是怎么回事

iOS Swift Webview 在加载时显示图像

如何在 url 加载时显示图像

在后台加载 Webview 时显示启动画面

如何保存选定的 TableView 行数据并在用户返回屏幕时显示?