我已经在这方面工作了几天了。我刚开始使用Android。我有两个问题。我想检查互联网是否可用。如果它是启动webView,如果没有发出警报并阻止webView加载。我试过这个,但如果没有互联网连接(例如飞机模式),它会强行关闭。如何让它发送消息并停止加载webview。还有一种方法可以连续检查连接,以便在网页断开连接时不显示网页404?
这是我的代码。
public class MainActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = cm
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo datac = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((wifi != null & datac != null)
&& (wifi.isConnected() | datac.isConnected())) {
setContentView(R.layout.activity_main);
}else{
//no connection
Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG);
toast.show();
}
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://mysite.com/?ma=1");
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("mysite.com")) {
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.logout:
finish();
return true;
}
return false;
}
}
编辑:添加了错误 具体来说,在显示Toast表示没有互联网连接后,按下后会出现这些错误。如果我在toast消息后使用后退按钮并且错误在下面,则崩溃。
04-07 14:40:38.664: E/AndroidRuntime(15173): FATAL EXCEPTION: main
04-07 14:40:38.664: E/AndroidRuntime(15173): java.lang.NullPointerException
04-07 14:40:38.664: E/AndroidRuntime(15173): at com.mysite.testapp.MainActivity.onKeyDown(MainActivity.java:67)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.view.KeyEvent.dispatch(KeyEvent.java:2705)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.app.Activity.dispatchKeyEvent(Activity.java:2401)
04-07 14:40:38.664: E/AndroidRuntime(15173): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2007)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3813)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3761)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2926)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.os.Handler.dispatchMessage(Handler.java:99)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.os.Looper.loop(Looper.java:137)
04-07 14:40:38.664: E/AndroidRuntime(15173): at android.app.ActivityThread.main(ActivityThread.java:4918)
04-07 14:40:38.664: E/AndroidRuntime(15173): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 14:40:38.664: E/AndroidRuntime(15173): at java.lang.reflect.Method.invoke(Method.java:511)
04-07 14:40:38.664: E/AndroidRuntime(15173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
04-07 14:40:38.664: E/AndroidRuntime(15173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
04-07 14:40:38.664: E/AndroidRuntime(15173): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:24)
要检查网络连接可用性,请使用以下
public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}
在您的活动中
if(CheckNetwork.isInternetAvailable(Activity.this)) //returns true if internet available
{
//do something. loadwebview.
}
else
{
Toast.makeText(Activity.this,"No Internet Connection",1000).show();
}
按后退按钮
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(mWebView.canGoBack() == true){
mWebView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
更新:如果您需要始终检查网络连接可用性,则系统会在连接发生变化或连接断开时广播事件。您可以通过注册广播来捕获活动中的广播。但是你需要在不需要时取消注册。
以下链接就是一个例子。
Android service to check internet connectivity?
或者您可以使用在后台检查互联网连接的服务。但是,您需要在不需要时销毁服务。但服务用于在后台运行长时间运行的操作
更新2:
尝试以下方法。我测试过了。它适用于我的三星Galaxy S3。
在清单
中添加这些权限 <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
您的activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:id="@+id/wv"/>
</RelativeLayout>
您的活动
public class MainActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.wv);
if(CheckNetwork.isInternetAvailable(MainActivity.this))
{
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
// webView = (WebView) findViewById(R.id.wv);
// webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
MainActivity.this.setProgress(progress * 1000);
}
});
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(MainActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl("http://slashdot.org/");
}
else{
//no connection
Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG);
toast.show();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else
{
finish();
}
return super.onKeyDown(keyCode, event);
}
}
答案 1 :(得分:1)
为了防止应用程序崩溃,请将定义WebView
的所有代码移动到您检查互联网连接的位置,如下所示:
....
if ((wifi != null & datac != null) && (wifi.isConnected() || datac.isConnected()))
{
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://mysite.com/?ma=1");
}
else
{
//no connection
Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection",Toast.LENGTH_LONG);
toast.show();
}
.....
现在,如果你的应用程序经常需要互联网连接,我建议你创建一个Service
来不断检查这个连接,当它存在时,这个Service
会向收听广播方。
<强>更新强>
由于此行,您收到错误:
webView.goBack();
如果没有互联网连接并且没有实例化WebView,那么你就不能在其中使用goBack(),因为这是null,在这里你需要检查:
if (webView != null)
{
webView.goBack();
}
设置替代视图并不困难: 1.打开可视编辑器,创建一个与webview相同大小的ImageView。 2.然后这样做:
....
if ((wifi != null & datac != null) && (wifi.isConnected() || datac.isConnected()))
{
imageView.setVisibility(View.GONE);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://mysite.com/?ma=1");
}
else
{
imageView.setVisibility(View.VISIBLE);
//no connection
Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection",Toast.LENGTH_LONG);
toast.show();
}
.....
当然,在你可以操作它之前,你必须首先通过id找到这个视图。