我已经在我的Android应用程序中实现了pull to refresh功能,我正在使用异步任务从用户拉动刷新时从服务器获取数据,但有时如果用户拉多次刷新,它会请求多个服务器所以重复的数据来了。我想避免这种情况,有什么方法可以检查异步任务是否正在运行,而不是再次运行相同的任务,直到它完成。
这是我调用异步任务的函数
public void refresh()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && !mSharedPreferences.getString("SN","").equals("") )
new getfeeds(getSherlockActivity()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (AppConstants.URL_FEED_MAIN+mSharedPreferences.getString("SN",null)+"/newer/0/"));
else if( !mSharedPreferences.getString("SN","").equals("") )
new getfeeds(getSherlockActivity()).execute((AppConstants.URL_FEED_MAIN+mSharedPreferences.getString("SN","")+"/newer/0/"));
}
我想在if和elseif语句中添加一个条件,以便在启动getfeeds异步任务之前检查一些条件,直到之前的getfeeds执行完成为止
答案 0 :(得分:0)
您可以使用以下状态:
if(yourTask.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(yourTask.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(yourTask.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
}
好吧试试这个:
public void refresh()
getfeeds mygetFeeds;//declare somewhere globally.
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && !mSharedPreferences.getString("SN","").equals("") )
new getfeeds(getSherlockActivity()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (AppConstants.URL_FEED_MAIN+mSharedPreferences.getString("SN",null)+"/newer/0/"));
else if( !mSharedPreferences.getString("SN","").equals("") )
if(mygetFeeds.getStatus() != AsyncTask.Status.RUNNING){
mygetFeeds = new getfeeds(getSherlockActivity());
mygetFeeds.execute((AppConstants.URL_FEED_MAIN+mSharedPreferences.getString("SN","")+"/newer/0/"));
}
}