4

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

当应用程序的用户打开应用程序时,我想检查是否有互联网连接。我找到了一些检查方法,但我对 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>
4

3 回答 3

6

我认为您尚未在 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.
}
于 2013-03-31T11:20:31.677 回答
1

像这样检查

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

希望这会帮助你。

于 2013-03-31T11:21:10.893 回答
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();
    }
}
于 2013-03-31T11:28:48.693 回答