如何在没有连接互联网的情况下在webview中加载html,否则在android中加载网站

时间:2014-02-27 06:01:12

标签: android webview

即使没有连接互联网,如何显示网页?如果互联网连接比网站应加载webview .. 我是Android的新手,我需要一个应用程序。我检查了互联网并创建了应用程序。 我的仪表板代码是:

public class Dashboard扩展了Activity {

public String BASE_URL = "http://mywebsite.com/";
public String DASHBOARD_URL = BASE_URL;

private JavascriptInterface jsInterface;

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    WebView engine = (WebView) findViewById(R.id.web_engine);

    // Progress bar.
    // With full screen app, window progress bar (FEATURE_PROGRESS) doesn't seem to show,
    // so we use an explicitly created one.
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);

    engine.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress)
        {
            progressBar.setProgress(progress);
        }
    });

    engine.setWebViewClient(new FixedWebViewClient() {
        public void onPageStarted(WebView view, String url, Bitmap favicon)
        {
            jsInterface.enablePreferencesMenu  = false;
            jsInterface.modalIsVisible = false;
            jsInterface.urlForSharing = null;
            progressBar.setVisibility(View.VISIBLE);
        }

        public void onPageFinished(WebView view, String url)
        {
            progressBar.setVisibility(View.GONE);
        }
    });
    engine.getSettings().setJavaScriptEnabled(true);
    jsInterface = new JavascriptInterface();
    try {
        ComponentName comp = new ComponentName(this, Dashboard.class);
        PackageInfo pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0);
        jsInterface.versionCode = pinfo.versionCode;
    } catch(android.content.pm.PackageManager.NameNotFoundException e) {
    }

    engine.addJavascriptInterface(jsInterface, "Title");
    engine.loadUrl(BASE_URL);
}

private WebView getEngine() {
    return (WebView) findViewById(R.id.web_engine);
}

public void onBackPressed() {
    WebView engine = getEngine();
    String url = engine.getUrl(); 
    if (jsInterface.modalIsVisible) {
        engine.loadUrl("javascript: android.hideModal();");
    } else if (url != null && (
            url.equals(BASE_URL) ||
            url.equals(DASHBOARD_URL) ||
            !engine.canGoBack())) {
        // exit
        super.onBackPressed();
    } else {
        // go back a page, like normal browser
        engine.goBack();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
}

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem prefs = menu.findItem(R.id.preferences_menuitem);
    if (prefs != null) {
        prefs.setVisible(jsInterface.enablePreferencesMenu);
    }
    super.onPrepareOptionsMenu(menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.dashboard_menuitem:
        getEngine().loadUrl(DASHBOARD_URL);
        return true;
    case R.id.refresh_menuitem:
        getEngine().reload();
        return true;
    case R.id.preferences_menuitem:
        getEngine().loadUrl("javascript: android.showPreferences()");
        return true;
    case R.id.contact_menuitem:
        AboutBox.Show(Dashboard.this);
        return true;
    case R.id.share_url_menuitem:
        final String url = (jsInterface.urlForSharing != null
                            ? jsInterface.urlForSharing
                            : getEngine().getUrl());
        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("text/plain");
        i.putExtra(Intent.EXTRA_SUBJECT, "Android URL");
        i.putExtra(Intent.EXTRA_TEXT, url);
        startActivity(Intent.createChooser(i, "Share"));
    default:
        return super.onOptionsItemSelected(item);
    }
}

private class FixedWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.startsWith(BASE_URL) || url.startsWith("javascript:")) {
            // handle by the WebView
            return false;
        } else if (url.startsWith("mailto:")) {
            MailTo mt = MailTo.parse(url);
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("message/rfc822");
            i.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
            i.putExtra(Intent.EXTRA_SUBJECT, mt.getSubject());
            i.putExtra(Intent.EXTRA_CC, mt.getCc());
            i.putExtra(Intent.EXTRA_TEXT, mt.getBody());
            view.getContext().startActivity(i);
            view.reload();
            return true;
        } else {
            // Use external browser for anything not on this site
            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            view.getContext().startActivity(i);
            return true;
        }
    }
}

// The methods of JavascriptInterface are called from javascript.
// The attributes are accessed from the Dashboard class.
// This is deliberately a dumb container class to stop possible
// security issues of javascript controlling Java app.
final class JavascriptInterface {
    public boolean enablePreferencesMenu = false;
    public boolean modalIsVisible = false;
    public int versionCode = 0;
    public String urlForSharing = null;

    public void setEnablePreferencesMenu() {
        enablePreferencesMenu = true;
    }

    public void setModalIsVisible(boolean visible) {
        modalIsVisible = visible;
    }

    // This is useful for allowing the web site to be able to detect
    // old app versions and prompt the user to upgrade.
    public int getVersionCode() {
        return versionCode;
    }

    public void setUrlForSharing(String url) {
        urlForSharing = url;
    }
}

}

如果设备未连接到互联网,我应该在哪里编辑以显示没有网络连接消息?

2 个答案:

答案 0 :(得分:1)

首先,您需要检查互联网是否已连接到您的设备,您可以使用以下方法检查互联网连接

public static boolean checkNetworkConnection(Context _context){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
          return false;
    }

此方法将返回true[If internet is connected]false[if not connected]

根据该真值或假值,您可以决定是显示html页面还是web页面

现在问题是,如果你想显示本地文件夹中的网页,那么就像你这样做

您可以加载本地html文件,如下所示

WebView lWebView = (WebView)findViewById(R.id.webView);
File lFile = new File(Environment.getExternalStorageDirectory() + "<FOLDER_PATH_TO_FILE>/<FILE_NAME>");
lWebView.loadUrl("file:///" + lFile.getAbsolutePath());

如果你想要显示比{1}}页面更多的内容而不是你需要做一些R&amp; D任务。

现在,如果互联网已连接,您可以使用以下方法在webview上显示网页

html

我希望你理解所有的解释

答案 1 :(得分:0)

您可以使用以下方法检查互联网连接:

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

此处有更多信息:http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

要显示HTML而不加载来自互联网:

webview.loadData("<b>Connection not availeable</b>", "text/html", null);

更多信息:http://developer.android.com/reference/android/webkit/WebView.html#loadData(java.lang.String,java.lang.String,java.lang.String)