2012-06-06 3 views
8

Ich weiß, dass wir integrierte Download-Manager in Android 2.3 und höher verwenden können, aber meine App ist für Android 2.2 und höher geeignet. Meine Frage ist, wie man eigene Download-Manager in Android erstellen 2.2? Bitte geben Sie mir eine Beispielantwort.wie man eigenen Download-Manager in Android 2.2

Antwort

27

bitte geben Sie mir eine Beispielantwort.

Schritt 1 Suchen Sie nach Beispiel dafür, wie Dateien im Android zum Download

Schritt 2 Suchen Sie nach Beispiel dafür, wie Operationen in AsyncTask auszuführen.

Schritt 3 Suchen Sie zum Beispiel nach, wie der Download-Fortschritt beim Herunterladen angezeigt wird.

Step4 Suchen Sie nach Beispiel dafür, wie kundenspezifische Übertragung zu senden, wenn Task-

abgeschlossen ist

Schritt 5 Suchen Sie nach Beispiel dafür, wie AsysncTask Betrieb auch auf Gerätedrehung auf Persist

Step6 Suchen Sie nach Beispiel dafür, wie Download-Fortschritt anzeigen in Benachrichtigung.

Unten ist Beispielcode.

1. Verwenden AsyncTask und zeigen die Download Fortschritt in einem Dialog

// declare the dialog as a member field of your activity 
ProgressDialog mProgressDialog; 

// instantiate it within the onCreate method 
mProgressDialog = new ProgressDialog(YourActivity.this); 
mProgressDialog.setMessage("A message"); 
mProgressDialog.setIndeterminate(false); 
mProgressDialog.setMax(100); 
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 

// execute this when the downloader must be fired 
DownloadFile downloadFile = new DownloadFile(); 
downloadFile.execute("the url to the file you want to download"); 

The AsyncTask will look like this: 

// usually, subclasses of AsyncTask are declared inside the activity class. 
// that way, you can easily modify the UI thread from here 
private class DownloadFile extends AsyncTask<String, Integer, String> { 
    @Override 
    protected String doInBackground(String... sUrl) { 
     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 
      int fileLength = connection.getContentLength(); 

      // download the file 
      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/file_name.extension"); 

      byte data[] = new byte[1024]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       // publishing the progress.... 
       publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
     } 
     return null; 
    } 

Die oben beschriebene Methode (doInBackground) läuft immer auf einem Hintergrund-Thread. Sie sollten dort keine UI-Aufgaben ausführen. Auf der anderen Seite, die onProgressUpdate und OnPreExecute auf dem UI-Thread ausgeführt werden, so dass es können Sie den Fortschrittsbalken ändern:

@Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     mProgressDialog.show(); 
    } 

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

2. Herunterladen von Service-

Die große Frage ist: Wie Ich aktualisiere meine Aktivität von einem Dienst ?. Im nächsten Beispiel verwenden wir zwei Klassen, die Ihnen vielleicht nicht bekannt sind: ResultReceiver und IntentService. ResultReceiver ist der, mit dem wir unseren Thread von einem Dienst aktualisieren können; IntentService ist eine Unterklasse von Service, die einen Thread für die Hintergrundarbeit von dort erzeugt (Sie sollten wissen, dass ein Service tatsächlich im selben Thread Ihrer App ausgeführt wird. Wenn Sie den Service erweitern, müssen Sie manuell neue Threads generieren, um CPU-Blockierungsvorgänge auszuführen) .

Download-Service kann wie folgt aussehen:

public class DownloadService extends IntentService { 
    public static final int UPDATE_PROGRESS = 8344; 
    public DownloadService() { 
     super("DownloadService"); 
    } 
    @Override 
    protected void onHandleIntent(Intent intent) { 
     String urlToDownload = intent.getStringExtra("url"); 
     ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver"); 
     try { 
      URL url = new URL(urlToDownload); 
      URLConnection connection = url.openConnection(); 
      connection.connect(); 
      // this will be useful so that you can show a typical 0-100% progress bar 
      int fileLength = connection.getContentLength(); 

      // download the file 
      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk"); 

      byte data[] = new byte[1024]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       total += count; 
       // publishing the progress.... 
       Bundle resultData = new Bundle(); 
       resultData.putInt("progress" ,(int) (total * 100/fileLength)); 
       receiver.send(UPDATE_PROGRESS, resultData); 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     Bundle resultData = new Bundle(); 
     resultData.putInt("progress" ,100); 
     receiver.send(UPDATE_PROGRESS, resultData); 
    } 
} 

den Dienst zu Ihrem Manifest hinzufügen:

<service android:name=".DownloadService"/> 

und die Aktivität wird wie folgt aussehen:

// den Fortschrittsdialog initialisieren wie im ersten Beispiel

// So feuern Sie den Downloader

mProgressDialog.show(); 
Intent intent = new Intent(this, DownloadService.class); 
intent.putExtra("url", "url of the file to download"); 
intent.putExtra("receiver", new DownloadReceiver(new Handler())); 
startService(intent); 

hier waren, ist ResultReceiver kommt zu spielen:

Beantwortungs
private class DownloadReceiver extends ResultReceiver{ 
    public DownloadReceiver(Handler handler) { 
     super(handler); 
    } 

    @Override 
    protected void onReceiveResult(int resultCode, Bundle resultData) { 
     super.onReceiveResult(resultCode, resultData); 
     if (resultCode == DownloadService.UPDATE_PROGRESS) { 
      int progress = resultData.getInt("progress"); 
      mProgressDialog.setProgress(progress); 
      if (progress == 100) { 
       mProgressDialog.dismiss(); 
      } 
     } 
    } 
} 
+0

Dank. Ich werde es versuchen. –

+3

Wenn es Ihr Problem löst, vergessen Sie nicht, Antwort zu akzeptieren, da es anderen Benutzern hilft, –

Verwandte Themen