简体   繁体   English

如果没有可用的互联网连接,则我的应用中存在ANR

[英]ANR in my app if no internet connection available

I am having a little problem, I can connect to internet and read an url easily. 我有一个小问题,我可以连接到互联网并轻松阅读网址。 but if no internet connection is available I get ANR and my app is force closed ! 但是如果没有可用的互联网连接,我会收到ANR,并且我的应用已强制关闭! Any help ? 有什么帮助吗?

    try {
        URL Url = new URL(url); 
        HttpURLConnection httpCon = (HttpURLConnection) Url.openConnection();


        httpCon.setRequestMethod("GET");
        //httpCon.setReadTimeout(2000);
        Log.v("Parser","before connect");
        //httpCon.connect(); 
        int response;
            response = httpCon.getResponseCode();

        } catch (Exception urlExc) {
            Log.v("Parser","into parser error" + urlExc.getCause());
            return false;
        }

When no connection available, it is forced closed instead of going to catch() 如果没有可用的连接,则将其强制关闭而不是catch()

Are you doing this in the main UI thread? 您是在主UI线程中执行此操作吗? If so, don't. 如果是这样,那就不要。 Investigate one of the many ways of using background threads. 研究使用后台线程的多种方法之一。

See this Painless Threading article for a discussion. 请参阅这篇无痛线程文章以进行讨论。 It says: 它说:

Specifically, if everything is happening in a single thread, performing long operations such as network access or database queries on the UI thread will block the whole user interface. 具体来说,如果所有事情都发生在单个线程中,则在UI线程上执行长时间的操作(如网络访问或数据库查询)将阻塞整个用户界面。 No event can be dispatched, including drawing events, while the long operation is underway. 进行长时间操作时,不能调度任何事件,包括绘图事件。 From the user's perspective, the application appears hung. 从用户的角度来看,该应用程序似乎已挂起。 Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. 更糟糕的是,如果UI线程被阻塞了几秒钟(当前大约5秒钟),则会向用户显示臭名昭著的“应用程序无响应”(ANR)对话框。

( ASyncTask might be a good starting point.) ASyncTask可能是一个很好的起点。)

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

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