Visualizzazione dei risultati da 1 a 10 su 13

Hybrid View

  1. #1
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,320
    Ecco un esempio di AsyncTask che scarica un file da un server remoto...

    codice:
        private class DwTask extends AsyncTask<String, Integer, String> {
            
            private static final String TAG = "NomeApp.class";
            private int fileLength;
            private Context ctx;
            private final ProgressDialog dialogUpdate;
            
            public DwTask(Context ctx, int fileLength) {
                this.ctx = ctx;
                this.fileLength = fileLength;
                dialogUpdate = new ProgressDialog( ctx );
            }
            
            @Override
            public void onPreExecute() {
                dialogUpdate.setMessage("Download file in progress...");
                dialogUpdate.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
                dialogUpdate.setIndeterminate( false );
                dialogUpdate.setMax( 100 );
                dialogUpdate.setProgress(0);
                dialogUpdate.setCancelable( false );
                dialogUpdate.setCanceledOnTouchOutside( false );
                dialogUpdate.show();
            }
            
            @Override
            protected String doInBackground(String... fileUrl) {
                String localPath = Environment.getExternalStorageDirectory().getPath() + "/NomeApp/dwnldFile.txt";
                InputStream input = null;
                OutputStream output = null;
                try {
                    // Mi connetto al URL
                    URL url = new URL( fileUrl[0] );
                    URLConnection connection = url.openConnection();
                    connection.connect();
    
                    // Apro gli stream di input/output
                    input = url.openStream();
                    output = new FileOutputStream( localPath );
                    
                    // Scarico il file a blocchi di 1024 byte
                    byte data[] = new byte[1024];
                    int total = 0;
                    int count;
                    int lastProgress = 0;
                    while ((count = input.read(data)) != -1) {
                        output.write(data, 0, count);
                        output.flush();
                        total += count;
                        Integer byteProgress = (total * 100) / fileLength;
                        if (byteProgress != lastProgress) {
                            publishProgress( byteProgress );
                            lastProgress = byteProgress;
                        }
                    }
    
                    // Effettuo il flush
                    output.flush();
                } catch (Exception e) {
                    Log.e(TAG, "Error in download of file", e);
                } finally {
                    if (output != null) {
                        try { output.close(); } catch (Exception e) { }
                    }
                    if (input != null) {
                        try { input.close(); } catch (Exception e) { }
                    }
                }
                return localPath;
            }
            
            @Override
            protected void onProgressUpdate(Integer... values) {
                dialogUpdate.setProgress(values[0]);
                super.onProgressUpdate(values);
            }
            
            @Override
            protected void onPostExecute(String path) {
                dialogUpdate.dismiss();
            }
        }

    Come vedi, è stato fatto l'override di diversi metodi, tra i quali anche onPostExecute().


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

  2. #2
    Quote Originariamente inviata da LeleFT Visualizza il messaggio
    Ecco un esempio di AsyncTask che scarica un file da un server remoto...

    codice:
        private class DwTask extends AsyncTask<String, Integer, String> {
            
            private static final String TAG = "NomeApp.class";
            private int fileLength;
            private Context ctx;
            private final ProgressDialog dialogUpdate;
            
            public DwTask(Context ctx, int fileLength) {
                this.ctx = ctx;
                this.fileLength = fileLength;
                dialogUpdate = new ProgressDialog( ctx );
            }
            
            @Override
            public void onPreExecute() {
                dialogUpdate.setMessage("Download file in progress...");
                dialogUpdate.setProgressStyle( ProgressDialog.STYLE_HORIZONTAL );
                dialogUpdate.setIndeterminate( false );
                dialogUpdate.setMax( 100 );
                dialogUpdate.setProgress(0);
                dialogUpdate.setCancelable( false );
                dialogUpdate.setCanceledOnTouchOutside( false );
                dialogUpdate.show();
            }
            
            @Override
            protected String doInBackground(String... fileUrl) {
                String localPath = Environment.getExternalStorageDirectory().getPath() + "/NomeApp/dwnldFile.txt";
                InputStream input = null;
                OutputStream output = null;
                try {
                    // Mi connetto al URL
                    URL url = new URL( fileUrl[0] );
                    URLConnection connection = url.openConnection();
                    connection.connect();
    
                    // Apro gli stream di input/output
                    input = url.openStream();
                    output = new FileOutputStream( localPath );
                    
                    // Scarico il file a blocchi di 1024 byte
                    byte data[] = new byte[1024];
                    int total = 0;
                    int count;
                    int lastProgress = 0;
                    while ((count = input.read(data)) != -1) {
                        output.write(data, 0, count);
                        output.flush();
                        total += count;
                        Integer byteProgress = (total * 100) / fileLength;
                        if (byteProgress != lastProgress) {
                            publishProgress( byteProgress );
                            lastProgress = byteProgress;
                        }
                    }
    
                    // Effettuo il flush
                    output.flush();
                } catch (Exception e) {
                    Log.e(TAG, "Error in download of file", e);
                } finally {
                    if (output != null) {
                        try { output.close(); } catch (Exception e) { }
                    }
                    if (input != null) {
                        try { input.close(); } catch (Exception e) { }
                    }
                }
                return localPath;
            }
            
            @Override
            protected void onProgressUpdate(Integer... values) {
                dialogUpdate.setProgress(values[0]);
                super.onProgressUpdate(values);
            }
            
            @Override
            protected void onPostExecute(String path) {
                dialogUpdate.dismiss();
            }
        }

    Come vedi, è stato fatto l'override di diversi metodi, tra i quali anche onPostExecute().


    Ciao.
    Ottimo! Però ho un dubbio: Posso fare l'Override anche se la classe Asynctask (nel mio caso httpConnection) è esterna alla MainActivity?
    Non sei qui per fare una scelta, la scelta l'hai già fatta...Ora devi comprendere le ragioni per cui l'hai fatta. Non possiamo vedere oltre le scelte che non ci sono chiare. http://www.chicercatrova2000.it

Tag per questa discussione

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.