Android: jak czekać na zakończenie AsyncTask w MainThread?
Wiem, że najpierw to zrobisz... dlaczego do cholery na świecie używasz AsyncTask.
Więc tutaj jest mój problem pracuję na jakiejś aplikacji na Androida (API 7 dla Androida 2.1 lub nowszy), i jestem testowanie na emulatorze i wszystko było w porządku, więc potem testowałem na HTC Sensation i mówi NetworkOnMainThreadExeption!
Ściągałem zdjęcia, a potem rysowałem na mapie.Więc aby rozwiązać ten problem każdy (połączenie internetowe) w tym przypadku pobieranie zdjęć muszę umieścić na AsyncTask do pracy.
Więc potrzebuję metody, jak wiedzieć, kiedy wszystkie zdjęcia są zrobione, aby móc zacząć rysować..
Tak bardzo się starałem i żadnego rezultatu nie mam pojęcia. Mam jedno rozwiazanie z handlerem ale jak dzialam na wolniejszym netie dostaję nullpointer (bo zdjecia nie sa pobierane).
Więc proszę, pomóż mi.EDIT:
Oto pomysł:
Bitmap bubbleIcon ;
onCreate(){
...
// i am making call for Async
new ImgDown().execute(url);
//and then i calling functions and classes to draw with that picture bubbleIcon !
DrawOnMap(bubbleIcon);
}
//THIS IS ASYNC AND FOR EX. SUPPOSE I NEED TO DOWNLOAD THE PIC FIRST
class ImgDown extends AsyncTask<String, Void, Bitmap> {
private String url;
public ImgDown() {
}
@Override
protected Bitmap doInBackground(String... params) {
url = params[0];
try {
return getBitmapFromURL(url);
} catch (Exception err) {
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
bubbleIcon = result;
bubbleIcon = Bitmap
.createScaledBitmap(bubbleIcon, 70, 70, true);
}
public Bitmap getBitmapFromURL(String src) {
try {
Log.e("src", src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
// /tuka decode na slika vo pomalecuk kvalitet!
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
Bitmap myBitmap = BitmapFactory
.decodeStream(new FlushedInputStream(input));
Log.e("Bitmap", "returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("getBitmapFromURL", e.getMessage());
return null;
}
}
class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int byteValue = read();
if (byteValue < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
}
Mam nadzieję, że teraz jest jaśniej. 4 answers
class OpenWorkTask extends AsyncTask {
@Override
protected Boolean doInBackground(String... params) {
// do something
return true;
}
@Override
protected void onPostExecute(Boolean result) {
// The results of the above method
// Processing the results here
myHandler.sendEmptyMessage(0);
}
}
Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
// calling to this function from other pleaces
// The notice call method of doing things
break;
default:
break;
}
}
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-22 11:21:57
Możesz napisać własnego delegata, aby przekazał informacje o zakończeniu zadania, używając zasad OOP:
Task_delegate.java
public interface TaskDelegate {
void TaskCompletionResult(String result);
}
Main_activity.java
public class MainActivity extends Activity implements TaskDelegate {
//call this method when you need
private void startAsynctask() {
myAsyncTask = new MyAsyncTask(this);
myAsyncTask.execute();
}
//your code
@Override
public void TaskCompletionResult(String result) {
GetSomethingByResult(result);
}
}
My_asynctask.java
public class MyAsyncTask extends AsyncTask<Void, Integer, String> {
private TaskDelegate delegate;
protected MyAsyncTask(TaskDelegate delegate) {
this.delegate = delegate;
}
//your code
@Override
protected void onPostExecute(String result) {
delegate.TaskCompletionResult(result);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-30 12:48:18
class openWorkTask extends AsyncTask<String, String, Boolean> {
@Override
protected Boolean doInBackground(String... params) {
//do something
return true;
}
@Override
protected void onPostExecute(Boolean result) {
// The results of the above method
// Processing the results here
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-26 02:29:40
Na Twoim miejscu użyłbym okna postępu. W ten sposób użytkownicy mogą zobaczyć, że coś się dzieje, podczas gdy ASyncTask pobiera obraz. W postexecute wywołaj metodę z głównego kodu, która sprawdza, czy obrazki są null. Pamiętaj, że nie możesz zaktualizować interfejsu użytkownika w metodzie doInBackground, więc każdy interfejs działa zarówno w onPreExecute, jak i onPostExecute
private class DownloadPictures extends AsyncTask<String, Void, String>
{
ProgressDialog progressDialog;
@Override
protected String doInBackground(String... params)
{
//Download your pictures
return null;
}
@Override
protected void onPostExecute(String result)
{
progressDialog.cancel();
//Call your method that checks if the pictures were downloaded
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(
YourActivity.this);
progressDialog.setMessage("Downloading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected void onProgressUpdate(Void... values) {
// Do nothing
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-26 02:11:11