2011-07-29 7 views
2

내 앱에서 내 서버의 mp3를 다운로드 할 수있게하고 싶습니다. 지금까지 오디오 파일을 다운로드하는 mp3 파일을 가지고 있지만 매우 까다 롭고 제대로 작동하기 위해서는 방해를받을 수 없습니다. 즉, 나는 백그라운드에서 폴더에 파일을 다운로드하는 동안 사용자가 진행을 방해 할 수 없도록 취소 할 수없는 진행 대화 상자 팝업을 갖고 싶다고 말하고 있습니다. 독서 후 AsyncTask가이 작업을 수행하는 가장 좋은 방법 인 것처럼 보였지만 제대로 작동하지 않습니다. 아래는 내 코드의 버튼 중 하나입니다.Android Asynctask and progressDialog

공용 클래스 음악 활동 {

public static int mProgress = 0; 
    static String filename; 
    MediaPlayer buttonclicker; 
    static Toast msg; 
    public static int totalSize = 0; 
    public ProgressDialog dialog; 
    public static boolean isFinished; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.music); 
    buttonclicker = MediaPlayer.create(this, R.raw.button); 
    Button boomFullDownload = (Button) findViewById(R.id.boomfull); 

boomFullDownload.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      buttonclicker.start(); 
      filename = "boomboom.mp3"; 
      new downloadPumphouseShow().execute(filename); 

}

class downloadPumphouseShow extends AsyncTask<String , Void, Void> { 

    ProgressDialog dialog; 

    Toast msg; 

    protected void onPreExecute(){ 
     dialog = new ProgressDialog(context); 
     msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG); 
     msg.setGravity(Gravity.CENTER, msg.getXOffset()/2, msg.getYOffset()/2); 
     dialog.setMessage("Please Wait Loading"); 
     dialog.setCancelable(false); 
     dialog.show(); 

    } 
} 
    }); 

    protected void onPostExecute(Void result) { 
     dialog.hide(); 
     dialog.dismiss(); 
     } 


    protected Void doInBackground(String... params) { 

     String filename = params[0]; 

    try { 

      //set the download URL, a url that points to a file on the internet 
      //this is the file to be downloaded 
      URL url = new URL("http://lepumphouse.com/media/" + filename); 

      //create the new connection 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

      //set up some things on the connection 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.setDoOutput(true); 

      //and connect! 
      urlConnection.connect(); 

      //set the path where we want to save the file 
      //in this case, going to save it on the root directory of the 
      //sd card. 
      File Music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/Pumphouse/Party Cake"); 

     //create a new file, specifying the path, and the filename 
      if(Music.exists()) 
       msg.show(); 
      else 
       Music.mkdirs(); 
      //which we want to save the file as. 
      File file = new File(Music, filename); 

      //this will be used to write the downloaded data into the file we created 
      FileOutputStream fileOutput = new FileOutputStream(file); 

      //this will be used in reading the data from the internet 
      InputStream inputStream = urlConnection.getInputStream(); 

      //this is the total size of the file 
      int totalSize = urlConnection.getContentLength(); 
      //variable to store total downloaded bytes 
      int mProgress = 0; 

      //create a buffer... 
      byte[] buffer = new byte[1024]; 
      int bufferLength = 0; //used to store a temporary size of the buffer 

      //now, read through the input buffer and write the contents to the file 
      while ((bufferLength = inputStream.read(buffer)) > 0) { 
        //add the data in the buffer to the file in the file output stream (the file on the sd card 
        fileOutput.write(buffer, 0, bufferLength); 
        //add up the size so we know how much is downloaded 
        mProgress += bufferLength; 
        //this is where you would do something to report the pr0gress, like this maybe 


      } 
      //close the output stream when done 


      // progressDialog.dismiss(); 
      fileOutput.close(); 

    //catch some possible errors... 
    } catch (MalformedURLException e) { 

     e.printStackTrace(); 
    } catch (IOException e) { 

     e.printStackTrace(); 
    } 

    return null; 
    } 

    } 

} 나는 그것이 친화적 인 단지 매우되지 않은 사용자의 작업 AsyncTask를 다루는 모든 코드를 제거한다면

를 확장 그러나 파일은 다운로드됩니다. 진행 대화 상자와 백그라운드 작업을 추가하려고하면 종료됩니다. 매개 변수와 관련이 있다는 느낌이 들었습니다.

+1

무엇이 오류입니까? 로그에서 나타난 오류를 게시하십시오. – ayublin

+0

AsycnTask doc : http://developer.android.com/reference/android/os/AsyncTask.html 진행 상황을 표시하려면 예제에 표시된대로 onProgressUpdate를 사용해야합니다. – ania

답변

2
protected void onPreExecute() { 
    dialog=ProgressDialog.show(mContext, "", "Fetching book oversight"); 
    msg = Toast.makeText(context, " File Exist ", Toast.LENGTH_LONG).show; 
    super.onPreExecute(); 
} 



protected void onPostExecute(Void result) { 
    if(dialog!=null) 
    { 
     dialog.dismiss(); 
    } 
} 

) 나는 (당신이 msg.show를 호출해야한다고 생각하지 않는다, 대화

2

그냥 빠른 검사를 표시하는 다른 방법을이 시도; 배경 스레드에서.

관련 문제