平行倒数计时器

问题描述 投票:0回答:1

我对同时使用多个倒数计时器的最佳方法会有疑问。我已经在UI线程上执行此操作,并且正在更新许多组件(Textview,带有数据的rv,imageviews)。它有效,但是当我要切换即时通讯显示的“警报”时,我注意到ui有点滞后。

我还想使该警报在后台运行,并显示剩余时间的通知,因为我认为我永远无法使用我所做的此UI线程操作。

这将是正确的方法?

谢谢大家!

android multithreading service timer countdown
1个回答
0
投票

从任何service或任何intentserviceasynctask中,您都可以使用计时器线程(即您的情况下的倒数计时器):

public void Timer()
{
    new Thread(new Runnable()
    {
        public void run()
        {
            while (IsOnGoing)
            {
                try
                {
                    TimeUnit.SECONDS.sleep(1);
                    seconds++;

                    int hour = seconds/3600;
                    int remaining = seconds%3600;

                    int minutes = remaining/60;
                    int seconds = remaining%60;

                    String hourString = (hour<10 ? "0" : "")+hour;
                    String minutesString = (minutes<10 ? "0" : "")+minutes;
                    String secondsString = (seconds<10 ? "0" : "")+seconds;

                    String InCallDuration = hourString + " : " + minutesString + " : " + secondsString;

                    Intent intent = new Intent("ticks");
                    intent.setPackage(getPackageName());
                    intent.putExtra("InCallDuration", InCallDuration);
                    getApplicationContext().sendBroadcast(intent);

                    Log.d("InCallService :", "InCallDuration"+ InCallDuration+".. \n");
                }
                catch (InterruptedException e)
                {
                    Log.d("CallStateService :", "InterruptedException.. \n");
                    e.printStackTrace();
                }
            }
        }
    }).start();

}

如果您注意到上述代码中的行(下面提到):

getApplicationContext().sendBroadcast(intent);

正在将local broadcast发送到同一应用程序。 (即仅将广播从我们的应用发送到我们的应用。)

将其注册到任何活动中,如:

IntentFilter filterTicks = new IntentFilter("ticks");
registerReceiver(secondsBroadcastReceiver, filterTicks);

一旦完成任务,则在同一活动中注销/ onDestroy /OnPause:

unregisterReceiver(secondsBroadcastReceiver);

如何使用:

您已经在上面的代码中注意到广播接收器,如:

private BroadcastReceiver secondsBroadcastReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String InCallDuration = intent.getStringExtra("InCallDuration");
        Log.d("CallActivity :", "Received InCallDuration:" + InCallDuration + ".. \n");
        CallTime.setText(InCallDuration);
    }
};
  1. 您可以从中多次设置/更改UI textview文本它在背景中打勾。
  2. 我们只需要在每个滴答声之后发送广播
  3. 它的适当接收者接收它并更新UI(我们需要对其进行设置)
  4. 它会一直在广播中发送和接收广播。
  5. 您只需要替换Timer方法,因为您的壁虱会减少,现在我把它留给您编程休息。
© www.soinside.com 2019 - 2024. All rights reserved.