微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax回调与asynctask 下载比较

Aquery框架Ajax回调与AsyncTask 下载比较

获取url数据,最后进行播放的比较代码

AsynTask:

// Async Task Class
        class DownloadMusicfromInternet extends AsyncTask<String,String,String> {

            // Show Progress bar before downloading Music
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Shows Progress Bar Dialog and then call doInBackground method
                showDialog(progress_bar_type);
            }

            // Download Music File from Internet
            @Override
            protected String doInBackground(String... f_url) {
                int count;
                try {
                    URL url = new URL(f_url[0]);
                    URLConnection conection = url.openConnection();
                    conection.connect();
                    // Get Music file length
                    int lenghtOfFile = conection.getContentLength();
                    // input stream to read file - with 8k buffer
                    InputStream input = new BufferedInputStream(url.openStream(),10*1024);
                    // Output stream to write file in SD card
                    OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/jai_ho.mp3");
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // Publish the progress which triggers onProgressUpdate method
                        publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                        // Write data to file
                        output.write(data,0,count);
                    }
                    // Flush output
                    output.flush();
                    // Close streams
                    output.close();
                    input.close();
                } catch (Exception e) {
                    Log.e("Error: ",e.getMessage());
                }
                return null;
            }

            // While Downloading Music File
            protected void onProgressUpdate(String... progress) {
                // Set progress percentage
                prgDialog.setProgress(Integer.parseInt(progress[0]));
            }

            // Once Music File is downloaded
            @Override
            protected void onPostExecute(String file_url) {
                // dismiss the dialog after the Music file was downloaded
                dismissDialog(progress_bar_type);
                Toast.makeText(getApplicationContext(),"Download complete,playing Music",Toast.LENGTH_LONG).show();
                // Play the music
                playMusic();
            }
        }

Ajax回调:

aq.progress(prgDialog).download(url,target,new AjaxCallback<File>() {
                // Once download is complete
                public void callback(String url,File file,AjaxStatus status) {
                    // If file does exist
                    if (file != null) {
                        playMusic();
                    // If file doesn't exist display error message
                    } else {
                        Toast.makeText(aq.getContext(),"Error occured: Status" + status,Toast.LENGTH_SHORT).show();
                    }
                }
            });
  • aq.download()方法中已经封装了处理逻辑,只需要开发者传入url,目标文件位置和最后回调处理对象即可
  • aq.progress()传入ProgressBar对象,无需额外代码进行进度显示
  • aquery采取链式调用代码简洁

初始化组件的代码比较

AsyncTask:

// 初始化Button
btnPlayMusic = (Button) findViewById(R.id.btnProgressBar);
            // Download Music Button click listener
            btnPlayMusic.setonClickListener(new View.OnClickListener() {
                // When Download Music Button is clicked
                public void onClick(View v) {
                    // disable the button to avoid playing of song multiple times
                    btnPlayMusic.setEnabled(false);
                    // Downloaded Music File path in SD Card
                    File file = new File(Environment.getExternalStorageDirectory().getPath()+"/jai_ho.mp3");
                    // Check if the Music file already exists
                    if (file.exists()) {
                        Toast.makeText(getApplicationContext(),"File already exist under SD card,Toast.LENGTH_LONG).show();
                        // Play Music
                        playMusic();
                    // If the Music File doesn't exist in SD card (Not yet downloaded)
                    } else {
                        Toast.makeText(getApplicationContext(),"File doesn't exist under SD Card,downloading Mp3 from Internet",Toast.LENGTH_LONG).show();
                        // Trigger Async Task (onPreExecute method)
                        new DownloadMusicfromInternet().execute(file_url);
                    }
                }
            });

     ....

// 初始化ProgressDialog
prgDialog = new ProgressDialog(this);
                prgDialog.setMessage("Downloading Mp3 file. Please wait...");
                prgDialog.setIndeterminate(false);
                prgDialog.setMax(100);
                prgDialog.setProgressstyle(ProgressDialog.STYLE_HORIZONTAL);
                prgDialog.setCancelable(false);
                prgDialog.show();

AJAX回调:

// 初始化Button
        // Instantiate AQuery object
        aq = new AQuery(this);
        // Look for button click event using AQuery clicked() method
        aq.id(R.id.btnProgressBar).clicked(this,"downloadSongandplay");


        ....

        // 初始化ProgressBar
        prgDialog = new ProgressDialog(this); // Instantiate Progress Dialog Bar
        prgDialog.setMessage("Downloading MP3 from Internet. Please wait..."); // Set Progress Dialog Bar message
        prgDialog.setIndeterminate(false);  
        prgDialog.setMax(100); // Progress Bar max limit
        prgDialog.setProgressstyle(ProgressDialog.STYLE_HORIZONTAL); // Progress Bar style
        prgDialog.setCancelable(false); // Progress Bar cannot be cancelable
        // display progress dialog bar and initiate download of Mp3 file
        aq.progress(prgDialog);

播放音乐文件代码,此处相同

protected void playMusic(){
        // Read Mp3 file present under SD card
        Uri myUri1 = Uri.parse("file:///sdcard/pgfolder/jai_ho.mp3");
        mPlayer  = new MediaPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
                mPlayer.setDataSource(aq.getContext(),myUri1);
                mPlayer.prepare();
                // Start playing the Music file
                mPlayer.start();
                mPlayer.setonCompletionListener(new OnCompletionListener() {
                    public void onCompletion(MediaPlayer mp) {
                        // Todo Auto-generated method stub
                        // Once Music is completed playing,enable the button
                        aq.id(R.id.btnProgressBar).enabled(true);
                        Toast.makeText(getApplicationContext(),"Music completed playing",Toast.LENGTH_LONG).show();
                    }
                });
        } catch (IllegalArgumentException e) {
            Toast.makeText(getApplicationContext(),"You might not set the URI correctly!",Toast.LENGTH_LONG).show();
        } catch (SecurityException e) {
            Toast.makeText(getApplicationContext(),"URI cannot be accessed,permissed needed",Toast.LENGTH_LONG).show();
        } catch (IllegalStateException e) {
            Toast.makeText(getApplicationContext(),"Media Player is not in correct state",Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(),"IO Error occured",Toast.LENGTH_LONG).show();
        }
    }

参考资料

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但是在某些特殊情况下,我们可能还需要使用IE6来访问网页。而在IE6中,我们通常会使用JavaScript来提交表单,来看一下具体操作。
PHP中的count()函数是用来计算数组或容器中元素的个数。这个函数十分方便,在编写代码时使用频率也非常高。无论你是要统计数组的长度、统计字符串中字符出现的次数还是统计对象中属性的个数,count()都可以帮助你轻松
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不刷新整个页面的情况下,向服务器发送请求并接收响应。通常来说,我们使用 AJAX 请求是为了获取后台数据,并将其展示在前端页面上。然而,有时候我们只需要
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页用户体验的技术,通过与服务器进行异步通信,实现在网页上局部刷新数据而不必整个页面刷新的功能。在实际开发中,我们经常需要从服务器端下载文件,而传统
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以在不刷新整个页面的情况下,向服务器发送请求并获取响应数据。在某些场景下,我们需要通过AJAX下载Excel文件流,以便于在前端使用或保存到本地。本文将详
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax,我们可以在不刷新整个页面的情况下向服务器发送请求并获得响应数据。而在Ajax的基础上,.get和.post是两种常用的请求方法,它们分别用于发送GET和POST请
AJAX(Asynchronous JavaScript and XML)是一种在网页上实现异步数据传输的技术。通过AJAX,网页可以在不刷新整个页面的情况下与服务器进行数据交互,提升用户体验和页面性能。在实际应用中,AJAX广泛用于表单提交、
在使用Ajax下拉加载数据的过程中,有时候会出现无法取到360度的问题。这个问题可能是由于代码逻辑的问题导致的,也有可能是网络延迟引起的。为了解决这个问题,我们需要对代码进行仔细排查,并且在合适的地方添加适当
本文将介绍Ajax和.post之间的区别。Ajax是一种用于在网页上进行异步通信的技术,能够在不刷新整个页面的情况下更新部分页面内容。.post是jQuery中的一个方法,用于向服务器发送POST请求。虽然它们都可以用于发送异步
AJAX(Asynchronous JavaScript and XML)是一种在Web页面上进行异步数据请求和交互的技术。它的出现使得页面在后台与服务器进行数据交互的同时,不需要重新加载整个页面。在网页开发中,常常需要实现文件上传功能,