是否可以执行将执行 HTTP 请求的启动画面,如果此请求执行时间过长,即 7-10 秒,则中止请求并跳转到主要活动?
下面的代码是我所做的,但它不起作用 - 超时不起作用,HTTP 请求和跳转正在起作用。据我了解,可以延迟使用AsyncTask
'get()
方法或处理程序。Get()
方法应该在单独的线程中,但它不起作用。这个任务怎么做?
编辑:
public class SplashActivity extends Activity {
private static final String TAG = "SplashActivity";
private Handler handler = new Handler();
private Runnable r;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
if (Helpers.isNetworkConnected(getApplicationContext())) {
Log.d(TAG, "Has Internet");
final DownloadFAQ downloadFAQ = new DownloadFAQ();
new Thread(new Runnable() {
public void run() {
try {
Log.d(TAG, "Timing...");
downloadFAQ.execute().get(1000, TimeUnit.MILLISECONDS);
SplashActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d(TAG, "redirect");
redirect();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
downloadFAQ.cancel(true);
Log.d(TAG, "Task has benn canceled");
if (downloadFAQ.isCancelled())
redirect();
}
}
}).start();
} else {
r = new Runnable() {
public void run() {
redirect();
}
};
handler.postDelayed(r, 2500);
}
}
private class DownloadFAQ extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
Log.d(TAG, "Execute task");
ServerAPI server = new ServerAPI(getApplicationContext());
server.serverRequest(ServerAPI.GET_FAQ, null);
return null;
}
}
private void redirect() {
Intent i = new Intent(SplashActivity.this, TabsActivity.class);
startActivity(i);
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(r);
}
}