Webview应用程序检查网络并显示“ no internet connection”(如果没有连接,并在网络可用时重新加载)

问题描述 投票:0回答:1

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

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;
}
java android android-studio android-intent webview
1个回答
0
投票

创建广播接收器:

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" />
© www.soinside.com 2019 - 2024. All rights reserved.