当没有可用的互联网连接时强制关闭应用

时间:2013-03-31 11:09:56

标签: android

我知道之前可能已经问过这个问题,但我无法弄清楚如何使用这些答案让它们与我的应用程序一起使用。

我想在应用用户打开应用时检查是否有互联网连接。我找到了一些方法来检查,但我对android开发完全是新手,我只是不知道该怎么做。这是我目前的申请文件:

package com.pocket.line;

import com.pocket.line.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class AndroidMobileAppSampleActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    WebView mainWebView = (WebView) findViewById(R.id.mainWebView);

    WebSettings webSettings = mainWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mainWebView.setWebViewClient(new MyCustomWebViewClient());
    mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

    mainWebView.loadUrl("http://www.google.com/");
}

private class MyCustomWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}
}

如果没有连接,我想强制关闭应用,并显示提醒。我找到的代码片段可以检查:

    public boolean hasActiveInternetConnection()
     {
    try
    {
        HttpURLConnection urlc = (HttpURLConnection) 
        (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(4000);
        urlc.setReadTimeout(4000);
        urlc.connect();
        networkcode2 = urlc.getResponseCode();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e)
    {
        Log.i("warning", "Error checking internet connection", e);
        return false;
    }

    } 

我只是不知道我需要更改该代码的哪些部分才能使其与我的应用程序一起使用。任何帮助将不胜感激!

清单文件

 <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.pocket.line" android:versionCode="3"
  android:versionName="1.2">
 <uses-sdk android:minSdkVersion="11" />

 <uses-permission android:name="android.permission.INTERNET"/>

 <application android:icon="@drawable/ic_launcher" android:label="Pocket Line">
    <activity android:name="com.pocket.line.AndroidMobileAppSampleActivity"
              android:label="Pocket Line">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
</manifest>

3 个答案:

答案 0 :(得分:4)

我认为你还没有在AndroidManifest.xml中声明活动

这样做如果此活动是应用程序的启动器。

<activity
   android:name=".AndroidMobileAppSampleActivity"
   android:label="@string/title_activity" >
     <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
     </intent-filter>
</activity>

如果此活动不是启动器。

<activity
   android:name=".AndroidMobileAppSampleActivity"
   android:label="@string/title_activity" >
</activity>

而不是检查互联网连接,而不是这样。

/**
 * This method check mobile is connected to network.
 * @param context
 * @return true if connected otherwise false.
 */
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(conMan.getActiveNetworkInfo() != null && conMan.getActiveNetworkInfo().isConnected())
        return true;
    else
        return false;
}

并在AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

并使用以下代码检查:

if(!isNetworkAvailable(this)) {
   Toast.makeText(this,"No Internet connection",Toast.LENGTH_LONG).show();
   finish(); //Calling this method to close this activity when internet is not available.
}

答案 1 :(得分:1)

像这样检查

 if(hasActiveInternetConnection()){
        mainWebView.loadUrl("http://www.google.com/");
    }else{
        Log.d("TAG","No Internet connection");
    }

希望这会对你有所帮助。

答案 2 :(得分:1)

还有另一种简单的方法

public class MyActivity extends Activity {

    // flag for Internet connection status
    Boolean isInternetPresent = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

                // get Internet status
                isInternetPresent = isConnectingToInternet;

                if (!isInternetPresent) {
                    showAlertDialog(MyActivity.this, "No Internet Connection",
                            "You don't have internet connection.", false);
                }

    }


 /**
    * check the Internet connection and return true or false
    * 
    * @return
    */
   public boolean isConnectingToInternet() {
      ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext()
            .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;

   }



    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
        alertDialog.setIcon(R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
             finished();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}