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

参考资料

  • Asynchronous Network
  • Android AsyncTask Example
  • AQuery AJAX Callback

ajax回调与asynctask 下载比较的更多相关文章

  1. three.js模拟实现太阳系行星体系功能

    这篇文章主要介绍了three.js模拟实现太阳系行星体系功能,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

  2. HTML5页面无缝闪开的问题及解决方案

    这篇文章主要介绍了HTML5页面无缝闪开方案,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. 浅谈HTML5 FileReader分布读取文件以及其方法简介

    本篇文章主要介绍了浅谈HTML5 FileReader分布读取文件以及其方法简介,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  4. ios – 为什么,将nil作为参数从Objc C发送到swift类初始化器,用新对象替换nil参数

    除非属性本身被声明为nonnull:

  5. ios – 在Swift中对MKCircle进行子类化

    我想通过添加另一个String属性来继承MKCircle,我们称之为“代码”.这个属性不是可选的和常量的,所以我必须从初始化器设置它,对吧?有没有办法定义一个单一的便利初始化器,在这种情况下需要3个参数?本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请发送邮件至dio@foxmail.com举报,一经查实,本站将立刻删除。

  6. ios – AVAudioPlayer不再使用Swift 2.0/Xcode 7 beta

    对于我的iPhone应用程序中的vartestAudio声明,我在这里收到错误“调用可以抛出,但错误不能从属性初始化程序中抛出”当我转到Xcode7测试版时,就发生了这种情况.如何在Swift2.0中使用此音频剪辑?

  7. ios – 在导航栏下添加进度条

    我是iOS开发的新手.我想知道在iOS7中是否在UINavigationBar下发送消息时,其标题为:发送,有一个进度条正在加载,直到消息成功发送.我的问题是:>那个酒吧是进度条吗?有人可以给我一些关于如何在iOS7和iOS6上创建它的想法吗?

  8. ios – 斯威夫特.在初始化所有存储的属性之前在方法调用中使用’self’

    解决方法在初始化所有非可选实例变量之前,您无法在self上调用方法.有几种方法可以解决这个问题.>将属性更改为选项或隐式解包选项(不建议)>使buildCircle()方法静态或只是一个在文件中运行并为所有圆圈调用addSubview()在所有属性初始化并且您调用之后super.init()等等.你必须避免在自己之前打电话给自己class已初始化.

  9. ios – Objective-C警告未找到超类“-init”的指定的初始化程序的方法覆盖

    我在一个应用程序中清理警告,我收到了两次这个警告对于这行代码和这一行我相当新的Objective-C和谷歌这个警告,只是不明白的解决方案我的问题是如何摆脱这些警告?

  10. ios – UICollectionView不能使用UISearchController?

    在WWDC2014年的“AInsideInsidePresentationControllers”中,演示者展示了如何在UITableView中设置UISearchController.他们通过设置searchController的searchBar框架,然后将其设置为tableView的tableHeaderView来实现.不幸的是,UICollectionView没有相当于tableHeade

随机推荐

  1. xe-ajax-mock 前端虚拟服务

    最新版本见Github,点击查看历史版本基于XEAjax扩展的Mock虚拟服务插件;对于前后端分离的开发模式,ajax+mock使前端不再依赖后端接口开发效率更高。CDN使用script方式安装,XEAjaxMock会定义为全局变量生产环境请使用xe-ajax-mock.min.js,更小的压缩版本,可以带来更快的速度体验。

  2. vue 使用 xe-ajax

    安装完成后自动挂载在vue实例this.$ajaxCDN安装使用script方式安装,VXEAjax会定义为全局变量生产环境请使用vxe-ajax.min.js,更小的压缩版本,可以带来更快的速度体验。cdnjs获取最新版本点击浏览已发布的所有npm包源码unpkg获取最新版本点击浏览已发布的所有npm包源码AMD安装require.js安装示例ES6Module安装通过Vue.use()来全局安装示例./Home.vue

  3. AJAX POST数据中文乱码解决

    前端使用encodeURI进行编码后台java.net.URLDecoder进行解码编解码工具

  4. Koa2框架利用CORS完成跨域ajax请求

    实现跨域ajax请求的方式有很多,其中一个是利用CORS,而这个方法关键是在服务器端进行配置。本文仅对能够完成正常跨域ajax响应的,最基本的配置进行说明。这样OPTIONS请求就能够通过了。至此为止,相当于仅仅完成了预检,还没发送真正的请求呢。

  5. form提交时,ajax上传文件并更新到&lt;input&gt;中的value字段

  6. ajax的cache作用

    filePath="+escape;},error:{alert;}});解决方案:1.加cache:false2.url加随机数正常代码:网上高人解读:cache的作用就是第一次请求完毕之后,如果再次去请求,可以直接从缓存里面读取而不是再到服务器端读取。

  7. 浅谈ajax上传文件属性contentType = false

    默认值为contentType="application/x-www-form-urlencoded".在默认情况下,内容编码类型满足大多数情况。在这里,我们主要谈谈contentType=false.在使用ajax上传文件时:在其中先封装了一个formData对象,然后使用post方法将文件传给服务器。说到这,我们发现在JQueryajax()方法中我们使contentType=false,这不是冲突了吗?这就是因为当我们在form标签中设置了enctype=“multipart/form-data”,

  8. 909422229_ajaxFileUpload上传文件

    ajaxFileUpload.js很多同名的,因为做出来一个很容易。我上github搜AjaxFileUpload出来很多类似js。ajaxFileUpload是一个异步上传文件的jQuery插件传一个不知道什么版本的上来,以后不用到处找了。语法:$.ajaxFileUploadoptions参数说明:1、url上传处理程序地址。2,fileElementId需要上传的文件域的ID,即的ID。3,secureuri是否启用安全提交,默认为false。4,dataType服务器返回的数据类型。6,error

  9. AJAX-Cache:一款好用的Ajax缓存插件

    原文链接AJAX-Cache是什么Ajax是前端开发必不可少的数据获取手段,在频繁的异步请求业务中,我们往往需要利用“缓存”提升界面响应速度,减少网络资源占用。AJAX-Cache是一款jQuery缓存插件,可以为$.ajax()方法扩展缓存功能。

  10. jsf – Ajax update/render在已渲染属性的组件上不起作用

    我试图ajax更新一个有条件渲染的组件。我可以确保#{user}实际上是可用的。这是怎么引起的,我该如何解决呢?必须始终在ajax可以重新呈现之前呈现组件。Ajax正在使用JavaScriptdocument.getElementById()来查找需要更新的组件。但是如果JSF没有将组件放在第一位,那么JavaScript找不到要更新的内容。解决方案是简单地引用总是渲染的父组件。

返回
顶部