[英]How to stop async task executions when back button is pressed
請我有一個包含異步任務方法的活動,即使用戶已從該頁面移動,此異步任務方法也會繼續在后台執行。 只要用戶按下后退按鈕或從該頁面移動到另一頁面,就有辦法停止異步任務執行。
以下是我嘗試過但它不起作用
private AsyncTask totalLikesAsync;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
context = this;
totalLikesAsync = new TotalLikes().execute(msgID);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
totalLikesAsync.cancel(true);
this.finish();
break;
case R.id.share:
new ShareImage().execute(msgImage);
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
private class TotalLikes extends AsyncTask<String, String, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... msgIDs) {
UserFunctions userFunction = new UserFunctions();
String msgsID = msgIDs[0];
JSONObject json=null;
if(!isCancelled()){
//This gets all the information unread from the server
json = userFunction.TotalLikes(context, msgsID);
}
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
if (json != null) {
...
} else {
...
}
}
}
UPDATE
在測試下面的所有答案后,即使按下后退按鈕,它們都允許在異步任務中執行doinbackground
。 我想要一個按下后退按鈕后取消背景的情況。
@Override
public void onBackPressed() {
super.onBackPressed();
if (totalLikesAsync != null && totalLikesAsync.getStatus().equals(AsyncTask.Status.RUNNING)) {
totalLikesAsync.cancel(true);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
totalLikesAsync.cancel(true);
}
@Override
public void onBackPressed() {
TotalLikes.cancel(true);
// If you want to finish the activity you can use below code
// finish();
super.onBackPressed();
}
自己處理onBackPressed()方法:
@Override
public void onBackPressed()
{
if (totalLikesAsync != null)
totalLikesAsync.cancel(true);
super.onBackPressed();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.