如果在Android中打开手机或wifi,如何检查互联网是否可用

时间:2014-02-14 13:40:28

标签: android

我有两项活动

第一个名为:MainActivity

第二个命名为:MountLebanonActivity

在第二个活动中,我将此代码用于检索网站上的文本

private TextView txtdata;
final String textSource = "http://orthodoxprayers.yolasite.com/resources/saint_elie_sinelfil.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy); 
    setContentView(R.layout.activity_mount_lebanon);
    txtdata = (TextView)findViewById(R.id.txtdata);
    new MyTask().execute();
    URL textUrl;

       try {
        textUrl = new URL(textSource);

        BufferedReader bufferReader 
         = new BufferedReader(new InputStreamReader(textUrl.openStream()));

        String StringBuffer;
        String stringText = "";
        while ((StringBuffer = bufferReader.readLine()) != null) {
         stringText += StringBuffer;   
        }
        bufferReader.close();

        txtdata.setText(stringText);
       } catch (MalformedURLException e) {
        e.printStackTrace();
        txtdata.setText(e.toString());   
       } catch (IOException e) {
        e.printStackTrace();
        txtdata.setText(e.toString());   
       }

   }

   private class MyTask extends AsyncTask<Void, Void, Void>{

    String textResult;

    @Override
    protected Void doInBackground(Void... params) {

        URL textUrl;

        try {
         textUrl = new URL(textSource);

         BufferedReader bufferReader 
          = new BufferedReader(new InputStreamReader(textUrl.openStream()));

         String StringBuffer;
         String stringText = "";
         while ((StringBuffer = bufferReader.readLine()) != null) {
          stringText += StringBuffer;   
         }
         bufferReader.close();

         textResult = stringText;
        } catch (MalformedURLException e) {
         e.printStackTrace();
         textResult = e.toString();   
        } catch (IOException e) {
         e.printStackTrace();
         textResult = e.toString();   
        }

     return null;

    }

    @Override
    protected void onPostExecute(Void result) {

     txtdata.setText(Html.fromHtml(textResult));
     super.onPostExecute(result);   
    }

   }    

在第一个活动中,我将此代码放在按钮的onclick事件中

    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()
            && (wifi.isAvailable() | datac.isAvailable()))) {
            //connection is available
        Intent intent_main_time = new Intent(MainActivity.this,
                MountLebanonActivity.class);
        startActivity(intent_main_time);
        finish();
             }else{
            //no connection
              Toast toast = Toast.makeText(getBaseContext(), "No Internet",
            Toast.LENGTH_LONG);
    toast.show();  
            }

如果打开或关闭wifi或移动设备,此代码可以正常工作

但是如果我的wifi打开并且没有互联网连接这个代码不起作用因为我没有得到吐司但是第二个活动打开时出现错误代码java.net.connectesception:无法连接.. 。端口80连接失败econnrefused(连接被拒绝)

任何帮助?

1 个答案:

答案 0 :(得分:1)

你是对的。您提供的代码仅检查是否存在网络连接。检查是否存在活动Internet连接的最佳方法是尝试通过http连接到已知服务器。

public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
    }
} else {
    Log.d(LOG_TAG, "No network available!");
}
return false;
}