Non responsive app when downloading lots of data

梦想的初衷 提交于 2019-12-13 09:11:30

问题


I have an app that has to download a few MB (1MB - 10MB) of data from a server on app startup.

The problem is that the app:

  • doesn't show the main TextView before starting the download (the screen stays black)

  • is more or less unresponsive

Here is the code:

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DoIt();
    }

    private void DoIt() {

        HttpClient httpClient = new DefaultHttpClient();

        TextView tv = (TextView)findViewById(R.id.textView);
        tv.setText("Starting app...");

        try {        
            for (int i=1; i<100; i++) {
                HttpPost request2 = new HttpPost("http://192.168.1.12:3000/bytes/data" + i);            
                HttpResponse response2 = httpClient.execute(request2);

               // Do something with data. In some cases, it has to download 1MB data
            } 
        }

        // catch + finally ...
    }
}

How to prevent the app to be unresponsive?


回答1:


Your app become irresponsible because you are downloading files in main thread you should use background thread like this

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv = (TextView)findViewById(R.id.textView);
    tv.setText("Starting app...");

    new Thread(new Runnable() {
        @Override
        public void run() {
            DoIt();
        }
    }).start();

}

 private void DoIt() {

    HttpClient httpClient = new DefaultHttpClient();

    try {        
        for (int i=1; i<100; i++) {
            HttpPost request2 = new HttpPost("http://192.168.1.12:3000/bytes/data" + i);            
            HttpResponse response2 = httpClient.execute(request2);

           // Do something with data. In some cases, it has to download 1MB data
        } 
    }

    // catch + finally ...
}

I think this should work



来源:https://stackoverflow.com/questions/47743565/non-responsive-app-when-downloading-lots-of-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!