In my application I need to call two web-services to fetch the records from server on app start. I did that in Asynch Task and on splash screen but its not running fine. It waits for the aynsch task to complete his operation first then its moving to next activity.
I want my app should call webservice in background on app startup without blocking the user to move next activity.
any help would be appreciated.
**call Asyn server call wherever you need**
getServerResponse();
"startnewactivity" here
finish current activity here
**Asyn server call**
public void getServerResponse(){
new AsyncTask<Void, Void, Object>() {
#Override
protected Object doInBackground(Void... params) {
//write your server response code here
return null;
}
#Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
}
}.execute();
}
You can use an IntentService and fetch the details and store it.
Or You can use a Service, bind it with the activity and send the data when you have retrieved it.
Additionally you can navigate to the 2nd activity and call the AsyncTask to fetch the details and update the UI when done.
If the data retrieved is global and used by multiple activities then store it in the Application class and add a stateChangeListener and get notified when its updated from a background service or AsyncTask.
Using an Async task you can run the web service call in a background thread and your UI thread wouldn't be blocked and you can call the next activity in background using the runonuithread but it makes seamless solution. So its better to wait finish the background process first
Related
In my android application, I need to execute some operations, like creating some files in the internal storage and download some data from a server on start of the app. Only when these operations are finished, the rest of the application can work properly. So it’s my intention to show an image and a progress bar when the app is opened, and after all these operations are done, a new activity is opened.
Now, I know it’s common to put potentially long running operations like downloads and file reading/writing into async tasks. However, in my case, I can’t really continue until these operations are finished, so do I need to use Async Tasks, or is it ok for the application to block in this case?
Or should I start an Async Task and then wait for it, using the get() method?
Thanks for advices, I'd really like to do this the right way.
You care create a splash activity which should be your launcher activity.
Then in the splah, start an async task for downloading and all, then after the completion of the task, you can move to your desired activities.
You can also use a thread for this purpose; in that case, you need to handle the task completion callback using a handler or runOnUIThread mechanisms.
Better to use Async task for this.
You need to put it in an async task or different thread. Internet requests on the main ui thread will create a fatal error on the newest (android 4+) systems.
It is always better to show a loading image or progress dialog than showing a hanging white screen.
For all long blocking jobs, async is required.
If you have the splash screen as your main activity, add this code for your async task:
private class YourTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
//Do your work here
//Note that depending on the type of work, you can change the parameters
//of the async task.
return count;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//Put here the code when your job is done, for example:
//start a new activity (your real main activity).
}
}
After that, in your oncreate method of the activity, call
new YourTask ().execute(url1, url2, url3);
I'm writing an application for Android, which should get some data from the server as soon as it launches.
Between the start of the application and the response from the server (or timeout, if the server is down), the application should display a "waiting" animation.
Thereafter, the normal panel should be shown (if the server responded) or an error dialog box be displayed (if the server didn't respond).
What is the correct place to put this logic into?
MainActivity.onCreate or some other place?
if you want the data loaded only when the app starts for the first time, onCreate() is the right place. if you want to re-loaded every time the app comes into focus (i.e., the foreground), then onResume() is the right place. take a look at documentation on the activity lifecycle for details.
you'll want to take a look into AsyncTask, or Loader+AsyncTaskLoader to understand the right pattern for doing something in the background then updating the UI with the result.
As Jeffrey suggested at first you have to determine when you want to connect to the server? Depending on this you should connect to server in onCreate or onResume.
Now you must remember one thing that you can't do heavey tasks in your manin GUI thread. Else there is a good chance of ANR. So you have to implement this feature in a different thread. For this you can use different Thread, Handler or AsyncTask. You can find a nice doc here
I think it is a suitable situation to use AsyncTask. So here is an example with AsyncTask
private class ServerCommunication extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// show the connecting screen
// or you can do this before calling asyncTask
}
#Override
protected Void doInBackground(Void... params) {
// communicate with server
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// show the second screeen
}
}
and call it using
ServerCommunication pcd = new ServerCommunication();
pcd.execute();
This is just for suggesting the structure. You can definitely use neccessary paramenters or other method also.
I m new in android, I'm not much aware about services.i have an activity class with a UI, i want to make this activity class runs in background, when i click the back button. how to make my activity runs in background like a service, plz help me..
You cannot really run an Activity on background! When an activity is not on foreground it gets to onStop and then the system could terminate it, to release resources, by onDestroy method! see Activity Lifecycle
In order to run on background you need to create a Service or IntentService
Checkout android javadoc about Services here and here or IntentService
and here is a third-party Android Service Tutorial
Edit: you may also need a communication between your service and your activity so you can get through that: Example: Communication between Activity and Service using Messaging
If you simply want your activity runs in back Try using
moveTaskToBack(true);
It seems like you want to run an activity in background when it quits. However, activity can't be run unless it's on foreground.
In order to achieve what you want, in onPause(), you should start a service to continue the work in activity. onPause() will be called when you click the back button. In onPause, just save the current state, and transfer the job to a service. The service will run in the background when your activity is not on foreground.
When you return to your activity later, do something in the onResume() to transfer the service 's job to your activity again.
You should read the developer guide on Threads: http://developer.android.com/guide/components/processes-and-threads.html
Specifically the function doInBackground()
Example from page:
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
Due to android doc , The task can be executed only once.
I'm trying to run HttpClient in UI-Thread. But it allows for the only once. If I want to get another data from another link which is not yet run at the first start, how can I do it? Until I get all data when the app starts for the first time, it takes long time. Is there anyone who knows how to solve this problem ?
You're running a network operation on main thread. Use async task to run network operations in background thread (do your http requests in a background thread).
Do your networking in an async task like this:
class WebRequestTask extends AsyncTask{
protected void onPreExecute() {
//show a progress dialog to the user or something
}
protected void doInBackground() {
//Do your networking here
}
protected void onPostExecute() {
//do something with your
// response and dismiss the progress dialog
}
}
new WebRequestTask().execute();
Here are some tutorials for you if you don't know how to use async tasks:
http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/
http://www.vogella.com/articles/AndroidPerformance/article.html
Here are the official docs from Google:
https://developer.android.com/reference/android/os/AsyncTask.html
You can call the async task multiple times whenever needed to perform the download tasks. You can pass parameters to the async task so that you can specify what data it should download (for example by passing a different url each time as a parameter to the async task). In this way, using a modular approach, you can call the same aync task multiple times with different parameters to download the data. The UI thread wont be blocked so the user experience will not be hindered and your code will be thread safe too.
You can do multiple operations in an AsyncTask
protected Void doInBackground(Void param...){
downloadURL(myFirstUrl);
downloadURL(mySecondUrl);
}
An AsyncTask can only be executed once. This means, if you create an instance of AsyncTask, you can only call execute() once. If you want to execute the AsyncTask again, create a new AsyncTask:
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(); //Will work
myAsyncTask.execute(); //Will not work, this is the second time
myAsyncTask = new MyAsyncTask();
myAsyncTask.execute(); //Will work, this is the first execution of a new AsyncTask.
Consider the scenario where I have get data from server and post it to UI in say list view , but this is an going activity ,it never stops.
taskA{ //fetches data over network
if(!update)
fetch();//network operation
}
taskB{//using this data UI is updated at runtime just like feed.
if(update)
show();//UI operation
}
taskA starts first after it completes taskB starts by that time A is sleeping and vice versa , goes , now the problems i am facing are:
both operations have to be in worker thread
both operations are going in cycle till activity is alive.
if handler is used to post UI operation to the main thread , taskB seems to stop.
Can anybody please suggest me a design to get this working?
AsyncTask is doing the job for you. You can make it as an inner class under your Activity main class.
http://developer.android.com/reference/android/os/AsyncTask.html
Example code
private class YourTask extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
// Fetch Data (Task A)
return "Result";
}
protected void onProgressUpdate(Integer... progress) {
// Show progress
}
protected void onPostExecute(String result) {
// Show UI after complete (Task B)
}
}
AsyncTask is what you're looking for. Check out this link for some sample code:
http://geekjamboree.wordpress.com/2011/11/22/asynctask-call-web-services-in-android/
You can also use IntentService you can check some sample code
An Android service is lightweight but more complex to setup.
AsyncTask is very easy but not recommended as it has many downsides and flaws.
You could also look into Loaders but it's not as easy as AsyncTasks.