是否可以执行将执行HTTP请求的启动画面,如果此请求执行时间过长,即7-10秒,则中止请求并跳转到主活动?
以下代码就是我所做的,但它不起作用 - 超时不起作用,HTTP请求和跳转正在运行。据我了解,可以延迟使用AsyncTask
的{{1}}方法或处理程序。 get()
方法应该在单独的线程中,但它不起作用。怎么做这个任务?
修改
Get()
}
答案 0 :(得分:5)
因为您正在尝试在doInBackground
内再次启动AsyncTask时仍在运行。更改代码以使其正常工作:
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
downloadFAQ.execute().get(2000, TimeUnit.MILLISECONDS);
SplashActivity.thisrunOnUiThread(new Runnable() {
public void run() {
// start Activity here
Intent i = new Intent(SplashActivity.this,
TabsActivity.class);
SplashActivity.this.startActivity(i);
SplashActivity.this.finish();
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
并且您需要从doInBackground方法中删除downloadFAQ.get(2000, TimeUnit.MILLISECONDS);
将AsyncTask更改为
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
protected void onPostExecute(Void result) {
}
}
答案 1 :(得分:0)
考虑使用asyncTask状态: AsyncTask.Status