当有网络连接时,我需要从互联网中加载mWebview。而当没有网络连接时,它需要从缓存中加载。我已经做了一些尝试,但是根本没有加载该网站。
请帮帮我?
我已经添加了以下权限:
- android.permission.INTERNET
- android.permission.WRITE_EXTERNAL_STORAGE
- android.permission.ACCESS_NETWORK_STATE
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Layout Webview
mWebview = new WebView(this);
// Broadcast
Toast.makeText(this, "Laden van roosterwijzigingen.",
Toast.LENGTH_SHORT).show();
// Enable JavaScript
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebview.setHorizontalScrollBarEnabled(false);
mWebview.getSettings().setAppCacheMaxSize( 5 * 1024 * 1024 ); // 5MB
mWebview.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
mWebview.getSettings().setAllowFileAccess( true );
mWebview.getSettings().setAppCacheEnabled( true );
mWebview.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT ); // load online by default
final Activity activity = this;
// Make WebClient
mWebview.setWebViewClient(new WebViewClient() {
// Trace Errors
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
if ( !isNetworkAvailable() ) { // loading offline
mWebview.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}
mWebview.loadUrl("http://divers.ommelandercollege.nl/webportalen/dagrooster.php");
}