Download-Thread mit AsyncTask

  • 1 Antworten
  • Letztes Antwortdatum
W

Wicki12

Ambitioniertes Mitglied
0
Hallo,

mein Ziel:
ich will im UI-Thread einen Download starten, der in einem (AsyncTask)Thread laufen soll so dass ich im UI-Thread parallel dazu weiter arbeiten kann. So habe ich jedenfalls die Wirkungsweise von AsyncTask verstanden.
Es läuft auch alles soweit, nur ist der UI-Thread blockiert solange der Download läuft, ich kann den Button nicht aktivieren und keine Eingabe in das EditText-Feld machen. Kann mir das jemand erklären ? Wie kann man diese Blockade aufheben ?
Der Download wird durch eine Menü-Option gestartet, in einer ProgressBar ist die Fortschrittsanzeige zu sehen.

Hier der Code:
Code:
public class TestActivity2 extends Activity implements OnClickListener {
  private String TAG = "**** TEST, " + getClass().getSimpleName();
  EditText edittext;
  
  ProgressDialog mProgressDialog;
  DownloadFilesTask downloadFile;
  String urlsProz="http://apache.lauf-forum.at//commons/dbcp/binaries/commons-dbcp-1.4-bin.zip";

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button button = (Button) this.findViewById(R.id.button1);
    button.setOnClickListener(this);
    edittext = (EditText) findViewById(R.id.edittext);

    mProgressDialog = new ProgressDialog(this);
      mProgressDialog.setMessage("Progress...");
      mProgressDialog.setIndeterminate(false);
      mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  }

  @Override
  public void onClick(View v) {
        switch(v.getId()) {
        case R.id.button1 :  //Cancel download
            if (downloadFile != null)
                downloadFile.cancel(true);
            break;   
        }
  }

//************ OptionsMenu ************
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_1, menu);
    return true;
  }

  //Click on MENU-Button
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    String s = (String) item.getTitle();
    switch (item.getItemId()) {
      case R.id.item1:
        Log.i(TAG, s);
        downloadFile = new DownloadFilesTask();
        downloadFile.execute(urlsProz);
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  //solution from:
  //http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog
  private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
    //AsyncTask<Params, Progress, Result>
      long fileLength = 0;
    @Override
    protected Long doInBackground(String... sUrl) {
      long total = 0;
      try {
        URL url = new URL(sUrl[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        fileLength = connection.getContentLength();
        Log.i("**** fileLength:",""+fileLength);
        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/filexxx.yyy");

        byte data[] = new byte[1024];
        int count, i=0;
        while ((count = input.read(data)) != -1 && !isCancelled()) {
          total += count;
            if (++i % 10 == 0) {
            // publishing the progress in %-values
            publishProgress((int) (total * 100 / fileLength));
            }
          output.write(data, 0, count);
        }
        //display the 100%
        publishProgress((int) (total * 100 / fileLength));
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {}
        output.flush();
        output.close();
        input.close();
      } catch (Exception e) {
          e.printStackTrace();
      }
      return total;
    }
    @Override
    //showing the progress bar
    protected void onPreExecute() {
      super.onPreExecute();
      mProgressDialog.show();
      Log.i("**** ","onPreExecute");
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
      super.onProgressUpdate(progress);
      mProgressDialog.setProgress(progress[0]);
    }

    protected void onPostExecute(Long result) {
      String s = "Downloaded " + result + " bytes";
        Toast.makeText(getBaseContext(), s, Toast.LENGTH_LONG).show();
        this.cancel(true);
        mProgressDialog.dismiss();
    }
  }

}
main.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
          <Button
            android:id="@+id/button1"
            android:text="Button"
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
          />
          <EditText
            android:id="@+id/edittext"
            android:inputType="numberDecimal"
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
          />
</LinearLayout>
menu_1.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<menu
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/item1" android:icon="@drawable/copy" android:title="download Prozent" ></item>
</menu>
Gruss Wicki

Der ursprüngliche Beitrag von 15:44 Uhr wurde um 16:38 Uhr ergänzt:

Inzwischen habe ich eine Erklärung gefunden. Die Blockade wird durch die Fortschrittsanzeige (ProgressDialog) ausgelöst. Wenn ich alles entferne, was zum mProgressDialog gehört und in onProgressUpdate dann bspw.
Code:
textview.setText("Prozent:"+progress[0]);
statt der mProgressDialog-Anweisung einsetze, funktioniert das Ganze. Das textview-Element ist dann z.B. eine TextView im UI-Thread.
Bitte um Entschuldigung, dass mir das nicht etwas eher eingefallen ist.

Gruss Wicki
 
Trotzdem ist die Progress bar ja für solche Zwecke gedacht mich würde schon interessieren wie man das verändern müsste

Gesendet von meinem GT-S5660 mit der Android-Hilfe.de App
 

Ähnliche Themen

AnnaBauer21
Antworten
6
Aufrufe
1.019
AnnaBauer21
AnnaBauer21
Zurück
Oben Unten