Android Asynctask和progressDialog

发布于 2024-11-27 01:08:39 字数 4480 浏览 1 评论 0原文

我想做的是让我的应用程序能够下载我的服务器的 mp3。到目前为止,我已经将 mp3 下载到音频文件中,但它非常挑剔,不能被干扰才能正常工作。话虽这么说,我希望弹出一个无法取消的进度对话框,这样用户在将文件下载到后台文件夹时就无法中断进度。读完后,似乎 AsyncTask 是执行此操作的最佳方法,但我无法让它工作。下面是我的代码中的按钮之一。

public class music extends Activity {

    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 的代码,它就可以工作,这对用户来说非常不友好,但文件确实会下载。当我尝试添加进度对话框和后台任务时,它退出了。我感觉这和参数有关。

What I would like to do is give my app the ability to download my mp3 of my server. So far I have the download mp3 into a audio file working but it's very finicky and cannot be disturbed in order for it to work properly. That being said I would love to have a progress dialog pop up that cannot be canceled so the user can't interrupt the progress while downloading the file to the folder in the background. After reading it seemed that AsyncTask would be the best way to do this but I cannot get it to work. Below is one of the buttons from my code.

public class music extends Activity {

    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;
    }

    }

}

So if I stripped out all the code dealing with asynctask it works it's just extremely un-user friendly but the files do download. When I try to add the progress dialog and background task it quits on me. I have a feeling it has to do with the parameters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

水溶 2024-12-04 01:08:39
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();
    }
}

试试这个,显示对话框的另一种方式

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();
    }
}

Try this, a alternate way to show Dialog

凉世弥音 2024-12-04 01:08:39

只是快速扫描一下,我认为你不应该调用 msg.show();来自后台线程。

Just a quick scan, I don't think you should be calling msg.show(); from the background thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文