Observable.timer saving state - android

I'm using rxjava and rxandroid. In my presenter i have used
Observable.timer(10, TimeUnit.SECONDS);
And I would like to save time on screen orientation change. For example timer starts and after 3 seconds user is changing screen orientation, and timer starts again but from 0 for 10 seconds, but it needs to run for 7 remaining seconds.
Do you know any solution?

When you orientate your device, it recall onCreate() method of your activity and redraw your views. For this you can create a helper fragment and put your operations in that fragment. Put this line setRetainInstance(true); in onCreate() method. Then, do your operations onAsyncTask. If you wand display each second of timer in your screen, then call onProgressUpdate() method of your AsyncTask class. Then, create an interface, withProgress callback and put this callback in onProgressUpdate() method. Then you can handle this operations via implementing that interface which you created in your fragment. I have simple repository in github which can help you. Enjoy. This article also can help you: Enjoy.

Related

Android - refresh activity

My android application has 2 activities:
In the first one (MainActivity), the user chooses some parameters and these parameters are sent to the second activity (Display).
The second activity calls a web service, and according to the chosen parameters, the web service returns a value. I use the returned value to draw a bar chart of the evolution of this value. That's why I created a timer in the second activity that I put in the onCreate() function:
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
finish();
startActivity(getIntent());
}
},10000, 10000);
So every 10 seconds, the second activity is called again and the bar chart is updated with the new returned value.
The problem is, after the 2nd or the 3rd execution of the timer, several identical values are returned at the same time, as if the activity was called several times. And then the application starts freezing (but doesn't close).
I'm using the charts provided by this library: http://android-graphview.org/
I've also tried using the functions provided on the above website (resetData and appendData), and also the invalidate() function, but nothing works.
Any ideas why this happens? Is my way of refreshing the activity wrong?
The way you described it:
you create a new Timer (see 2.) with every call of the second activity
The purpose of each Timer is to call the second activity (see 1.) every 10 seconds
As a result the amount of times the second activity is called as a function of time increases exponentially.
A possible solution would be to move the timer to the onCreate method of your Main Activity (and still call the second activity from it).
This way there should be exactly one Timer active at any time.
EDIT:
As commented by Marius, an Activity might not be the optimal choice. If there is no user-input and the only thing the activity does is call a webservice and return the result, a method called from your Main Activity would be sufficient.
Firstly, calling finish() and starting the activity, NOT A GOOD IDEA.
Secondly, As far as i have understood your scenario, calling an AsyncTask inside a Timer after every 10 seconds is a better way to accomplish this. Call your web service in doInBackground() and then update your UI from onPostExecute(), this way you can avoid calling finish() and relaunching your activity every 10 seconds.
Finally you are creating a new Timer instance eveytime your Activity is called, so creating a huge number of Timer instances hanging your application.

Best place to run asynctask in fragment

I have thinking some time about this. I have an FragmentActivity in wich I have a FrameLayout and some Fragments change there. Each fragment has different layout and launches different asynctask. My question is :
Where is the best place, I mean best fragment state, to call asynctask ? I mean like I have some textviews in fragment layout and I want them to display text values based on asynctask result. Should I call the asynctask in onCreateView or somewhere else ? Making the call in onCreateView would invoke the asynctask more times as the orientation would change, as I am aware of. So what is the best practice for fragments with asynctask ?
Better to use AsyncTaskLoader instead AsyncTask with fragments
When you create the Asynctask in onCreate it gets called only when the fragment is created. When you call it in onResume it gets called even after the user returns gets a phone message. So it depends on how up to date you want the data.
You could even call it in onViewCreated but it really is up to you. You can also call it in the application object so the asynctask is executed only when the user starts the app.

Android timer notification across application activities

I have an application with several activities, and I have a timer I start in the first activity that is presented. The problem is this:
How can I get a reference to the current activity when the timer goes off when the activity I'm currently may not be the same as the one I started the timer.
What I actually want is to have a timer traverse all my actives, show an alert dialog when it expires and the do some stuff. But because of the way android works this seems to be impossible. Does anyone has an alternative?
I've already tried:
Using an async task to access the ui thread, doesn'nt work if it is not created in the main ui thread.
Can't use a Handler, my timer is in another class
What other choice do I have?
EDIT:
I canĀ“t change any of the activities code, the timer should be decoupled enough to function when someone plugs it in the project.
Getting an instance of the current activity from the timer worker thread should work, since it would let me run stuff in the ui thread.
Implement your timer as a singleton.
Then, implement an observer pattern:
Create an interface (maybe called AlertListener) that is implemented by each Activity you want to be alerted. This interface should have a method, something like onTimerExpired(). This method should do whatever needs to be done to the activity when the timer expires.
In your timer class, also maintain a reference to the current AlertListener and a method, named something like "setCurrentActivity(AlertListener currentActivity)".
In onResume or some other method of each activity, call MyTimer.setCurrentActivity(this).
When the timer goes off, call currentActivity.onTimerExpired().

Using result of a thread in OnResume()

My Problem: Is it possible to prevent an activity to call OnResume() when it is being created? As I saw after the OnCreate() and onStart() method runs, the next one is the onResume(), although I only want to have it when I resume the activity from the paused state.
Why do I need this: I launch my activity (FragmentActivity, so lets say OnPostResume() ) starting with a thread which takes about 2-3s to be ready getting data from an external database. After the thread is done, I call a method which needs these data and I want to call it everytime that activity gets visible. The thread runs only when the FragmentActivity is created (onCreate()), and I cannot put the method into the onResume() because onResume() would be running way before the thread would finish its task. So it would receive not-ready data.
Anyone has a better idea?
Not sure of the exact application of this but I'll make a suggestion.
If you use an AsyncTask, you can send it off to get the data you need and in the onPostExcecute() method you can call your method that requires the data or update the view as needed. (It runs on the UI thread)
If you happen to already have the data you need in certain scenarios you could also bypass the AsyncTask and directly update the view.
This AsyncTask can be triggered in the onResume() method.
If I'm missing something, please let me know and I can adjust my suggestion.
I didn't understand the purpose of this, but here's a possible solution:
If you only wish to get the even of onResume on states that didn't have the onCreate before, just use a flag.
In the onCreate, set it to true, in the onResume check the flag (and also set it to false). if it was true, it means the onCreate was called before.
I personally would prefer to check if the result available, rather than always executing the getter-code in onResume. If the user somehow resumes your activity before the background thread is finished, you'd have a call on onResume, but don't want to display a result.
Maybe it would be a good idea to calculate/fetch the values in the thread, and let the thread return immediately (and cause the values to get filled in) if the values are already cached somewhere. That way you'd only have one entry point (the thread) for updating your UI instead of two (the thread and the onResume method).

Execute an AsyncTask after Activity is shown

I'm developing an Android 3.1 application.
I want to execute an AsyncTask after activity is shown. I want to show something to user before execute AsyncTask.
I've read that it is not recommend to execute AsyncTask on onCreate().
Where I have to execute AsyncTask on onStart() or onResume()?
I want to left enough time to show activity before execute it.
onCreate(), onStart() and onResume() are lifecycle methods called by the operating system and shouldn't be called directly. You can however override them to have your code executed at these stages of the activities lifecycle:
However, if you want your AsyncTask to start after all of your Views have been inflated and drawn to the screen then you need to put the code in this:
toReturn.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
toReturn.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// asyncTask.execute();
}
});
In the above example toReturn is a view in your onCreate() method. It can be any view you like.
This pulls a ViewTreeObserver from the View and add's a listener to it which will be called when the view has finished being drawn to the screen. It's important you keep the "removeGlobalOnLayoutListener()` line in as this will stop the code firing every time the View is drawn.
Answer is in onResume()
I hade same requirement in my activity where i need to show some list with other buttons and images..
List were getting data from server so used AsyncTask for that..
But before that required to show empty listview and other part of the screen..
so first when it goes to onCreate() I set empty arraylist to listview's adapter then in onResume() call the Asynctask and in that task fill the ArrayList and call adapter.notifyDataSetChanged()
Then another problem occure..when i go to next activity and come back it always call the asynctask even if i dont require..
So had put some condition like if(arrayList.size()==0) then call asynctask else dont.
You can put yur code in the onWindowsFocusChanged method. You can use a thread inside it to manage the timer to start your specific asynctask.
Be aware that this would be performed each time your activity have the focus, not only the first time you launch your activity (I don't know if this could be a problem for you).
implement a View object and override the onDraw().
that way you'll know exactly when the first screen is visible to the user

Categories

Resources