我正在寻找检查数据连接是启用还是禁用的方法。 如果数据启用,则在webView中打开一个链接,否则吐司(数据被禁用)。
在我处理webview的代码下面
public class Question_web extends Activity { /** 在第一次创建活动时调用。 * /
WebView webview;
ProgressBar progressBar;
int a;
String value;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webcontent);
value = getIntent().getExtras().getString("url");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
WebView engine = (WebView) findViewById(R.id.webviews);
engine.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
Toast.makeText(getBaseContext(), "downloading", Toast.LENGTH_SHORT).show();
i.setData(Uri.parse(url));
startActivity(i);
}
});
engine.setWebViewClient(new FixedWebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progressBar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url)
{
progressBar.setVisibility(View.GONE);
}
});
engine.getSettings().setJavaScriptEnabled(true);
engine.loadUrl(value);
}
public void onBackPressed() {
WebView engine = (WebView) findViewById(R.id.webviews);
String url = engine.getUrl();
if (url.equals(value) ||
url.equals(value)) {
// exit
super.onBackPressed();
} else {
// go back a page, like normal browser
engine.goBack();
}
}
private class FixedWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
答案 0 :(得分:1)
我们可以使用NetworkInfo类的getActiveNetworkInfo()和isConnected()来检查网络连接是否可用。
此示例可在Android doc上找到,
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
// display error
}
请记住在清单中添加权限。按照步骤tutorial执行此步骤。