ajax回调与asynctask 下载比较

前端之家收集整理的这篇文章主要介绍了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();
        }
    }

参考资料

原文链接:https://www.f2er.com/ajax/163561.html

猜你在找的Ajax相关文章