许多具有不同延迟的 postDelayed 处理程序(大约 2.000)

Many postDelayed handlers with different delays (around 2.000)

我的应用程序接收消息并且必须一个接一个地安排多个回复,每个回复都有不同的延迟。有大约 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
         }
}

您可以改用 thread.sleep(毫秒)。它会延迟特定时间的线程。

 @Override
        public void run()
        {
            while (!Thread.interrupted())
                try
                {
                    Thread.sleep(1000);
                    MainActivity.this.runOnUiThread(new Runnable()
                    {

                        @Override
                        public void run()
                        {
                            ////
                        }
                    });
                }
                catch (InterruptedException e)
                {

                }
        }
    })).start();