[英]off AsyncTask if loading more than a certain time(android)
对不起我的英语不好。 如果要在一定时间内(在我的情况下,超过1秒钟)继续加载AsyncTask,我想做的一切都被取消,并且向用户显示一条消息“请检查Internet”,我有一条消息显示,但是ProgressDialog继续运行。
SendRequestAutorization sendAvtoriz = new SendRequestAutorization ();
//code
try {
sendAvtoriz.execute(
new String[]{login.getText().toString(), password.getText().toString()}).get(1, TimeUnit.SECONDS);
} catch(Exception e) {
Log.e("Avtorization", e.toString());
Toast.makeText(getApplicationContext(), "Please check the Internet", Toast.LENGTH_SHORT).show();
sendAvtoriz.cancel(true);
}
//code
private class SendRequestAutorization extends AsyncTask<String, String, String> {
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Avtorization.this);
pDialog.setMessage("Authorization");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... params) {
//code
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
我没事吧 我需要另一个ProgressDialog,对吗?
UDP:
理想情况下,这就是我要执行的操作:如果在应用程序中单击按钮“ avtorization”,则显示动画加载(AsyncTask工作),如果加载时间超过5秒,则显示消息“请检查Internet”,否则我将输入我的个人资料。 现在我有:如果我没有连接互联网,则单击“ avtorization”按钮5秒未显示任何内容,显示快速加载动画并输入配置文件,如果我没有Internet连接并单击“ avtorization”,则没有显示5秒,然后显示“请检查Internet”
现在是我的代码:
private Button logInn;
private SendRequestAutorization sendAvtoriz;
ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p_avtorization);
logInn = (Button) findViewById(R.id.createAccount);
sendAvtoriz = new SendRequestAutorization();
logInn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pDialog = new ProgressDialog(Avtorization.this);
pDialog.setMessage("Authorization");
pDialog.setCancelable(false);
pDialog.show();
try {
sendAvtoriz.execute(
new String[]{login.getText().toString(), password.getText().toString()}).get(5, TimeUnit.SECONDS);
} catch(Exception e) {
Log.e("Avtorization", e.toString());
Toast.makeText(getApplicationContext(), "Please check the Internet", Toast.LENGTH_SHORT).show();
sendAvtoriz.cancel(true);
pDialog.dismiss();
}
}
}
//code
private class SendRequestAutorization extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
//code
return null;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
您可以通过超时从AsyncTask获取结果,查看方法get(长超时,TimeUnit单位)
此方法阻止UI线程,因此在这种情况下最好不要调用get()方法,而要创建TimerTask,如果它仍在工作,它将在5秒后取消AsyncTask。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.