我对同时使用多个倒数计时器的最佳方法会有疑问。我已经在UI线程上执行此操作,并且正在更新许多组件(Textview,带有数据的rv,imageviews)。它有效,但是当我要切换即时通讯显示的“警报”时,我注意到ui有点滞后。
我还想使该警报在后台运行,并显示剩余时间的通知,因为我认为我永远无法使用我所做的此UI线程操作。
这将是正确的方法?
谢谢大家!
从任何service
或任何intentservice
或asynctask
中,您都可以使用计时器线程(即您的情况下的倒数计时器):
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);
}
};