2016-08-01 1 views
0

나는 여전히 첫 번째 앱을 만들려고 노력하고 있습니다. 그래서, 그것은 자랍니다 ... 나는 그것을 몇 팩에 나누려고 노력합니다. 첫 번째 팩은 파일과 함께 작동하며 파일 다운로드, 파일 및 기타 등등의 데이터 읽기를 수행 할 수있는 클래스를 포함합니다.Android : 다른 팩의 활동에서 비동기 작업의 ProgressDailog를 표시하는 방법?

그래서 주 활동 첫 번째 클래스에서 벗어나려고하지만 ProgressDialog에 문제가있어 작동하지 않습니다. 따라서 몇 가지 질문이 있습니다.

1) 내 응용 프로그램의 활동에 다운로드하는 %를 보내는 가장 좋은 방법은 무엇입니까? 2) 다운로드 진행 중에 사용자가 현재 활동을 변경하면 어떻게됩니까?

package com.domen.myapplication.Files; 

import android.app.ProgressDialog; 
import android.content.Context; 
import android.os.AsyncTask; 
import android.os.PowerManager; 
import android.widget.Toast; 


import com.domen.myapplication.R; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 

/** 
* Created by DL on 01.08.2016. 
*/ 
public class DownloadTask extends AsyncTask<String, Integer, String> { 

    private Context context; 
    private PowerManager.WakeLock mWakeLock; 
    public int progress=0; 
    public int progressShow=0; 
    public ProgressDialog mProgressDialog; 




    public DownloadTask(Context context) { 
     this.context = context; 

     mProgressDialog = new ProgressDialog(this.context); 
     mProgressDialog.setMessage(this.context.getResources().getString(R.string.loading_empty)); 
     mProgressDialog.setIndeterminate(true); 
     mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
     mProgressDialog.setCancelable(true); 


    } 

    @Override 
    protected String doInBackground(String... sUrl) { 
     InputStream input = null; 
     OutputStream output = null; 
     HttpURLConnection connection = null; 
     try { 
      URL url = new URL(sUrl[0]); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 

      // expect HTTP 200 OK, so we don't mistakenly save error report 
      // instead of the file 
      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       return "Server returned HTTP " + connection.getResponseCode() 
         + " " + connection.getResponseMessage(); 
      } 

      // this will be useful to display download percentage 
      // might be -1: server did not report the length 
      int fileLength = connection.getContentLength(); 

      // download the file 
      input = connection.getInputStream(); 
      //output = new FileOutputStream("/sdcard/file_name.extension"); 


      File cacheFile = new File(this.context.getCacheDir(), "FIRMWARE"); 

      output = new FileOutputStream(cacheFile); 

      byte data[] = new byte[4096]; 
      long total = 0; 
      int count; 
      while ((count = input.read(data)) != -1) { 
       // allow canceling with back button 
       if (isCancelled()) { 
        input.close(); 
        return null; 
       } 
       total += count; 
       // publishing the progress.... 
       if (fileLength > 0) // only if total length is known 
        publishProgress((int) (total * 100/fileLength)); 
       output.write(data, 0, count); 
      } 
     } catch (Exception e) { 
      return e.toString(); 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
      } catch (IOException ignored) { 
      } 

      if (connection != null) 
       connection.disconnect(); 
     } 
     return null; 
    } 


    //метод выше (doInBackground) запускается отдельным поток все сотальное ниже в главном потоке 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // take CPU lock to prevent CPU from going off if the user 
     // presses the power button during download 
     PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 
     mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
       getClass().getName()); 
     mWakeLock.acquire(); 
     progressShow=1; 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 
     super.onProgressUpdate(progress); 
     // if we get here, length is known, now set indeterminate to false 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.setMax(100); 
     mProgressDialog.setProgress(progress[0]); 
     this.progress=progress[0]; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     mWakeLock.release(); 
     progressShow=1; 
     mProgressDialog.dismiss(); 
     if (result != null) 
      Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show(); 
     else 
      Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show(); 
    } 


} 

답변

1

활동에서만 파일을 다운로드하려면 활동의 내부 클래스로 AsyncTask를 작성하여 사용하십시오.

활동에 관계없이 파일을 다운로드하려면 서비스를 만들고 서비스에 다운로드 논리를 구현하고 서비스에서 파일 다운로드 진행 알림을 표시하고 다운로드 백분율로 업데이트하십시오. Play 스토어 앱 다운로드 진행 상황과 동일합니다.

두 번째 질문 다운로드 진행 중에 사용자가 현재 활동을 변경하면 어떻게됩니까?

예, 비동기 작업은 작업이 완료된 후에도 작업이 완료 될 때까지 실행됩니다. 자세한 정보를 보려면이 링크를 확인하십시오. https://stackoverflow.com/a/13147992/1066839

+0

아, 도움이되었습니다. 감사! 내 앱에 이미 하나의 서비스가 있습니다. 따라서 사용자가 현재 활동을 변경하면 서비스가 작동합니까? 그리고 새로운 활동에서 다시 바인딩해야합니까? 내 응용 프로그램에는 하나의 활동 만 있고 ViewFlipper 변경 화면의 도움을받습니다. (하지만이게 좋지 않다고 생각합니까?) –

+0

서비스가 이미있는 경우. 서비스 내에서 스레드를 생성하고 서비스를 시작하고 파일을 다운로드하고 파일 진행 상황에 대한 알림을 표시합니다. – John

+0

내 서비스가 블루투스 연결을 관리하고 있습니다. 그리고 나는 하나의 서비스를 더 가질 필요가 있다고 생각한다. –

관련 문제