问题
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