经常检查互联网连接,如果连接,运行代码(Android)

时间:2013-03-02 17:40:53

标签: android webview looper

我想不断检查互联网连接,如果连接出现或消失,请更改TextView。但是在我刷新应用程序之前,TextView不会改变。 这是我目前的代码:

    TextView offline;
    public void run() {
  try {
    Looper.prepare();

    new Handler();
        if(isInternetOn()) {
            swebview.reload();
            offline.setText(null);
            }else{
                swebview.reload();
                offline.setText("No Internet Connection!");
            }
    Looper.loop();
  } catch (Throwable t) {
    Log.d(TAG, "halted due to an error", t);
  }
}

isInternetOn()代码:

public final boolean isInternetOn() {
    ConnectivityManager connec =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    // ARE WE CONNECTED TO THE NET
    if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||
    connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTING ||
    connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING ||
    connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
    // MESSAGE TO SCREEN FOR TESTING (IF REQ)
    //Toast.makeText(this, connectionType + ” connected”, Toast.LENGTH_SHORT).show();
    return true;
    } else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED  ) {
    //System.out.println(“Not Connected”);
    return false;
    }
    return false;
    }
}

2 个答案:

答案 0 :(得分:0)

请继续关注此链接,我希望能否解决您的互联网连接问题,

Detect whether there is an Internet connection available on Android

答案 1 :(得分:0)

您可以尝试以下代码来不断检查互联网并更新文字视图

 TextView tvstatus;
 tvstatus=(TextView)findViewById(R.id.txtviewstatus);

   public static boolean hasConnection() {
ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
    Context.CONNECTIVITY_SERVICE);

NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
     Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("WifiNetwork kAvailable");

     return true;
}

NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {

  Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("MobileNetworkAvailable");

  return true;
}

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {

    Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("Network Available");

  return true;
}

return false;
 }