简体   繁体   English

如何在应用程序的某些活动中解决诸如ANR之类的错误?

[英]How to resolve error like ANR in some activity of application?

I use Asynctask in my activity and i want to fetch html content of url using asynctask ...I am geeting html content successfully some time but sometime not happen anything..I cant't get content of html and its giving me black screen and give error of ANR... 我在活动中使用Asynctask,我想使用asynctask来获取url的html内容...我成功地对html内容进行了匹配,但是有时却什么也没发生。.我无法获取html的内容,并且它给了我黑屏,给出ANR错误...

My Activity coding... 我的活动编码...

public class ControlActivity extends AppCompatActivity {

    private static TextView txt1, txt2, txt3, txt4,txt5,txt6,txt7,txt8;
    private static SwitchCompat switch1, switch2, switch3, switch4, switch5, switch6, switch7, switch8;
  //  private static ImageView image1,image2,image3,image4,image5,image6,image7,image8;
    private static Button allon,alloff;
    String t1,t2,t3,t4,t5,t6,t7,t8;


    SwipeRefreshLayout swipe_container;

    JSONArray data = null;

    Handler mHandler;
    private static String ip,port,uname,password;
    private static Document htmlDocument;
    private static String htmlContentInStringFormat,content;
    private static String stringuri;
    private static List<String> listOfString = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control);
        new JSONAsyncTask().execute();
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Boolean doInBackground(String... urls) {
            StringBuffer stringBuffer = new StringBuffer("");
            BufferedReader bufferedReader = null;
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet();

                URI uri = new URI("http://"+ip+":"+port+"/index.htm");

                httpGet.setURI(uri);
                httpGet.addHeader(BasicScheme.authenticate(
                        new UsernamePasswordCredentials(uname, password),
                        HTTP.UTF_8, false));

                HttpResponse httpResponse = httpClient.execute(httpGet);

                // Read the contents of an entity and return it as a String.
                content = EntityUtils.toString(httpResponse.getEntity());

                Log.e("content: ", "> " + content);





              //  listOfString.clear();



                InputStream inputStream = httpResponse.getEntity().getContent();
                bufferedReader = new BufferedReader(new InputStreamReader(
                        inputStream));

                String readLine = bufferedReader.readLine();
                while (readLine != null) {
                    stringBuffer.append(readLine);
                    stringBuffer.append("\n");
                    readLine = bufferedReader.readLine();
                }

            }  catch (Exception e) {
                // TODO: handle exception
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        // TODO: handle exception
                    }
                }
            }
            return false;
        }

        protected void onPostExecute(Boolean result) {

            txt1=(TextView)findViewById(R.id.txt1);
            txt2=(TextView)findViewById(R.id.txt2);
            txt3=(TextView)findViewById(R.id.txt3);
            txt4=(TextView)findViewById(R.id.txt4);
            txt5=(TextView)findViewById(R.id.txt5);
            txt6=(TextView)findViewById(R.id.txt6);
            txt7=(TextView)findViewById(R.id.txt7);
            txt8=(TextView)findViewById(R.id.txt8);

            Document doc = Jsoup.parse(content);
            htmlContentInStringFormat = doc.title();

            Elements td=doc.getElementsByTag("td");
            //Log.e("td: ", "> " + td);

            String td1=td.toString();
            //  Log.e("td1: ", "> " + td1);

            Elements articles = doc.select("td");

            for (Element element : articles) {
                String content1 = element.text();
                Log.e("content1: ", "> " + content1);
                listOfString.add(content1);
                System.out.println(content1);
            }

            t1 = listOfString.get(26);
            t2 = listOfString.get(31);
            t3 = listOfString.get(36);
            t4 = listOfString.get(41);
            t5 = listOfString.get(46);
            t6 = listOfString.get(51);
            t7 = listOfString.get(56);
            t8 = listOfString.get(61);

            Log.e("t1: ", "> " + t1);
            Log.e("t2: ", "> " + t2);
            Log.e("t3: ", "> " + t3);
            Log.e("t4: ", "> " + t4);
            txt1.setText(t1);
            txt2.setText(t2);
            txt3.setText(t3);
            txt4.setText(t4);
            txt5.setText(t5);
            txt6.setText(t6);
            txt7.setText(t7);
            txt8.setText(t8);

        }
    }
}

and it give me roor like this.. 这样给我带来了回报。

在此处输入图片说明

Application Not Responding (ANR) - will occur if we are doing any heavy functionality along with UI modification in the Main(UI) Thread. 应用程序无响应(ANR) -如果我们在Main(UI)线程中做任何繁重的功能以及UI修改,就会发生。 If time consuming heavy computation occurs in UI thread, it will delay response to user actions, which may irritate user, and hence stop your process. 如果UI线程中进行了耗时的大量计算,它将延迟对用户操作的响应,这可能会激怒用户,从而停止您的进程。 Android versions above 2.3.3(Gingerbread) in fact strictly discourages heavy processing in UI thread and allows user to close the app with ANR dialog. 实际上,高于2.3.3(Gingerbread)的Android版本严格不鼓励在UI线程中进行繁重的处理,并允许用户使用ANR对话框关闭应用程序。

Solution - Run only UI components in Main Thread and move other computation to background thread. 解决方案 -仅在主线程中运行UI组件,并将其他计算移至后台线程。 In this case, move the parsing work to background thread and pass the parsed results to onPostExecute() call. 在这种情况下,将解析工作移至后台线程,并将解析的结果传递给onPostExecute()调用。

Note - In any situation in which your app performs a potentially lengthy operation, you should not perform the work on the UI thread, but instead create a worker thread and do most of the work there. 注意 -在任何情况下,如果您的应用程序可能执行冗长的操作,则不应在UI线程上执行工作,而应创建工作线程并在其中执行大部分工作。

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

相关问题 在 java intellij 中面临问题,例如在单击调试时出现一些错误,显示如何解决它 - Facing issue in java intellij like while clicking on debug some error is showing how to resolve it 如何解决 SensorEventListener 操作单独线程中出现的 ANR 问题? - How to resolve ANR problem occured in SensorEventListener operating separete thread? 如何解决某些文件处理失败的错误? - How to resolve the error some file crunching failed? 如何解决 Spring 应用程序中的数据源错误? - How to resolve DataSource Error in Spring Application? GLSurfaceView在活动被破坏后导致ANR - GLSurfaceView causing ANR after activity is destroyed 如何解决 Java 处理应用程序中的运行时错误? - How can i resolve Runtime Error in Java Processing Application? 如何解决错误:无法在 SpringBoot 应用程序中找到或加载主类 - How to resolve Error: Could not find or load main class in SpringBoot application 如何解决 Spring Boot 应用程序中与“Whitelabel Error Page”相关的问题 - How to resolve the problem related to "Whitelabel Error Page" in a Spring Boot application 如何解决 pom.xml - android eclipse 应用程序中的错误? - How to resolve error in pom.xml - android eclipse application? 应用程序或活动需要一些时间来加载 - Application or activity takes time to load some times
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM