繁体   English   中英

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

[英]Why is my android app not responding when there is no internet connection?

我的应用程序从互联网加载网页。 如果没有互联网连接,它应该在Web视图中显示一条消息,即将再次连接到互联网,然后尝试连接。 但是当我测试我的应用程序时,直到它具有互联网连接,它才会显示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();
    }
    }
}

您正在通过在主线程上执行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" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM