Android Asynctask и progressDialog - PullRequest
2 голосов
/ 29 июля 2011

То, что я хотел бы сделать, это дать моему приложению возможность загружать мои mp3 с моего сервера. Пока что у меня есть загрузка mp3 в аудио файл, но он очень привередливый и не может быть нарушен для правильной работы. При этом я хотел бы, чтобы появилось всплывающее диалоговое окно прогресса, которое нельзя отменить, чтобы пользователь не мог прервать процесс при загрузке файла в папку в фоновом режиме. После прочтения казалось, что AsyncTask будет лучшим способом сделать это, но я не могу заставить его работать. Ниже одна из кнопок из моего кода.

расширяет классную музыку. Деятельность {

    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, он работает, он просто крайне не удобен для пользователя, но файлы действительно загружаются. Когда я пытаюсь добавить диалог прогресса и фоновое задание, оно выходит из-под контроля. У меня есть ощущение, что это связано с параметрами.

Ответы [ 2 ]

2 голосов
/ 29 июля 2011

Просто быстрое сканирование, я не думаю, что вы должны вызывать msg.show ();из фоновой темы.

2 голосов
/ 29 июля 2011
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();
    }
}

Попробуйте, альтернативный способ показать диалог

...