postDelayed
方法run
方法中启动AsyncTask onPostExecute
中,再次调用Handler对象的postDelayed
onResume
中,调用Handler对象的post
方法onPause
中,调用Handler对象的removeCallbacks
以删除邮件队列中Runnable的待处理帖子onPause
中删除了Runnable的待处理帖子,仍然会发生当前运行的执行其doInBackground
方法的AsyncTask在其onPostExecute
时将新的Runnable添加到队列中已启动(基本上在removeCallbacks
onPause
后不久)
shouldPoll
已添加到活动onResume
中设置为true,在onPause
onPostExecute
中,我检查shouldPoll
是否为真,只在那种情况下调用Handler对象的postDelayed
shouldPoll
变量吗?shouldPoll
变量)是否会发生某些事情;因此,以某种方式打破了AsyncTask的onPostExecute
boolean shouldPoll = false;
@Override
protected void onResume() {
super.onResume();
shouldPoll = true;
handler.post(pollURLRunnable);
}
@Override
protected void onPause() {
shouldPoll = false;
handler.removeCallbacks(pollURLRunnable);
super.onPause();
}
final Handler handler = new Handler();
final Runnable pollURLRunnable = new Runnable() {
public void run() {
PollingAsyncTask pollTimestampAsyncTask = new PollingAsyncTask();
pollTimestampAsyncTask.execute();
}
};
@Override
protected void onPostExecute(Result result) {
if (result != null) {
//Do something here
}
if (shouldPoll) {
handler.postDelayed(pollURLRunnable, 10000);
}
}
@Override
protected void onResume() {
super.onResume();
handler.post(startIntentServiceRunnable);
LocalBroadcastManager.getInstance(this).registerReceiver(statusBroadcastReceiver, new IntentFilter(Constants.MY_INTENT_FILTER));
}
@Override
protected void onPause() {
handler.removeCallbacks(startIntentServiceRunnable);
LocalBroadcastManager.getInstance(this).unregisterReceiver(statusBroadcastReceiver);
super.onPause();
}
final Handler handler = new Handler();
final Runnable startIntentServiceRunnable = new Runnable() {
public void run() {
Intent intent = new Intent(MainActivity.this, PollingService.class);
startService(intent);
}
};
final BroadcastReceiver statusBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//...
//Do something useful with the extras from intent here
//...
handler.postDelayed(startIntentServiceRunnable, 2000);
}
};
@Override
protected void onHandleIntent(Intent intent) {
//...
//Perform the polling and prepare results here
//...
broadcastResults();
}
private void broadcastResults() {
Intent intent = new Intent(Constants.MY_INTENT_FILTER);
//...
//Fill the intent extras with the data here
//...
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
答案 0 :(得分:1)
您可以通过在后台线程中运行hander来跳过AsyncTask。然后将工作移动到您发布给处理程序的runnable。
HandlerThread handlerThread = new HandlerThread("Background thread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());