How to display the hour counter of an entire application on a Blackberry?

I do and display the hour counter with this code

LabelField time; long mille=0; Timer timer=null;TimerTask task=null; public Timerscreen() { mille=1000*60*1; time=new LabelField(); add(time); timer=new Timer(); task=new TimerTask() { public void run() { synchronized (UiApplication.getEventLock()) { if(mille!=0){ SimpleDateFormat date=new SimpleDateFormat("mm:ss") ; System.out.println("================="+date.formatLocal(mille)+"====================="+Thread.activeCount()); time.setText(date.formatLocal(mille)); mille=mille-1000; }else{ time.setText("00:00"); mille=1000*60*1; timer.cancel(); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { Dialog.inform("Time expaired"); } }); } } } }; timer.schedule(task,0, 1000); 

And when I click on the new screen, I want this clock to still be displayed and counted. How can i do this?

+4
source share
1 answer

It is not possible to add one ui field or manager to two manager or screen s .. each ui field or manager must have at most one parent ( screen or manager ).

So, if you need a LabelField that will hold and show time on different screen s, then you only need to implement some kind of listener that will listen to time changes .. and for each change you have to update screen and LabelField new value. You have already implemented TimerTask , which will provide you with updated data.

[Edited - added later]

you can check the following codes, not verified, but something like this will solve your problem ...

 class MyTimerUtil { TimerListener listener = null; public MyTimerUtil() { } public void setTimerListener(TimerListener listener) { this.listener = listener; } public void startTimer() { final int interval = 1000; Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { // add your codes.. // notify others if (listener != null) { listener.timeChanged(); } } }; timer.schedule(task, 0, interval); } } interface TimerListener { public void timeChanged(); } class ScreeA extends MainScreen implements TimerListener { public void timeChanged() { // add Codes here on time changed event } } 

in the above snippet, you can implement the TimerListener interface in any screen instance and can receive an update every time the event is changed by the MyTimerUtil class. To do this, you need to install an instance of ScreeA (which implements TimerListener ) through setTimerListener() of the MyTimerUtil class.

You must also start the timer by calling startTimer() .

+1
source

Source: https://habr.com/ru/post/1386669/


All Articles