通过asynctask下载mp3文件并有进度条listview android

发布于 2024-11-29 20:30:02 字数 6755 浏览 2 评论 0原文

我有一个异步任务

new DownloadFile().execute(url2.toString());

当我在 url 上找到 mp3 文件(例如 www.xyz.com/preview.mp3

)时,我将上述异步任务称为

new DownloadFile().execute(url2.toString());

然后我在列表视图中也有一个进度条,但现在进度条没有更新 我使用自定义适配器并正确地放大了视图。

                 public class CopyOfDownloadsListActivity extends ListActivity {
                /** Called when the activity is first created. */

                //  static ArrayList<String> pthreads = new ArrayList<String>();
                static ImageView bt;
                static ProgressBar pb;
                static ListView allList;
                static TextView tv;
                String fileName;
                String mp3URL;
                URL url2;
                int myProgress;
                static int filecount  = 0;
                MyCustomAdapter adapter;

                private class DownloadFile extends AsyncTask<String, Integer, Void>{
                    int count = 0;
                    ProgressDialog dialog;
                    int myProgess = 0;
                    ProgressBar progressBar;

                    @Override
                    protected Void doInBackground(String... u) {

                        try {                   
                            URL ul = new URL(u[0]);
                            Log.i("UI",ul.toString());
                       //   int len = CopyOfMusicDownloader.mp3urls.size();
                       //   URL url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                            HttpURLConnection c = (HttpURLConnection) ul.openConnection();
                            c.setRequestMethod("GET");
                            c.setDoOutput(true);
                            c.connect();

                            int lengthOfFile = c.getContentLength();

                            String PATH = Environment.getExternalStorageDirectory()
                                    + "/download/";
                            Log.v("", "PATH: " + PATH);
                            File file = new File(PATH);
                            file.mkdirs();

                            fileName = "Track";
                            filecount++;

                            fileName =  fileName + Integer.toString(filecount) + ".mp3";


                            File outputFile = new File(file, fileName);
                            FileOutputStream fos = new FileOutputStream(outputFile);
                            InputStream is = c.getInputStream();

                            byte[] buffer = new byte[1024];
                            int len1 = 0;      
                            while ((len1 = is.read(buffer)) != -1) {
                                myProgress = (int)(len1*100/lengthOfFile);
                                //myProgress = (int)(len1);

                                Log.i("My Progress", Integer.toString(myProgress));
                                publishProgress(myProgress);
                                //  publishProgress((int)(len1*100/lengthOfFile));
                                fos.write(buffer, 0, len1);
                            }
                            fos.close();
                            is.close();

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

                    protected void onPostExecute() {

                    }

                    @Override
                    protected void onPreExecute() {
                          setListAdapter(new MyCustomAdapter(CopyOfDownloadsListActivity.this, R.layout.row, CopyOfMusicDownloader.mp3urls));

                    }



                    @Override
                    protected void onProgressUpdate(Integer... values) {
                         pb.setProgress(count);// HERE IS THE PROBLEM

                         count++;
                         Log.i("Values", Integer.toString(values[0]));
                    }
                 }  

                @Override
                public void onCreate(Bundle savedInstanceState) {
                    requestWindowFeature(Window.FEATURE_NO_TITLE);
                    super.onCreate(savedInstanceState);

                    int len = CopyOfMusicDownloader.mp3urls.size();
                    try {
                        url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                        new DownloadFile().execute(url2.toString());
                        Log.i("url",url2.toString());
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                 }

                @Override
                public boolean onCreateOptionsMenu(Menu menu) {
                     MenuInflater myMenuInflater = getMenuInflater();
                     myMenuInflater.inflate(R.menu.menu, menu);
                    return true;
                }

                @Override
                public boolean onOptionsItemSelected(MenuItem item) {
                     switch(item.getItemId()){
                     case(R.id.browsermenu):
                     Intent i = new Intent(CopyOfDownloadsListActivity.this, MusicDownloader.class);  
                     startActivity(i);
                     break;
                     case(R.id.downloaderrmenu):      
                     break; 
                     case(R.id.playermenu):
                     Intent j = new Intent(CopyOfDownloadsListActivity.this, Players.class);  
                     startActivity(j);
                    break;
              }
                 return true;
                }


                public class MyCustomAdapter extends ArrayAdapter<String> {     
                    public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<String> pthreads) {
                    super(context, textViewResourceId, pthreads);
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                            LayoutInflater inflater = getLayoutInflater();
                            View row = inflater.inflate(R.layout.row, parent, false);
                            bt =(ImageView)row.findViewById(R.id.cancel_btn);
                            tv =(TextView)row.findViewById(R.id.filetext);
                            pb = (ProgressBar)row.findViewById(R.id.progressbar_Horizontal);
                            return row;
                        }
                    }


            }

I have an async task

new DownloadFile().execute(url2.toString());

When ever i find a mp3 file on url for example www.xyz.com/preview.mp3

I call the above async task

new DownloadFile().execute(url2.toString());

Then i also have a progress bar in a list view, But now the progress bar isnt updated
I use a custom adapter and have inflated the view properly.

                 public class CopyOfDownloadsListActivity extends ListActivity {
                /** Called when the activity is first created. */

                //  static ArrayList<String> pthreads = new ArrayList<String>();
                static ImageView bt;
                static ProgressBar pb;
                static ListView allList;
                static TextView tv;
                String fileName;
                String mp3URL;
                URL url2;
                int myProgress;
                static int filecount  = 0;
                MyCustomAdapter adapter;

                private class DownloadFile extends AsyncTask<String, Integer, Void>{
                    int count = 0;
                    ProgressDialog dialog;
                    int myProgess = 0;
                    ProgressBar progressBar;

                    @Override
                    protected Void doInBackground(String... u) {

                        try {                   
                            URL ul = new URL(u[0]);
                            Log.i("UI",ul.toString());
                       //   int len = CopyOfMusicDownloader.mp3urls.size();
                       //   URL url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                            HttpURLConnection c = (HttpURLConnection) ul.openConnection();
                            c.setRequestMethod("GET");
                            c.setDoOutput(true);
                            c.connect();

                            int lengthOfFile = c.getContentLength();

                            String PATH = Environment.getExternalStorageDirectory()
                                    + "/download/";
                            Log.v("", "PATH: " + PATH);
                            File file = new File(PATH);
                            file.mkdirs();

                            fileName = "Track";
                            filecount++;

                            fileName =  fileName + Integer.toString(filecount) + ".mp3";


                            File outputFile = new File(file, fileName);
                            FileOutputStream fos = new FileOutputStream(outputFile);
                            InputStream is = c.getInputStream();

                            byte[] buffer = new byte[1024];
                            int len1 = 0;      
                            while ((len1 = is.read(buffer)) != -1) {
                                myProgress = (int)(len1*100/lengthOfFile);
                                //myProgress = (int)(len1);

                                Log.i("My Progress", Integer.toString(myProgress));
                                publishProgress(myProgress);
                                //  publishProgress((int)(len1*100/lengthOfFile));
                                fos.write(buffer, 0, len1);
                            }
                            fos.close();
                            is.close();

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

                    protected void onPostExecute() {

                    }

                    @Override
                    protected void onPreExecute() {
                          setListAdapter(new MyCustomAdapter(CopyOfDownloadsListActivity.this, R.layout.row, CopyOfMusicDownloader.mp3urls));

                    }



                    @Override
                    protected void onProgressUpdate(Integer... values) {
                         pb.setProgress(count);// HERE IS THE PROBLEM

                         count++;
                         Log.i("Values", Integer.toString(values[0]));
                    }
                 }  

                @Override
                public void onCreate(Bundle savedInstanceState) {
                    requestWindowFeature(Window.FEATURE_NO_TITLE);
                    super.onCreate(savedInstanceState);

                    int len = CopyOfMusicDownloader.mp3urls.size();
                    try {
                        url2 = new URL(CopyOfMusicDownloader.mp3urls.get(len-1));
                        new DownloadFile().execute(url2.toString());
                        Log.i("url",url2.toString());
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                 }

                @Override
                public boolean onCreateOptionsMenu(Menu menu) {
                     MenuInflater myMenuInflater = getMenuInflater();
                     myMenuInflater.inflate(R.menu.menu, menu);
                    return true;
                }

                @Override
                public boolean onOptionsItemSelected(MenuItem item) {
                     switch(item.getItemId()){
                     case(R.id.browsermenu):
                     Intent i = new Intent(CopyOfDownloadsListActivity.this, MusicDownloader.class);  
                     startActivity(i);
                     break;
                     case(R.id.downloaderrmenu):      
                     break; 
                     case(R.id.playermenu):
                     Intent j = new Intent(CopyOfDownloadsListActivity.this, Players.class);  
                     startActivity(j);
                    break;
              }
                 return true;
                }


                public class MyCustomAdapter extends ArrayAdapter<String> {     
                    public MyCustomAdapter(Context context, int textViewResourceId, ArrayList<String> pthreads) {
                    super(context, textViewResourceId, pthreads);
                    }

                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                            LayoutInflater inflater = getLayoutInflater();
                            View row = inflater.inflate(R.layout.row, parent, false);
                            bt =(ImageView)row.findViewById(R.id.cancel_btn);
                            tv =(TextView)row.findViewById(R.id.filetext);
                            pb = (ProgressBar)row.findViewById(R.id.progressbar_Horizontal);
                            return row;
                        }
                    }


            }

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

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

发布评论

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

评论(3

荭秂 2024-12-06 20:30:02

这就是您要找的吗?

private class DownloadFile extends AsyncTask<String, Integer, Void> {
    ProgressBar progressBar;
    public DownloadFile(ProgressBar progressBar) {
        this.progressBar=progressBar;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {
        progressBar.setProgress(count);
    }

}

现在,每个 DownloadFile Task 都有自己的 ProgressBar

is that what you are looking for?

private class DownloadFile extends AsyncTask<String, Integer, Void> {
    ProgressBar progressBar;
    public DownloadFile(ProgressBar progressBar) {
        this.progressBar=progressBar;
    }


    @Override
    protected void onProgressUpdate(Integer... values) {
        progressBar.setProgress(count);
    }

}

now, every DownloadFile Task have its own ProgressBar.

眼趣 2024-12-06 20:30:02

认为这就是问题所在(我没有测试你的代码

 myProgress = (int)(len1*100/lengthOfFile);

这一定是这样的

 myProgress += (int)(len1*100/lengthOfFile);

i think this is the problem ( i didnt test your code)

 myProgress = (int)(len1*100/lengthOfFile);

this must look like this

 myProgress += (int)(len1*100/lengthOfFile);
掌心的温暖 2024-12-06 20:30:02

我知道这个问题很老了,但有人可能会像我一样遇到过。这是我的代码。也许这不是最好的方法,但我需要让它尽快发挥作用。
我的适配器 getView 方法上的适配器元素

ChatRow

public class ChatRow {
    private int progressCount;
    private boolean sending;

        public boolean isSending()
        {
            return sending;
        }

        public void setSending(boolean sending)
        {
            this.sending = sending;
        }

            public int getProgressCount() {
                return progressCount;
            }

            public void setProgressCount(int progressCount) {
                this.progressCount = progressCount;
            }
}

我有这部分代码

if (row.isSending()) {
    holder.progressBar.setVisibility(View.VISIBLE);
    holder.progressBar.setProgress(row.getProgressCount());
}

,这在我的 AsyncTask 上
发送文件任务

private class SendFileTask extends AsyncTask<String, Integer, Boolean> {
    private ChatRow row;

    public SendFileTask(int rowNumber) {
        this.row = adapter.getItem(rowNumber);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        Logger.d(String.format("progress[%d]", values[0]));
        row.setProgressCount(values[0]);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        row.setSending(false);
        row.setProgressCount(0);
        adapter.notifyDataSetChanged();
    }

I know this question is old but someone might came across like I did. Here's my code. Maybe it's not the best approach but I need to make it work ASAP.
My adapter element

ChatRow

public class ChatRow {
    private int progressCount;
    private boolean sending;

        public boolean isSending()
        {
            return sending;
        }

        public void setSending(boolean sending)
        {
            this.sending = sending;
        }

            public int getProgressCount() {
                return progressCount;
            }

            public void setProgressCount(int progressCount) {
                this.progressCount = progressCount;
            }
}

on the getView method of my adapter i have this part of code

if (row.isSending()) {
    holder.progressBar.setVisibility(View.VISIBLE);
    holder.progressBar.setProgress(row.getProgressCount());
}

and this on my AsyncTask
SendFileTask

private class SendFileTask extends AsyncTask<String, Integer, Boolean> {
    private ChatRow row;

    public SendFileTask(int rowNumber) {
        this.row = adapter.getItem(rowNumber);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        Logger.d(String.format("progress[%d]", values[0]));
        row.setProgressCount(values[0]);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        row.setSending(false);
        row.setProgressCount(0);
        adapter.notifyDataSetChanged();
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文