Android :: Periodically Executing AsyncTasks?
Sep 1, 2010I am getting data from the server using AsyncTask. I need to update the data periodically.
View 3 RepliesI am getting data from the server using AsyncTask. I need to update the data periodically.
View 3 RepliesI am replacing the multithreaded code in my app with the AsyncTask from 1.5. I found that two AsyncTasks do not work concurrently. I investigated a bit and found a workaround; I would like second opinion if my solution is right. OR if there is a better solution.
AsyncTask allows the app to do a task on a thread other than the UI thread. But IIUC, it only provides a single thread on which a queue of tasks is performed. Therefore, if one of the task is to wait on some event (n/w or sleep) then all other tasks will wait for it to finish.
To elaborate with the coding example: <code>
public class MyTask extends AsyncTask<...> { ... }
On the UI thread execute two tasks MyTask mt1 = new MyTask().execute(args);
MyTask mt2 = new MyTask().execute(args); </code>
In the above code both the execute calls will return immediately and free up the UI thread; however mt1 will be executed first and mt2 will have to wait until mt1 finishes.
Thanks to the android's open source, we can see implementation of AsyncTask. http://google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#uX1GffpyOZk/core...
I copied AsyncTask.java as UserTask.java in my project and changed the value of CORE_POOL_SIZE to 5. This makes the thread pool to use 5 threads to multiplex the queued AsyncTasks. This indeed solved my problem. Now if mt1 blocks on a sleep; mt2 goes ahead and finishes its job.
Here are some questions for those who know more about AsyncTask implementation:
Is this work-around right? If yes, can the CORE_POOL_SIZE be made configurable in future, via an API call? Is there a solution by which multiple thread pools can be used?
Let me add that, I am aware that this is a phone and not a web server - I am not using 10s of threads to do network I/O. However a single thread is not sufficient for my app either.
I have an AsyncTask that acts as a countdown timer for my game. When it completes the countdown it displays the out of time end screen and it also updates the timer displayed on the screen. Everything works fine, except I need to be able to pause and resume this when the pause button in the game is pressed.
If I cancel it and try to re-execute it, it crashes with an IllegalStateException.
If I cancel it and instantiate a new AsyncTask in its place the old one begins to run again and the new one runs at the same time.
Is there a way to cancel/pause the timer and restart it using AsyncTasks or is there a different way I should be going about doing this?
I'm trying to run two AsyncTasks at the same time. (Platform is Android 1.5, HTC Hero.) However, only the first gets executed.
Here's a simple snippet to describe my problem:
CODE:................
The output I expect is:
onCreate() is done.
bar bar bar
foo foo foo
bar bar bar
foo foo foo
And so on. However, what I get is:
onCreate() is done.
bar bar bar
bar bar bar
bar bar bar
The second AsyncTask never gets executed. If I change the order of the execute() statements, only the foo task will produce output.
Am I missing something obvious here and/or doing something stupid? Is it not possible to run two AsyncTasks at the same time?
I realized the phone in question runs Android 1.5, I updated the problem descr. accordingly. I don't have this problem with an HTC Hero running Android 2.1.
I have three simultaneous instances of an AsyncTask for download three files. When two particular ones finish, at the end of onPostExecute() I check a flag set by each, and if both are true, I call startActivity() for the next Activity.
I am currently seeing the activity called twice, or something that resembles this type of behavior. Since the screen does that 'swipe left' kind of transition to the next activity, it sometimes does it twice (and when I hit back, it goes back to the same activity). It's obvious two versions of the activity that SHOULD only get called once are being put on the Activity stack.
Could this be from both onPostExecute()s executing simultaneously and both checking the flags each other set at the exact same time? This seems extremely unlikely since two processes would have to be running line-by-line in parallel...
A lot removed from this question since I was way off in what I thought was wrong. Nonetheless I found the answer here quite useful, so I have edited the question to reflect the useful parts.
I'm about to create a lazy image loader for images both from device and from the web for a ListView. I'm thinking of what to use and how, on one hand i can use a thread that pools my request (always running, and i can attach a view and an adapter and it will handle the image loading for me), cache my allready loaded images and checks for the visibility of the images before i load so i wont do unneeded job.
I had another thought of using the AsyncTask like many suggest in the forum. Terhe is one drawback though.I see that many use new MyTask().execute(urls); this presents a problem if i want to start loading and stop loading images on demand. If i use the async task per image then i need new async task for each image, that's a lot of 'new' to make, i can use a pool, but if too many async tasks are stuck, i will still create about 150-200 asyc tasks, too many for my taste...
What do you guys think ? i think a thread will do a nicer job here:
1. keep on running till killed
2. try to get a job from the queue, if not jobs, wait.
3. if a job is available, get it and start processing.
4. each request is processed alone,serially and blocks the thread.
5. once does goes on with '2'.
6. each enqueue that is done by the adapter using startLoadingImage() for views that need to be displayed will create anew job and call notify on the wait lock.
I can optimize this code with a pool of threads if i want several GETPOST requests in parallel. Also I'm caching the images i already downloaded loaded for fast load on next access. the idea is to minimize GC and list's slagging.
I have no idea, but my app is stalling sometimes completely (not responding to touching the screen) I thought I was following all the rules for threading, but my app is apparently slowing down the Sprint EVO! I have never used an app as slow as my own. I don't get an ANR dialog, though I think I probably should get getting one. I have no idea how to make this application run like every other app I've ever used -- Not freezing. Is it not a good idea to have one HttpClient and keep a static reference to it for all Activities that want to use it? I used to create a new one each time, and thought that changing it to one sped it up. None of my AsyncTasks ever end. If I go to Activity A -> B -> C -> D the first time it will be smooth. I can press back but when I get back to A, its completely frozen, not responding to anything. That when I took that screenshot. I really have no clue what I am doing wrong. Should I manually kill my AsyncTasks on Activity.onPause()?
View 1 Replies View RelatedI'm making a App to send SMS trough VOIP providers from betamax.To send I just need to execute the URL
https://www.12voip.com/myaccount/sendsms.php?username=w​&password=x&from=y&to=z&text=some%20text
My app already creates the URL, but i cant understand how to execute.i think i have to make an HTTP request....but after a few hours after answers i still didn't understood.Can anyone help me execute that url with android?
I want to change the start point of my machine, that is,when start on Android, it can run my app instead of "home" firstly,if it possible?
View 4 Replies View RelatedThere is a strange out of memory error issue. I create a class to parse live streaming, and the class needs buffers to keep these raw data. Here are code snippets...
View 4 Replies View RelatedDose anyone know how to unable HOME KEY when program is executing?
View 2 Replies View RelatedI have to execute the shell command
setprop net.dns1 xxx.xxx.xxx.xxx
from an android activity but i can't find a working way to do it. How can i execute this command from the application?
For example, is there any way to define a service to run as 'system' UID or GID?Or any way to add your app to the 'system' group?
View 1 Replies View RelatedIn the documentation, I read that it is not possible for executing 2 Async Tasks. If execute is called again, it should throw an exception.
The following is given under the heading of "Threading Rules", and i quote:
"The task can be executed only once (an exception will be thrown if a second execution is attempted.)"
I wish to understand the meaning of this statement.
Does this mean, that if i try and execute the same task twice (concurrently) when the first execution of the task was still going on...an exception will be thrown ? Will i need to wait for the completion of the first task, before i spawn a second task ?
A possible use case:
The user wishes to download a set of files. He clicks on the download button by providing the URL. When the first download is still going on, he wishes to download another file and provides another URL. Both these user actions are serviced by a DownloadTask, that extends the AysncTask.
If i wish to change this default behavior, is there a configuration option?
I am devoloping an application of image editor. I always do it by using the resources in the drawable carpet. Now I changed it to use the resources in the SD card. I don't change the code of the image access but the program always produce an error if I intent to set the value of a pixel. The program works correctly if I try to read the pixel but if I try to modify it fails. I think this is a permissions error but I added the following: <uses-permission android:name="com.android.editorImagenes.permission.WRITE_EXTERNAL_STORAGE"></ uses-permission> <uses-permission android:name="com.android.editorImagenes.permission.WRITE_OWNER_DATA"></ uses-permission> And everything remains exactly the same. I'm desperate. A thing happens is that if I try to do the scaling or rotating the image using a matrix postrotate, etc, the program works correctly and as of this moment I can use the SetPixel without causing error.
View 2 Replies View RelatedI've a lot of initialization code in my main activity's onCreate(). When I launch my game, the screen goes black for a long time, then my game appears. I did logged some message at the start and end of onCreate() and found that onCreate() is executing its code while the screen is black. Sometimes the screen goes black for too long and phone shows a popup dialog prompting me to choose between Force close/Wait. Then when onCreate() is completed, my game appears. Choosing 'Wait' then dismiss the dialog.
I tried using progress dialog described in this article:
http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog
But it doesn't work. The screen goes black for the same amount of time even after I use the progress dialog.
I would like to a WebView to run some JavaScript before loading the rest of the page. This JavaScript should run in the same context of the page, just as if extra <script> content were added before any other <script> content. This is not possible with add Java script Interface() since I want to set up some instance variables, before the page scripts are run, so that the page scripts can use them.
View 5 Replies View RelatedThis link says that Android support Python, Lua and BeanShell Scripts, subsequently for Perl too. If it is so, is it possible for developers to write python scripts and call them in their standard Java based android applications?
View 2 Replies View RelatedI am configuring wifi on my android based board using shell script. Now I want to execute the same script from android application. For that, I had used following code, but it didn't give any success till now,
I had executed same script from "adb shell" prompt and it works nicely.
Process exeCommands = Runtime.getRuntime().exec("/data/busybox/ board_script.sh");
is there anything else required than this?
I try to create a mini player view on home screen and still use the music mediaplayback service by putting a IMediaPlaybackService aidl in home directory. the mini player can normally playback and control the music, but often meet the anr(com.android.music) and see below log.
CODE:....................
How would I force the current thread to wait until another has finished before continuing. In my program the user selects a MODE from an AlertDialog, I want to halt executing of the program before continuing as the mode holds important configuration for the gameplay.
new AlertDialog.Builder(this)
.setItems(R.array.game_modes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
setMode(TRAINING_MODE);
case 1:
setMode(QUIZ_MODE);
default:
setMode(TRAINING_MODE);
break; ............
//continue loading the rest of onCreate();
contineOnCreate(); } })
.create().show();
If this is impossible can anyone give a possible solution?
Trying to root my Hero for the first time. I am downloading the InstantRoot.apk.zip file, extracting it to InstantRoot.apk, which I then copy to the root folder of the phones sdcard.
When I try to execute it, using Astro, and choose "Open App Manager", it says "Could not open /sdcard/InstantRoot.apk as a APK file". What am I doing wrong? Is it maybe the unzipping that causes it?
I have successfully been getting GPS data through the registerLocationListener() and onLocationChanged() methods. The only problem with this is that the speed reading of my app freezes if there is no more GPS data (e.g. when I go indoors, enter a tunnel, etc). The behavior I want for my app is that the user is somehow notified that the speed reading is probably not accurate due to a lack of fresh data (set speed to zero, blink the speed reading, etc). How can I do that? I though of checking periodically whether the GPS unit was detecting any satellites, but I'm not sure how to force periodic checks.
View 1 Replies View RelatedI am trying to execute a {public void} method in Service, from scheduled TimerTask which is periodically executing.This TimerTask periodically checks a condition. If it's true, it calls method via {className}.{methodName};However, as Java requires, the method needs to be {pubic static} method, if I want to use {className} with {.dot}.The problem is this method is for notification using Toast(Android pop-up notification) and Status Bar.But for this to work, the method must not have {static} modifier and resides in Service class.So, basically, I want background Service to evaluate condition from scheduled TimerTask, and execute a method in Service class.Can anyone help me what's the right way to use Service, invoking a method when certain condition is satisfied while looping evaluation?
View 1 Replies View RelatedI'm developing sort of a wireless scanner, so I need to scan every X seconds. I know I should use WifiManager and startScan() to get the networks and then register a receiver to receive the event once the scan has finished. However I'm having problems when trying to figure out how to scan periodically. It's more like a design problem. My solution so far has been to create a Service which takes care of the scanning, besides the main Activity.
I think this is correct. So, how could I tell this Service to scan every X seconds? I've thought it may have a Thread object, call its Scan method during tart_services() and then take it to sleep. Also I thought I could just get rid of the Service and run the Thread from the main Activity, but then I guess it would die whenever the Activity is not visible. None of then seem like a really good solution to me, and I think there must be an easier way to do this.
We have a very patchy wi-fi network here. The wi-fi router's pretty old and I tend to need to switch it off and on every couple of days. Is there an app I can use that will - perhaps in conjunction with Locale so it only runs when I'm in the office - periodically check if our wi-fi connection is up and running?
View 1 Replies View RelatedI currently use SMS Backup & Restore, but that has two drawbacks I see
-I have to manually initiate the backup
-It only stores and restores one file, so I have to overwrite and rename
I just lost my texts and only had a two day old backup. I'd love to see the same thing but that can do it with a timestamped file such as backup_2009-12-18-15-08.xml (pickable when restoring) and can run at a preset time each day or each half day.
I have one activity. OnCreate the activity gets the source (html) of a web page to a string and presents the result (after parsing it a bit) in a textview. I would like the activity to reload/refresh periodically to always present the latest information.
View 1 Replies View RelatedIf I want to upload a text file containing some game stats to a web server for testing purpose, which approach is the best? Do I write a service along with my application and then upload the log file once it reaches a specific size? Or do I embed the logic into my application and then do it during idle times?
View 3 Replies View RelatedI never got this working in a straightforward manner. Sorry if I'm being a little vague. I'll try to elaborate on what I'm trying to do. I am trying to build a listview that grabs its data from a webservice. Once I initialize a listview, I want to keep polling the webserver periodically and update the contents of the listview. For this I am doing something like this:
public class SampleAutoUpdateList extends Activity {
//Autoupdate handler
private Handler handler = new Handler();
private Runnable updater = new Runnable() {
public void run() {
/*
* Update the list
*/..................................