简体   繁体   English

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

[英]Webview app to check for network and display “no internet connection” if there is none and also reload when network is available

I created a simple webview app that displays an error.html from assets when there is no network, but users cannot continue with webview once network is available.我创建了一个简单的 webview 应用程序,该应用程序显示错误。当没有网络时,来自资产的 html,但是一旦网络可用,用户就无法继续使用 webview。 users are simply stuck in the error.html page.用户只是停留在 error.html 页面。 what i have been trying to do now is to make the webview app to check for network and display "no internet connection" if there is none and also reload when network is available.我现在一直在尝试做的是让 webview 应用程序检查网络并在没有网络时显示“没有互联网连接”,并在网络可用时重新加载。

Manifest.xml清单.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 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 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;
}

create a broadcast receiver:创建广播接收器:

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();
}
}

in your activity use it like this:在您的活动中像这样使用它:

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

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

permission in manifest:清单中的许可:

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

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

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