DispatcherTimer not updating with AdControl running - windows-phone-7

I have a simple app that I am creating with a countdown timer that uses a DispatcherTimer for the time base. I have an event handler setup for On_Tick of the DispatcherTimer (set for 1 sec interval). I have three (3) pivot pages using three different instances of AdControl and all are "live" with a real ApplicationID and AdUnitID. This timer is setup on one of the pivot pages.
What I am seeing is that when I open my app and the AdControl starts, after 60 seconds, the adControl wants to refresh. My timer works fine for the first minute, then starts to lose a second every three seconds, like it is missing a tick event (coincidentally when the adcontrol "scrolls" to a new message every three seconds?). I've tried using a background worker for the dispatcherTimer but that did not seem to do anything for me. The code in the event handler is fairly short, with just a couple of "if-then" statements and a few textBlock updates.
Anyone else seen similar issues with the AdControl?

I would say the reason is that the ad control and the timer both want to do something on the UI thread. Thus when the ad control is busy the timer action is blocked during this time. To quote MSDN:
Timers are not guaranteed to execute exactly when the time interval
occurs, but they are guaranteed to not execute before the time
interval occurs. This is because DispatcherTimer operations are placed
on the Dispatcher queue like other operations. When the
DispatcherTimer operation executes is dependent on the other jobs in
the queue and their priorities.
It also explains why using a background worker does not help. As soon as you go back from another thread to the UI thread you have the same problem again. So this issue is basically by design.
Oh and it can also be the other way round. If you would be doing intensive work in the UI thread then the ad control would be blocked. As well as the rest of your UI. This is the reason why you should do as much work as possible in background threads. Maybe the ad control doesn't adhere to this advice.
So far this probably won't help you much. But perhaps it is possible to just use one AdControl and move this from Pivot to Pivot as the user pans around?

I've experienced the same problem with my own timer style app. In my case it only appears to happen when there is animation in the current advertisement.
According to the DispatcherTimer documentation, the delay is expected behaviour, so the solution it to use a different timer... eg System.Threading.Timer
...
//create the timer
var timer = new System.Threading.Timer(
new System.Threading.TimerCallback(TimerTick),
null,
//Set the due time to infinite so the timer wont start immediately
System.Threading.Timeout.Infinite,
0);
//start the timer
timer.Change(0, 1000);
//stop the timer
timer.Change(System.Threading.Timeout.Infinite, 0);
}
void TimerTick(object state)
{
//Dont forget to update the UI on the UI thread.
Dispatcher.BeginInvoke(() =>
{
MyTextBox.Text = "New Text";
});
}
Problem solved!

Related

Nativescript - ActivityIndicator not working for a specific chunk of code

I'd like to display an activity-indicator displayed when I do a long process.
I set a model busy flag to true.
I then call a method that returns a Promise - when the promise calls resolve, I then set the busy flag to false in my 'then' handler.
When I wait for the promise to resolve, I expect the Activity Indicator animation to be displayed but it's not.
I checked and made sure the UI set up is correct and it works.
The work that's being done is using nativescript-calendar plugin - I'm adding a few calendar entries.
I commented out the work that's being done and just went to sleep for a little bit and then called resolve() and the animation worked.
So the Activity Indicator and the Promise mechanism is setup correctly - it's something this plug-in is doing that's causing the AI not to display.
What could cause such a behavior?
I actually edited the Promise work code - put to sleep for about 1 second and then started the calendar work. I see the AI for 1 second and then it freezes.
So it looks like the calendar writes is causing the AI to freeze.
I was under the understanding that Promise work is done in the background and should not effect foreground animation.
I've had a similar issue when using SQLite.
As you haven't explicitly stated that your running the calendar in a worker I am assuming your keeping it in the UI thread (main thread).
Any large amount of work done in the UI thread will cause noticeable lag/delays. So for example you call the activity-indicator then call a process that maxes out the thread, the process finishes the activity indicator goes to be drawn on the screen but then is hidden straight away before it is displayed as the process is finished.
The ideal way to solve this is to move the calendar writes code into a worker (multithread your app) and on success message turn off the activity-indicator.

Must a ProgessDialog run in an AsyncTask or on a seperate Thread?

I have two activities. The second activity if for data collection from the user (he types in new data) and the first for showing graphs. Once the user finish the second activity (by clicking back), I need to do calculations before the charts update on the MainActivity. It is important that the calculations finish first before activity 2 is finished. The code therefore runs in the onBackPressed method.
There seemed to be three options:
1) Use a thread that does the calculations and update the ProgressDialog with a seperate handler to watch for thread completion. The handler receives a message once the thread is complete and then close the second activity. Android Studio warns me that the handler needs to be static and warns me of memory leaks. So this doesn't seem to be a safe approach.
2) Use an AsyncTask and wait until the AsyncTask is completed before closing activity two. However, it appears meaningless to run a seperate thread or an AsyncTask for calculations that should run on the main thread simply to show a ProgressDialog.
3) Show the ProgressDialog on the main thread. However, this does not seem to be possible.
Could you please point this noob to the right method to show a ProgressDialog while sequentially executing calculations for which the user must wait (only a few seconds).
Thanks,
Jean
Use the AsyncTask in Activity one there is no need to open second activity for load data and calculation you can do that in activity one and just use progress dialog in AsyncTask and close that dailog in postExecute method of Asynctask and Call that AsyncTask on OnCreate() method of Activity One.

JavaFX Button detecting event as well as time elapsed

I implemented another version of this project with Java Swing, but because it could not support multi-touch functionality, I am rewriting it using JavaFX.
So I want the program to wait either for a user clicks a Button object or for a timeout, say 5 seconds - this means that the program would present a Button on the screen at one point and does not proceed to the next phase until either the Button is pressed or 5 seconds pass without it being pressed.
Clearly, detecting a click is elementary because adding ActionEvent would solve it. The tricky part is measuring the time. When implementing with Swing objects, I would have a while loop and have Thread.sleep(very_short_time_interval) inside to periodically check the elapsed time:
lastUpdate = System.currentTimeMillis();
while ((!pressed) && (System.currentTimeMillis() - lastUpdate <= timeout)) {
Thread.sleep(50);
}
The purpose of the Thread.sleep() in the pseudo-code above was to prevent the while loop from executing too often. Though it does not seem like the best practice, this trick apparently worked when used with Swing objects. But I realized after trying out the same thing with JavaFX Button objects, it turns the shape of the mouse pointer to a circulating ring, indicating the process is busy on Windows. What is worse is the button would not recognize mouse inputs during this busy phase. I am guessing JavaFX objects are heavier than Swing objects and is causing this problem as a result.
So my question is, would there be another way, possibly native function in JavaFX to make a Button expire without requiring a while loop? Or would there be some lighter weight objects than Button that works in a similar manner (listening to mouse clicks) that could work with the original while approach?
You can use a PauseTransition to wait for n-seconds. On its setOnFinished you can add an action to be performed. If the button has been pressed, you can cancel the transition on its action.
final PauseTransition pt = new PauseTransition(Duration.millis(5000));
pt.setOnFinished( ( ActionEvent event ) -> {
doSomething();
});
button.setOnAction( (ActionEvent event) -> {
doSomething();
pt.stop(); // If the button has been pressed, stop the Transition
});
pt.play();

Timer stops when I focus out of the window

I have a timer set on my application using html 5 and jquery. Now when I move on to different tab or I minimize my window, the timer for that few seconds stops. I do not want this. And again as I open the window(tab or browser page, whatever u say)the timer starts. But it gets pause for those seconds. What should be the issue ? What code should I write for it ?
I want that even though I minimize my window or look at new tab, my timer should be on.
Code for getting the timer is:
Here the timer is set and it runs, but as soon as i move my focus to other page, the timer is paused. A function is just shown here.
function showTime()
{
if(ms>=100){
ms = 0;
s++;
}
// calculates seconds and hours also
var temp= $("#clock").text(checkTime(h)+":"+checkTime(m)+":"+checkTime(s)+"."+checkTime(ms));
if(windows_focus=true){
timer=setTimeout('showTime()', 10);}
else if(windows_focus=false){
timer=setTimeout('showTime()', 100);
}
}
checktime is a function which just add a zero in front of numbers<10.
I just added in windows_focus=false also, as I thought if I move away, then also it should work, but i am not getting.
I tried using setInterval also, when I use setInterval, then even though I minimize the window the timer is getting started. But the problem is that the time runs in a really weird manner. Runs very very fast.
Can anyone please help me out.
http://jsfiddle.net/JWxS6/44/ this might be useful to see my code.
I am really new, please help me out

Picking photo from Photochooser or holding hardware back button cause active timers ring

This is a very strange problem, and all the people I had asked to confirm it said that it takes place.
I have a Threading.Timer instance which fires every 15 minutes. And if I call the PhotoChooser view and then select a photo from it, when going back to the calling page my application calls that timer's callback! I tried different timers either it be Timer from Threading namespace or Dispatcher timer.
The same happens when being in my app I hold the back button of my device and then choose the app from the list.
My application is as plain as it can be - the timer with a callback and method calling PhotoChooser. Could anyone help with solution or workaround please?
Update:
My code construction is as follows:
private Timer _timer;
public void CallTimer()
{
var period = 15 * 1000 * 60;
_timer = new Timer(repeatTimer_Tick, null, 0, period);
}
private void repeatTimer_Tick(object state)
{
// Some action here
}
private void Stop()
{
if (_timer != null)
_timer.Dispose();
}
private void CallPhotoChooser()
{
// Some basic actions calling photochooser task
}
As explained in Windows Phone 7 Tombstoning the application is most likely tombstoned when the user presses and holds the back button or a launcher, like the PhotoChooserTask, is called. This happens unless the page is returned to in a matter of seconds.
You need to store the timer timeout in your application state somehow, or set the initial timeout to 15 minutes so it doesn't fire immediately. To store the application state, take a look at the article linked, it recommends doing this in the NavigatedFrom event which you can overload in the page code behind.
The time left before the timer fires is a bit more difficult. I guess to know how long it's left of a timeout you need to get the time with DateTime.UtcNow (which you can store in the application state) when creating the timer and calculate the next time it will fire upon resuming the application.
You should not be creating those long running timers :) Just handle the activation/deactivation and reset your timers, then reinstate them when photo chooser returns you back to your app.

Resources