问题描述
我的应用程序收到消息,并且必须安排一个又一个的多个回复,每个回复都具有不同的延迟。 处理大约2000个具有不同延迟的延迟任务的最佳方法是什么? 由于资源有限,Android无法同时运行太多处理程序。
有任何想法吗?
提前致谢。
代码简化:
class TimedTask extends TimerTask { //runs every 10 seconds and checks for new contacts in queue to reply to (contacts can go up to 500 ones)
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(SendMessagesService.this);
String contacts = sp.getString("contacts", ""); //queued by another Thread
String contacts_array[] = contacts.split(",");
for (String contact : contacts_array) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
String message = sp.getString("message1",""); //there are different messages with different delays, depending on which were already sent
ReceiveContactsAdapter mDbHelper = new ReceiveContactsAdapter(SendMessagesService.this);
mDbHelper.open();
mDbHelper.sendMessages(message, contact);
mDbHelper.close();
}
}, delay); //delay depends on which message will be sent
}
}
1楼
您可以改用thread.sleep(milisec)。 它将线程延迟特定的时间。
@Override
public void run()
{
while (!Thread.interrupted())
try
{
Thread.sleep(1000);
MainActivity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
////
}
});
}
catch (InterruptedException e)
{
}
}
})).start();