我正在使用AsyncTask填充SQLite数据库。我正在从某个网页下载数据,并将其放入SQLite表中。问题是,我想要么下载100%的数据,要么不下载任何数据。因此,如果AsyncTask由于某种原因而中断,我想删除到目前为止已下载的所有数据。
这是我尝试执行的操作:
@Override
protected void onCancelled() {
super.onCancelled();
dbHandler.deleteFromDatabase(razred);
Log.i("TAG", "AsyncTask cancelled");
}
我以为如果AsyncTask以任何方式被中断,“ onCancelled”将执行,但不会。如果以任何方式取消了AsyncTask所做的数据,我该怎么办?(例如,活动暂停,活动被破坏,互联网连接中断等)
您的路线是正确的,但doInBackground()
您还需要专门致电isCancelled()
以检查是否已取消,然后从返回doInBackground()
。然后您的代码将正常工作。
请参阅AsyncTask
文档“取消任务”
这是文档中的引用,以方便参考:
可以通过调用随时取消任务
cancel(boolean)
。调用此方法将导致后续调用isCancelled()
返回true。调用此方法后,将在返回后调用onCancelled(Object)
,而不是。为了确保尽快取消任务,应始终定期检查的返回值,如果可能的话(例如在循环内)。onPostExecute(Object)
doInBackground(Object[])
isCancelled()
doInBackground(Object[])
编辑:每个请求,一些示例代码:
private class MyAsyncTask extends AsyncTask<Void,Void,Void> {
private SQLiteDatabase db;
@Override
protected void onPreExecute() {
// any kind of initialization or setup needed before the
// background thread kicks off. remember: this is still on
// on the main (UI) thread
// since youre doing DB I/O, Ill make believe Im initializing the DB here
db = DatabaseHelper.getInstance(MainActvity.this).getWritableDatabase();
}
/*
* The background thread to do your disk and network I/O. If you need
* to pass in any parameters, this is the first Void in the template
*/
@Override
protected Void doInBackground(Void... params) {
// other stuff you need to do in the background. Since you want an
// all-or-nothing type thing, we will use a transaction to manually
// control the db
db.beginTransaction();
try {
// do network I/O to retrieve what you need and then write to DB.
...
... // if theres a loop in here somewhere when reading the data, check !isCancelled() as part of the condition or as one of the first statements and then break
...
db.setTransactionSuccessful(); // assuming everything works, need to set
// this successful here at the end of the try
} catch (InterruptedException ie) { // or some other exception
cancel(true); // heres where you can call cancel() if youve been interrupted
} catch (IOException ioe) { // if your network connection has problems
cancel(true);
} finally {
db.endTransaction();
// other cleanup, like closing the HTTP connection...
// no need to close the DB if you implement it properly
}
return null; // if there was some return value, that would go here
}
@Override
protected void onCancelled(Void result) {
// depending on how you implement doInBackground(), you may not even need this,
// unless you have a lot of other "state" you need to reset aside from the DB transaction
}
@Override
protected void onPostExecute(Void result) {
// any other items to do on main (UI) thread after doInBackground() finishes
// remember, this only gets called if cancel() is not called!
}
}
希望有帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句