I am new to programming and I have struggled with this for days and cannot get it to work.
I have a loop to execute some tasks. It will display a picture in an ImageView for that particular task. So it goes something like this:
setImageResource
do some task
wait for 1 second
then start everything again until the commands end
when all commands end, close that activity by calling finish()
I tried to use a handler with runnable and asynctask but I cannot get it to work. The UI is always updated later than the 1 second delay. As I call finish() after the commands ends, the photo seems not show up at all.
for(int i=0; i<actions.size(); i++) {
switch((int)actions.get(i)[0]) {
case 0:
ivActionIcon.setImageResource(R.drawable.image);
sleeping=true;
DelayAsyncTask delay=new DelayAsyncTask();
delay.execute();
while(sleeping){};
break;
}
}
finish();
class DelayAsyncTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
sleeping=false;
}
}
I am using a variable "sleeping" to let the main thread to wait for the delay.
Just from taking a guess this loop is somewhere in a UI thread. That means that you are blocking the UI thread until the async finishes. That is a NO-NO! Why not just update the image in the onPostExecute? Something like
class DelayAsyncTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
try {
Thread.sleep(5000);
} catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
ivActionIcon.setImageResource(R.drawable.new_image);
}
obviously remove this line of code as well (I don't think I ever know a reason for doing something like that anyway).
while(sleeping){};
Related
I need to call task() function from doInBackground() of AsyncTask class. The task function contains 2 sub-async task. So the task() return immediately from doInBackground().
Is it possible to stop(or mark this task done) this task from anywhere else?
How to wrap two sub async task in one.
You don't need to call another AsyncTask from within doInBackground. As a matter of fact, once you get to a high enough API, you'll get an exception. You can call another long running method from within AsyncTask without needing to worry about a thread; you're already in a background thread. If you really feed the need, call another service, but there is no reason to do this.
To stop an AsyncTask, just override OnCancelled. Then you can just call:
task.cancel(true).
EDIT:
If you want to wait for another process to finish before you move on, you can wait for that process to finish by setting a global variable in your class or application and then doing a Thread sleep until done. You will not get an ANR because you are already in a background thread and not on the Main UI:
private boolean processIsDone = false.
//then in your method you are calling from AsyncTask:
private void myLongRunningMethod() {
//do your work here....
//at the end set
processIsDone = true;
}
//in your AsyncTask:
protected Void doInBackground(Void... params) {
//do first part of AsyncTask here
myLongRunningMethod();
do {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!processIsDone);
//finish the process here.
return null;
}
I do not understand the question exactly but maybe this can help. Use this class in your Activity like this:
myTask = new BackgroundAsyncTask().execute();
And cancel this way:
myTask.cancel(true);
This is the code of the class:
private class BackgroundAsyncTask extends AsyncTask<Object , Object ,String> {
protected void onPreExecute(){
// Do Before execute the main task
}
protected String doInBackground(Object... param) {
//Execute the main task and return for example and String
return res;
}
protected void onPostExecute(String result) {
// You can use the String returned by the method doInBackground and process it
}
}
Hope it's help
About your first question, you can catch event when your task is cancelled by onCancelled() method. try like this:
private CancelTask extends AsyncTask {
private boolean cancelled = false;
protected void onCancelled() {
cancelled = true;
}
protected Object doInBackground(Object... obj) {
do {
// do something...
}while(!cancelled)
}
}
and call AsyncTask.cancel(true); when you want to stop.
CancelTask task = new CancelTask();
task.execute();
...
task.cancel(true);
And about second question, I want to know how you handle two "Sub-AsyncTask"s.
I will try to find a solution after you update your code.
I have two asyc task both perform separate network operation.I want one async task to wait for other task to finish for a single variable..I thought of doing it like perform other asyc operation onPostexecute of first one but for a single variable i have to make other task to wait first one to finish...is there any to achieve efficently
Referring to this, you can not use .execute() so;
First you have to start your tasks like this:
// Start first task
new Task1().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
// Start second task
new Task2().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "");
and then you can make a static variable so the both of tasks can access to it:
public static boolean task1Finished = false;
Then simple example of the tasks:
First task
private class Task1 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.d("myApp", "Task1 started");
for(int x = 0; x < 10; ++x)
{
try
{
Thread.sleep(1000);
//Log.d("myApp", "sleeped 1000 ms");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
return "";
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
// Lets the second task to know that first has finished
task1Finished = true;
}
}
Second task
private class Task2 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
Log.d("myApp", "Task2 started");
while( task1Finished == false )
{
try
{
Log.d("myApp", "Waiting for Task1");
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
Log.d("myApp", "Task1 finished");
// Do what ever you like
// ...
return "";
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
Log.d("myApp", "All done here (Task2)");
}
}
Maybe asynctask is not the best tool? There are some interesting classes in the android api that can help doing specifically the synchronizing job :
Quote from android developper : "Four classes aid common special-purpose synchronization idioms.
Semaphore is a classic concurrency tool.
CountDownLatch is a very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
A CyclicBarrier is a resettable multiway synchronization point useful in some styles of parallel programming.
An Exchanger allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs."
So I suggest looking into :
Cyclic Barrier
http://developer.android.com/reference/java/util/concurrent/CyclicBarrier.html
Exchanger
http://developer.android.com/reference/java/util/concurrent/Exchanger.html
You need to create another async in OnpostExecute of first one if you need to call the other synchronously.
The goal:
Using Google App Engine server and Android client, I'm trying to put on the Google map at the Android client Users overlays. Every 30 seconds I'm polling the server and getting Vector that contains users and adding it to the map.
Current status:
I'm dong all that using in one new thread, So after running the app I got:
weird behaviors(delayed overlays, multiple overlays) and after that crushed with ConcurrentModificationException.
After reading a bit i figured out that I need to work with AsyncTask.
Correct me if I'm wrong,But I understand that everything done in the Activity at at onCreate is "running" in UIhread so I need to put the "Logic" (All the Network handling) in doInBackground and all the UI Handling like putting overlays on the map in onPostExecute.
My Question are:
1) In the current status I'm doing:
new Thread()
{
#Override
public void run()
{
super.run();
while(true)
{
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
putNewOnlineUserOnTheMap();
}
}
}.start();
What is the right way to convert this To AsyncTask?
Do I poll the server still using new thread in the doInBackground or there is right way to do this?
2) Is there a specific list of what counts as UI to put in onPostExecute or any concepts list?
In my case I guess that in need to put putNewOnlineUserOnTheMap() in onPostExecute.
Thanks.
Something similar to the following:
class UpdateTask extends AsyncTask<Void, Vector, Void>{
#Override
protected Void doInBackground(Void... params) {
// this is running in a background thread.
while (!isCancelled()) {
SystemClock.sleep(30000);
Vector responseFromServer = getUsersVectorFromServer();
// send the result back to the UI thread
// onProgressUpdate will be called then
publishProgress(responseFromServer);
}
return null;
}
#Override
protected void onProgressUpdate(Vector... values) {
// this is executed on the UI thread where we can safely touch UI stuff
putNewOnlineUserOnTheMap(values[0]);
}
}
You can't use the result of the task since the task is finished then. But you can use the progress publishing mechanism to get periodic results. If you use it like that and do the modification on the UI thread you should not get ConcurrentModificationException because you do the modifications on the one thread that can safely modify the UI.
One thing to note here: create new instances of your Vector in the background thread and then use it to update the UI. But don't touch the same object afterwards in the backgroundthread. That way you don't need any synchronization since after the background thread sends it away it is only the UI thread that touches it. (and you could use a simple ArrayList instead of a Vector)
AsyncTask uses generics and varargs.The parameters that are passed to the asyntask are . TypeOfVariableArgumentsParameters is passed into the doInBackground(), ProgressParam is used for progress information and ResultParam must be returned from doInBackground() and is passed to onPostExecute() as parameter.
example:--
protected class ParsingTask extends AsyncTask> {
private ProgressDialog loadingDialog = new ProgressDialog(JsonParserActivity.this);
protected void onPreExecute() {
loadingDialog.setMessage("loading app store..");
loadingDialog.show();
}
#Override
protected ArrayList<Items> doInBackground( Context... params ) {
// do ur process here.
return result;
}
if (!this.isCancelled()) {
}
return result;
}
#Override
protected void onProgressUpdate(String... s) {
super.onProgressUpdate(s);
Toast.makeText(getApplicationContext(), s[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute( ArrayList<Items> response ) {
//if u r dealing with list view and adapters set the adapter here at the onPostExecute()
loadingDialog.dismiss();
}
#Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(getApplicationContext(), "The operation was cancelled", 1).show();
}
}
You can use AsyncTask like below. Hope this will help you..
Class YourClass{
void YourClass(){
NetworkTask nT = new NetworkTasK();
nT.execute();
}
}
protected class NetworkTask extends AsyncTask<Void, String, Boolean>
{
#Override
protected Boolean doInBackground(Void... params)
{
try
{
String response;
while(keepreceiving)
{
response = in.readLine();//Prog Counter stops here until getting i/p.
if(response != null)
yourFunctionForResponse(response);
}
}
catch (Exception ex)
{
}
return null;
}
private void yourFunctionForResponse(String response){
//things to do....
}
}
You may also try runOnUiThread(Runnable action) along with this to implement your work.
I am trying to retrieve JPGs from an MJPG Stream using an async task. I first thought, i could let the task continuously be running and just letting the buffered JPGs pop up in the onProgressUpdate() method. But this doesn't seem to work, because the method only displays integers, no drawables...what I tried:
private class StreamTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
image = readMJPGStream();
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
imView.setImageDrawable(image); // << doesn't work
}
}
Do you have any ideas? What approach should I try?
Thank you very much in advance!
Huck
When you start a AsyncTask, the doInBackground is called, but it is only run once. I'm not sure what readMJPGStream does, but assuming it blocks until an image is retrieved, its certainly possible that onProgressUpdate gets called several times while your image is still null, then once image get set to something valid and doInbackground quickly exits, there are no further calls to OnProgressUpdate.
You should probably put the call to imView.setImageDrawable in onPostExecute to make sure it gets called when the image has been downloaded. You may also need to call invalidate() on your image view to ensure it gets redrawn. Additionally, if you intend to loop and continue downloading images, you'll need to devise a mechanism of triggering updates. In reality, the issue you're having is because you want 'on demand' get on the UI Thread, but you're dependent on calls to onProgressUpdate. You'd have much better luck using a Handler and your own Runnable/Thread because then when an image download completes, you can post to the UI thread (using the Handler) without having to wait for the onProgressUpdate.
I now got it running this way:
public class StreamActivity extends Activity implements Runnable{
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imView = (ImageView) findViewById(R.id.imView);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
while (connected){
image = readMJPGStream();
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
imView.setImageDrawable(image);
}
};
public Drawable readMJPGStream() {
//...
return image;
}
}
The only problem is that my while loop is not fast enough. Any ideas are very much appreciated!
Huck
I am using AsyncTask to perform some background calculations but I am unable to find a correct way to handle exceptions. Currently I am using the following code:
private class MyTask extends AsyncTask<String, Void, String>
{
private int e = 0;
#Override
protected String doInBackground(String... params)
{
try
{
URL url = new URL("http://www.example.com/");
}
catch (MalformedURLException e)
{
e = 1;
}
// Other code here...
return null;
}
#Override
protected void onPostExecute(String result)
{
if (e == 1)
Log.i("Some Tag", "An error occurred.");
// Perform post processing here...
}
}
I believe that the variable e maye be written/accessed by both the main and worker thread. As I know that onPostExecute() will only be run after doInBackround() has finished, can I omit any synchronization?
Is this bad code? Is there an agreed or correct way to handle exceptions in an AsyncTask?
I've been doing that in my apps, I guess there is not a better way.
You can also read Mark Murphy answer about it.
I think your code would to the job but there is already some kind of error handling built into the AsyncTask class.
You can avoid to use an extra variable by using the cancel() method and its handler method onCancelled(). When you call cancel within the doInBackground() method the onCancelled method in the UI thread. Whether you call cancel(true) or cancel(false) depends on your needs.
private class MyTask extends AsyncTask<String, Void, String>
{
#Override
protected NewsItem doInBackground(String... params)
{
try
{
URL url = new URL("http://www.example.com/");
}
catch (MalformedURLException e)
{
cancel(false/true);
}
// Other code here...
return null;
}
#Override
protected void onPostExecute(String result)
{
// Perform successful post processing here...
}
#Override
protected void onCancelled() {
super.onCancelled();
// Perform error post processing here...
}
}
This is guaranteed to work, even on SMP architecture. All the synchronization is done for you. It would however be better to use the return value to do this.