为什么我的Android应用程序没有响应没有互联网连接?

时间:2015-06-17 20:15:24

标签: java android

我的应用从互联网上加载网页。当没有互联网连接时,它应该在webview中显示一条消息,它将再次连接到互联网,然后它应该尝试连接。但是,当我测试我的应用程序时,它没有显示ui,直到它有互联网连接。如何解决这个问题?

public class ma extends Fragment {

String dag = "1";
public WebView webViewma;

@Override
@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT > 8) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    View v = inflater.inflate(R.layout.ma, container, false);
    webViewma = (WebView) v.findViewById(R.id.webViewma);
    LaadRooster();
    return v;

}


public void LaadRooster() {


    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://foo.com/foo.php");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("dag", dag));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        String ret = EntityUtils.toString(response.getEntity());

        if (ret.startsWith("<!DOCTYPE html>")) {
            webViewma.loadData(ret, "text/html", null);



        } else {
            webViewma.loadData("No connection, trying again...", "text/html", null);
            LaadRooster();
        }
    } catch (IOException e) {
                        webViewma.loadData("No connection, trying again...", "text/html", null);
        LaadRooster();
    }
    }
}

1 个答案:

答案 0 :(得分:0)

您通过在主线程上执行HTTP请求来锁定UI。这需要移动到后台线程。

此外,检查设备是否以这种方式连接到互联网可能更容易:

public static boolean isConnected(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] allNetworks = cm.getAllNetworkInfo();

    for (NetworkInfo networkInfo : allNetworks) {
        if (networkInfo.isAvailable() && networkInfo.isConnected()) {
            return true;
        }

    }

    return false;
}

在清单中:

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