受到这个的启发终于结局了如何在AsyncTask运行中终止其操作。
单纯的onCancelled(true)是不行的
下面把代码贴出来~实现了登陆功能。
AsyncTask简介,它使创建需要与用户界面交互的长时间运行的任务变得更简单。相对来说AsyncTask更轻量级一些,适用于简单的异步处理,不需要借助线程和Handler即可实现。
转自stackoverflow
001 | packagecom.isummation.exampleapp; |
003 | importjava.io.BufferedReader; |
004 | importjava.io.InputStreamReader; |
005 | importjava.net.URLEncoder; |
006 | importjava.net.UnknownHostException; |
008 | importorg.apache.http.HttpResponse; |
009 | importorg.apache.http.client.HttpClient; |
010 | importorg.apache.http.client.methods.HttpGet; |
011 | importorg.apache.http.impl.client.DefaultHttpClient; |
012 | importorg.apache.http.params.CoreProtocolPNames; |
013 | importorg.apache.http.protocol.BasicHttpContext; |
014 | importorg.apache.http.protocol.HttpContext; |
015 | importorg.json.JSONObject; |
017 | importandroid.app.Activity; |
018 | importandroid.app.Dialog; |
019 | importandroid.app.ProgressDialog; |
020 | importandroid.content.DialogInterface; |
021 | importandroid.content.DialogInterface.OnCancelListener; |
022 | importandroid.os.AsyncTask; |
023 | importandroid.os.Bundle; |
024 | importandroid.view.View; |
025 | importandroid.view.View.OnClickListener; |
026 | importandroid.widget.Button; |
027 | importandroid.widget.EditText; |
028 | importandroid.widget.Toast; |
030 | publicclassUserLoginextendsActivity { |
032 | privateEditText etUsername; |
033 | privateEditText etPassword; |
034 | privateProgressDialog progressDialog; |
035 | privatestaticfinalintPROGRESSDIALOG_ID =0; |
036 | privatestaticfinalintSERVER_ERROR =1; |
037 | privatestaticfinalintNETWORK_ERROR =2; |
038 | privatestaticfinalintCANCELLED =3; |
039 | privatestaticfinalintSUCCESS =4; |
040 | privateString ServerResponse; |
041 | privateLoginTask loginTask; |
044 | publicvoidonCreate(Bundle savedInstanceState) { |
045 | super.onCreate(savedInstanceState); |
046 | setContentView(R.layout.login); |
048 | etUsername = (EditText) findViewById(R.id.txt_username); |
049 | etPassword = (EditText) findViewById(R.id.txt_password); |
051 | Button login_button = (Button)this.findViewById(R.id.login_button); |
052 | login_button.setOnClickListener(newOnClickListener() { |
053 | publicvoidonClick(View viewParam) { |
054 | if(etUsername.getText().toString().length() ==0 |
055 | || etPassword.getText().toString().length() ==0) { |
056 | Toast.makeText(getApplicationContext(), |
057 | "Please enter username and password", |
058 | Toast.LENGTH_SHORT).show(); |
062 | showDialog(PROGRESSDIALOG_ID); |
068 | protectedDialog onCreateDialog(intid) { |
070 | casePROGRESSDIALOG_ID: |
071 | removeDialog(PROGRESSDIALOG_ID); |
076 | progressDialog = ProgressDialog.show(UserLogin.this,"Authenticating", |
077 | "Please wait...",true,true,newOnCancelListener(){ |
079 | publicvoidonCancel(DialogInterface dialog) { |
082 | if(loginTask !=null&& loginTask.getStatus() != AsyncTask.Status.FINISHED) |
083 | loginTask.cancel(true); |
088 | progressDialog =null; |
090 | returnprogressDialog; |
094 | protectedvoidonPrepareDialog(intid, Dialog dialog) { |
096 | casePROGRESSDIALOG_ID: |
099 | if(loginTask !=null&& loginTask.getStatus() != AsyncTask.Status.FINISHED) |
100 | loginTask.cancel(true); |
101 | loginTask =newLoginTask(); |
106 | classLoginTaskextendsAsyncTask<Void, Integer, Void> { |
108 | protectedVoid doInBackground(Void... unused) { |
110 | ServerResponse =null; |
111 | HttpClient httpClient =newDefaultHttpClient(); |
112 | HttpContext localContext =newBasicHttpContext(); |
113 | HttpGet httpGet =newHttpGet( |
114 | getString(R.string.WebServiceURL) |
115 | +"/cfc/iphonewebservice.cfc?returnformat=json&method=validateUserLogin&username=" |
116 | + URLEncoder.encode(etUsername.getText() |
119 | + URLEncoder.encode(etPassword.getText() |
120 | .toString(),"UTF-8")); |
121 | httpClient.getParams().setParameter( |
122 | CoreProtocolPNames.USER_AGENT,"Some user agent string"); |
134 | publishProgress(CANCELLED); |
137 | HttpResponse response = httpClient.execute(httpGet, |
140 | BufferedReader reader =newBufferedReader( |
141 | newInputStreamReader( |
142 | response.getEntity().getContent(),"UTF-8")); |
143 | ServerResponse = reader.readLine(); |
144 | publishProgress(SUCCESS); |
145 | }catch(UnknownHostException e) { |
146 | removeDialog(PROGRESSDIALOG_ID); |
148 | publishProgress(NETWORK_ERROR); |
149 | }catch(Exception e) { |
150 | removeDialog(PROGRESSDIALOG_ID); |
152 | publishProgress(SERVER_ERROR); |
158 | protectedvoidonProgressUpdate(Integer... errorCode) { |
159 | switch(errorCode[0]) { |
161 | removeDialog(PROGRESSDIALOG_ID); |
162 | Toast.makeText(getApplicationContext(),"Cancelled by user", |
163 | Toast.LENGTH_LONG).show(); |
166 | removeDialog(PROGRESSDIALOG_ID); |
167 | Toast.makeText(getApplicationContext(),"Network connection error", |
168 | Toast.LENGTH_LONG).show(); |
171 | removeDialog(PROGRESSDIALOG_ID); |
172 | Toast.makeText(getApplicationContext(),"Server error", |
173 | Toast.LENGTH_LONG).show(); |
176 | removeDialog(PROGRESSDIALOG_ID); |
178 | if(ServerResponse !=null) { |
179 | JSONObject JResponse =newJSONObject(ServerResponse); |
180 | String sMessage = JResponse.getString("MESSAGE"); |
181 | intsuccess = JResponse.getInt("SUCCESS"); |
187 | UserLogin.this.finish(); |
193 | Toast.makeText(getApplicationContext(), sMessage, |
194 | Toast.LENGTH_SHORT).show(); |
198 | Toast.makeText(getApplicationContext(),"Server error", |
199 | Toast.LENGTH_LONG).show(); |
207 | protectedvoidonPostExecute(Void unused) { |
213 | protectedvoidonDestroy(){ |
215 | if(loginTask !=null&& loginTask.getStatus() != AsyncTask.Status.FINISHED) |
216 | loginTask.cancel(true); |
原文出处:http://www.ericyue.info/archive/stop-asynctask#more-1117