0

我想不断检查互联网连接并更改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;
    }
}
4

1 回答 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;
 }
于 2013-03-02T18:11:32.550 回答