misco
misco

Reputation: 1952

android wait activity for thread

How can I wait for thread processing in the activity. My thread downloads .png picture from remote server. I want to wait for downloading the picture, and then the activity will be continue in the processing.

Activity

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.initializer);

    ImageView mainImageView = (ImageView) findViewById(R.id.imageView);
    ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

    InitProgress initProgress = new InitProgress(progressBar); // initialization progress bar
    MyMap map = new MyMap(); // there is written the picture as Drawable from thread

    MapDownloader mapDownloader = new MapDownloader(map,initProgress); // thread that download picture from server

    // wait ???

    mainImageView.setBackgroundDrawable(buildingMap.getDrawableMap()); // using downloaded picture
    }

This code continues without downloaded picture, the picture is downloaded later. Are the semaphores suitable for this purpose?

Upvotes: 1

Views: 1115

Answers (3)

If you don't want to be constrained to an ASyncTask, use a BroadcastReceiver. You will listen for the BroadcastReceiver in your main class by registering it in the OnResume() method of the activity. When your Service or background activity finishes you will trigger the BroadcastReceiver to tell the activity the background service is done.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, WordService.class);
        context.startService(service);
        }

Upvotes: 1

coder_For_Life22
coder_For_Life22

Reputation: 26971

You should use AsyncTask for this purpose.

Here is an example

public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

ImageView imageView = null;

@Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}

@Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}


private Bitmap download_Image(String url) {
...

}

Upvotes: 0

ahodder
ahodder

Reputation: 11439

Use an AsyncTask paired with a LoadingBar Dialog. This will display progress as the png downloads.

Then once the download is complete use the onPostExecute() method in AsyncTask to continue on with what ever you want your activity to do.

Upvotes: 0

Related Questions