Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發本地及網絡Mp3音樂播放器(十三)網絡音樂搜索功能實現,歌名歌手專輯名搜索

Android開發本地及網絡Mp3音樂播放器(十三)網絡音樂搜索功能實現,歌名歌手專輯名搜索

編輯:關於Android編程

實現功能:
實現網絡音樂搜索功能
使用觀察者設計模式

使用URLEncoder.encode轉碼

SearchMusicUtils是重點

實現效果如圖:

\

\

\

\

\

\

\


實現代碼如下:
NetMusicListFragment如下:
package com.iwanghang.drmplayer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.iwanghang.drmplayer.adapter.MyMusicListAdapter;
import com.iwanghang.drmplayer.adapter.NetMusicListAdapter;
import com.iwanghang.drmplayer.utils.AppUtils;
import com.iwanghang.drmplayer.utils.Constant;
import com.iwanghang.drmplayer.utils.SearchMusicUtils;
import com.iwanghang.drmplayer.vo.Mp3Info;
import com.iwanghang.drmplayer.vo.SearchResult;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

public class NetMusicListFragment extends Fragment implements OnItemClickListener,OnClickListener {

    private ListView listView_net_music;

    //private ArrayList mp3Infos;

    private LinearLayout load_layout;
    private LinearLayout ll_search_btn_container;//查詢按鈕的容器
    private LinearLayout ll_search_container;//查詢按鈕的容器
    private ImageButton ib_search_btn;
    private EditText et_search_content;

    private NetMusicListAdapter netMusicListAdapter;

    //存放 網絡音樂 的集合
    private ArrayList searchResults = new ArrayList();

    private int page = 1;//搜索音樂的頁碼

    private MainActivity mainActivity;

    //private boolean isPause = false;//歌曲播放中的暫停狀態

    private int position = 0;//當前播放的位置,提供給PlayActivity

    //onAttach(),當fragment被綁定到activity時被調用(Activity會被傳入.).
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //mainActivity = (MainActivity) context;
        mainActivity = (MainActivity) getActivity();
    }

    public static NetMusicListFragment newInstance() {
        NetMusicListFragment net = new NetMusicListFragment();
        return net;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //UI組件初始化
        View view = inflater.inflate(R.layout.net_music_list_layout,null);
        //item
        listView_net_music = (ListView) view.findViewById(R.id.listView_net_music);
        //findViewById
        load_layout = (LinearLayout) view.findViewById(R.id.load_layout);
        ll_search_btn_container = (LinearLayout) view.findViewById(R.id.ll_search_btn_container);
        ll_search_container = (LinearLayout) view.findViewById(R.id.ll_search_container);
        ib_search_btn = (ImageButton) view.findViewById(R.id.ib_search_btn);
        et_search_content = (EditText) view.findViewById(R.id.et_search_content);

        //Item點擊事件監聽
        listView_net_music.setOnItemClickListener(this);
        //按鈕點擊事件監聽
        ll_search_btn_container.setOnClickListener(this);
        ib_search_btn.setOnClickListener(this);
        loadNetData();//加載網絡音樂
        return view;
    }

    private void loadNetData() {
        load_layout.setVisibility(View.VISIBLE);
        //加載網絡音樂的異步任務
        new LoadNetDataTask().execute(Constant.BAIDU_URL + Constant.BAIDU_DAYHOT);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_search_btn_container:
                ll_search_btn_container.setVisibility(View.GONE);
                ll_search_container.setVisibility(View.VISIBLE);
                break;
            case R.id.ib_search_btn:
                //搜索事件
                searchMusic();
                break;
        }
    }

    //搜索音樂
    private void searchMusic() {
        //隱藏鍵盤
        AppUtils.hideInputMethod(et_search_content);
        ll_search_btn_container.setVisibility(View.VISIBLE);
        ll_search_container.setVisibility(View.GONE);
        //獲取輸入的文字
        String key = et_search_content.getText().toString();
        if (TextUtils.isEmpty(key)){//如果為空,則,Toast提示
            Toast.makeText(mainActivity,"請輸入歌手或歌詞",Toast.LENGTH_SHORT).show();
            return;
        }
        load_layout.setVisibility(View.VISIBLE);//加載layout效果.顯示
        //填充item 使用SearchMusicUtils搜索音樂工具類,並,使用觀察者設計模式,自己回調,自己監聽
        SearchMusicUtils.getInstance().setListener(new SearchMusicUtils.OnSearchResultListener(){
            @Override
            public void onSearchResult(ArrayList results) {
                ArrayList sr = netMusicListAdapter.getSearchResults();
                sr.clear();
                sr.addAll(results);
                netMusicListAdapter.notifyDataSetChanged();//更新網絡音樂列表
                load_layout.setVisibility(View.GONE);
            }
        }).search(key,page);
    }

    //加載網絡音樂的異步任務
    //Android1.5提供了 工具類 android.os.AsyncTask,它使創建異步任務變得更加簡單,不再需要編寫任務線程和Handler實例即可完成相同的任務。
    class LoadNetDataTask extends AsyncTask{
        //onPreExecute方法用於在執行後台任務前做一些UI操作
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            load_layout.setVisibility(View.VISIBLE);//加載layout.顯示
            listView_net_music.setVisibility(View.GONE);//item.隱藏
            searchResults.clear();//搜索結果.清理
        }

        //doInBackground方法內部執行後台任務,不可在此方法內修改UI
        @Override
        protected Integer doInBackground(String... params) {
            String url = params[0];
            try {
                //使用Jsoup組件請求網絡,並解析音樂數據
                Document doc = Jsoup.connect(url).userAgent(Constant.USER_AGENT).timeout(6*1000).get();
//半壺紗							
//劉珂矣        	
//千年一般若影視原聲							
//韓磊        	
                //從doc分析以上html代碼;把所有span標簽下song-title查找出來,存在songTitles集合中;即,歌名集合;
                //從doc分析以上html代碼;把所有span標簽下author_list查找出來,存在artists集合中;即,歌手集合;
                Elements songTitles = doc.select("span.song-title");
                Elements artists = doc.select("span.author_list");
                //System.out.println(artists);
                for (int i=0;i半壺紗<,半壺紗就是a鏈接的內容);即,最終的歌名;
                    Elements urls = songTitles.get(i).getElementsByTag("a");
                    //System.out.println("@urls : " + urls);
                    searchResult.setUrl(urls.get(0).attr("href"));//設置最終的url
                    searchResult.setMusicName(urls.get(0).text());//設置最終的歌名

                    //a鏈接,存在urls集合中;即,歌曲url集合;
                    Elements artistElements = artists.get(i).getElementsByTag("a");
                    //System.out.println("@artistElements : " + artistElements);
                    searchResult.setArtist(artistElements.get(0).text());//設置最終的歌手

                    searchResult.setAlbum("熱歌榜");//設置最終的專輯

                    System.out.println("@searchResult : " + searchResult);
                    searchResults.add(searchResult);//把最終的所有信息,添加到集合
                }
                System.out.println("@searchResults : " + searchResults);
                //System.out.println("@songTitles.size() : " + searchResults.size());
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
            return 1;
        }

        //onPostExecute方法用於在執行完後台任務後更新UI,顯示結果
        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);
            if (result==1){
                netMusicListAdapter = new NetMusicListAdapter(mainActivity,searchResults);
                //System.out.println(searchResults);
                listView_net_music.setAdapter(netMusicListAdapter);
                listView_net_music.addFooterView(LayoutInflater.from(mainActivity).inflate(R.layout.footviwe_layout,null));
            }
            load_layout.setVisibility(View.GONE);
            listView_net_music.setVisibility(View.VISIBLE);
        }
    }




    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {

    }
}

MediaUtils如下:

 

package com.iwanghang.drmplayer.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import com.iwanghang.drmplayer.R;
import com.iwanghang.drmplayer.vo.Mp3Info;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;

/**
 * Created by iwanghang on 16/4/16.
 */
public class MediaUtils {

    // 獲取專輯封面的Uri
    private static final Uri albumArtUri = Uri
            .parse("content://media/external/audio/albumart");

    /**
     * 根據歌曲id查詢歌曲信息
     */
    public static Mp3Info getMp3Info(Context context, long _id){
        System.out.println("MediaUtils.java #0 : " + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
                MediaStore.Audio.Media._ID + "=" + _id, null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        Mp3Info mp3Info = null;

        if(cursor.moveToNext()){
            mp3Info = new Mp3Info();
            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));//音樂id
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));//音樂標題
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));//藝術家
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));//專輯
            long albumid = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));//專輯id
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));//時長
            long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));//文件大小
            String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));//文件路徑
            int isMusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否為音樂
            if(isMusic != 0){
                mp3Info.setId(id);
                mp3Info.setTitle(title);
                mp3Info.setArtist(artist);
                mp3Info.setAlbum(album);
                mp3Info.setAlbumId(albumid);
                mp3Info.setDuration(duration);
                mp3Info.setSize(size);
                mp3Info.setUrl(url);
                //System.out.println("MediaUtils.java #101 : title = " + title + " | artist = " + artist + " | duration = " + duration);
                //System.out.println("MediaUtils.java #102 : id = " + id + " | album = " + album + " | size = " + size);
                //System.out.println("MediaUtils.java #103 : url = " + url);
            }
        }
        cursor.close();
        return mp3Info;
    }

    /**
     * 用於從數據庫中查詢歌曲的信息,保存在List當中
     */
    public static long[] getMp3InfoIds(Context context){
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[] {MediaStore.Audio.Media._ID},
                MediaStore.Audio.Media.DURATION + ">=30000", null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        long[] ids = null;
        if(cursor != null){
            ids = new long[cursor.getCount()];
            for (int i = 0;i getMp3Infos(Context context) {
        System.out.println("MediaUtils.java #2 : " + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
                MediaStore.Audio.Media.DURATION + ">=30000", null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        ArrayList mp3Infos = new ArrayList();
        System.out.println("MediaUtils.java #3 :cursor.getCount() : " + cursor.getCount());
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            Mp3Info mp3Info = new Mp3Info();
            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));//音樂id
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));//音樂標題
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));//藝術家
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));//專輯
            long albumid = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));//專輯id
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));//時長
            long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));//文件大小
            String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));//文件路徑
            int isMusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否為音樂
            if (isMusic != 0) {
                mp3Info.setId(id);
                mp3Info.setTitle(title);
                mp3Info.setArtist(artist);
                mp3Info.setAlbum(album);
                mp3Info.setAlbumId(albumid);
                mp3Info.setDuration(duration);
                mp3Info.setSize(size);
                mp3Info.setUrl(url);
                mp3Infos.add(mp3Info);
                //System.out.println("MediaUtils.java #401 : title = " + title + " | artist = " + artist + " | duration = " + duration);
                //System.out.println("MediaUtils.java #402 : id = " + id + " | album = " + album + " | size = " + size);
                //System.out.println("MediaUtils.java #403 : url = " + url);
                //System.out.println("MediaUtils.java #404 : mp3Infos = " + mp3Infos.size());
            }
        }
        cursor.close();
        System.out.println("MediaUtils.java #405 : mp3Infos = " + mp3Infos.size());
        return mp3Infos;
    }

    /**
     * 格式化時間,將毫秒轉換為分:秒格式
     */
    public static String formatTime(long time){
        String min = time / (1000*60) + "";
        String sec = time % (1000*60) + "";
        if (min.length()<2){
            min = "0" + time / (1000*60) + "";
        }else {
            min = time / (1000*60) + "";
        }
        if (sec.length() == 4){
            sec = "0" + time % (1000*60) + "";
        }else if (sec.length() == 3){
            sec = "00" + time % (1000*60) + "";
        }else if (sec.length() == 2){
            sec = "000" + time % (1000*60) + "";
        }else if (sec.length() == 1) {
            sec = "0000" + time % (1000 * 60) + "";
        }
        return min + ":" + sec.trim().substring(0,2);
    }




    /**
     * 獲取默認專輯圖片
     */
    public static Bitmap getDefaultArtwork(Context context,boolean small) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        if(small){	//返回小圖片
            return BitmapFactory.decodeStream(context.getResources().openRawResource(R.mipmap.music), null, opts);
        }
        return BitmapFactory.decodeStream(context.getResources().openRawResource(R.mipmap.music), null, opts);
    }


    /**
     * 從文件當中獲取專輯封面位圖
     */
    private static Bitmap getArtworkFromFile(Context context, long songid, long albumid){
        Bitmap bm = null;
        if(albumid < 0 && songid < 0) {
            throw new IllegalArgumentException("Must specify an album or a song id");
        }
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            FileDescriptor fd = null;
            if(albumid < 0){
                Uri uri = Uri.parse("content://media/external/audio/media/"
                        + songid + "/albumart");
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if(pfd != null) {
                    fd = pfd.getFileDescriptor();
                }
            } else {
                Uri uri = ContentUris.withAppendedId(albumArtUri, albumid);
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if(pfd != null) {
                    fd = pfd.getFileDescriptor();
                }
            }
            options.inSampleSize = 1;
            // 只進行大小判斷
            options.inJustDecodeBounds = true;
            // 調用此方法得到options得到圖片大小
            BitmapFactory.decodeFileDescriptor(fd, null, options);
            // 我們的目標是在800pixel的畫面上顯示
            // 所以需要調用computeSampleSize得到圖片縮放的比例
            options.inSampleSize = 100;
            // 我們得到了縮放的比例,現在開始正式讀入Bitmap數據
            options.inJustDecodeBounds = false;
            options.inDither = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;

            //根據options參數,減少所需要的內存
            bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bm;
    }

    /**
     * 獲取專輯封面位圖對象
     */
    public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefalut, boolean small){
        if(album_id < 0) {
            if(song_id < 0) {
                Bitmap bm = getArtworkFromFile(context, song_id, -1);
                if(bm != null) {
                    return bm;
                }
            }
            if(allowdefalut) {
                return getDefaultArtwork(context, small);
            }
            return null;
        }
        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(albumArtUri, album_id);
        if(uri != null) {
            InputStream in = null;
            try {
                in = res.openInputStream(uri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                //先制定原始大小
                options.inSampleSize = 1;
                //只進行大小判斷
                options.inJustDecodeBounds = true;
                //調用此方法得到options得到圖片的大小
                BitmapFactory.decodeStream(in, null, options);
                /** 我們的目標是在你N pixel的畫面上顯示。 所以需要調用computeSampleSize得到圖片縮放的比例 **/
                /** 這裡的target為800是根據默認專輯圖片大小決定的,800只是測試數字但是試驗後發現完美的結合 **/
                if(small){
                    options.inSampleSize = computeSampleSize(options, 40);
                } else{
                    options.inSampleSize = computeSampleSize(options, 600);
                }
                // 我們得到了縮放比例,現在開始正式讀入Bitmap數據
                options.inJustDecodeBounds = false;
                options.inDither = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                in = res.openInputStream(uri);
                return BitmapFactory.decodeStream(in, null, options);
            } catch (FileNotFoundException e) {
                Bitmap bm = getArtworkFromFile(context, song_id, album_id);
                if(bm != null) {
                    if(bm.getConfig() == null) {
                        bm = bm.copy(Bitmap.Config.RGB_565, false);
                        if(bm == null && allowdefalut) {
                            return getDefaultArtwork(context, small);
                        }
                    }
                } else if(allowdefalut) {
                    bm = getDefaultArtwork(context, small);
                }
                return bm;
            } finally {
                try {
                    if(in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 對圖片進行合適的縮放
     */
    public static int computeSampleSize(Options options, int target) {
        int w = options.outWidth;
        int h = options.outHeight;
        int candidateW = w / target;
        int candidateH = h / target;
        int candidate = Math.max(candidateW, candidateH);
        if(candidate == 0) {
            return 1;
        }
        if(candidate > 1) {
            if((w > target) && (w / candidate) < target) {
                candidate -= 1;
            }
        }
        if(candidate > 1) {
            if((h > target) && (h / candidate) < target) {
                candidate -= 1;
            }
        }
        return candidate;
    }
}

 

SearchResult如下:
package com.iwanghang.drmplayer.utils;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.iwanghang.drmplayer.vo.SearchResult;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.xml.parsers.ParserConfigurationException;

/**
 * Created by iwanghang on 16/4/30.
 * 搜索音樂工具類
 */
public class SearchMusicUtils {
    private static final int SIZE = 20;//查詢歌曲數量
    //private static final String URL = Constant.BAIDU_URL + Constant.BAIDU_SEARCH;
    //private static String URL = Constant.BAIDU_URL + Constant.BAIDU_SEARCH;
    private static SearchMusicUtils sInstance;
    private OnSearchResultListener mListener;

    private ExecutorService mThreadPool;//線程池

    public synchronized static SearchMusicUtils getInstance(){
        if (sInstance == null){
            try {
                sInstance = new SearchMusicUtils();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            }
        }
        return sInstance;
    }

    //設置搜索事件
    private SearchMusicUtils() throws ParserConfigurationException{
        mThreadPool = Executors.newSingleThreadExecutor();//單任務線程池
    }

    public SearchMusicUtils setListener(OnSearchResultListener l){
        mListener = l;
        return this;
    }

    public void search(final String key,final int page){
        final Handler handler = new Handler(){//handler 用於返回數據
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case Constant.SUCCESS:
                        if (mListener != null) mListener.onSearchResult((ArrayList)msg.obj);
                        break;
                    case Constant.FAILED:
                        if (mListener != null) mListener.onSearchResult(null);
                        break;
                }
            }
        };

        //執行線程
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {//run方法
                ArrayList results = getMusicList(key,page);
                if(results == null){
                    handler.sendEmptyMessage(Constant.FAILED);
                    return;
                }
                handler.obtainMessage(Constant.SUCCESS,results).sendToTarget();
            }
        });

    }

    //使用Jsoup組件請求網絡,並解析音樂數據
    private ArrayList getMusicList(final String key,final int page){
        final String start = String.valueOf((page - 1) * SIZE);

        Document doc = null;
        String URL = Constant.BAIDU_URL + Constant.BAIDU_SEARCH;
        try {
            //music.baidu.com/search/song?key=蔡琴&start=0&size=20
            //由上面url得到下面的代碼,這個方法也是對的,但是我沒有搞懂,搞明白的麻煩告訴我一下
            //doc = Jsoup.connect(URL)
            //        .data("key",key,"start",start,"size",String.valueOf(SIZE))
            //        .userAgent(Constant.USER_AGENT)
            //        .timeout(60 * 1000).get();
            //System.out.println("~~doc = " + doc);


            //從浏覽器復制出來的Url是這樣的,"http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";
            //漢字經過utf8編碼,比如 冰雨 == %E5%86%B0%E9%9B%A8;
            //經過測試 獲取頁面 使用"http://music.baidu.com/search?key=冰雨";無法打開正確連接
            //比如使用URLEncoder.encode轉碼,轉為utf8
            //實際使用 獲取頁面 使用"http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";
            String keyUrlEnCode = URLEncoder.encode(key, "utf8");
            URL = URL + "=" + keyUrlEnCode;
            System.out.println(URL);
            doc = Jsoup.connect(URL)
                    .data("query", "Java")
                    .userAgent(Constant.USER_AGENT)
                    .timeout(60 * 1000).get();
            //System.out.println("~~doc = " + doc);

            //
            //由上面的網頁源碼得到"div.song-item.clearfix"
//01你的眼神
            //由上面代碼 >你的眼神< ,你的眼神,就是標題
            Elements songTitles = doc.select("div.song-item.clearfix");
            Elements songInfos;
            ArrayList searchResults = new ArrayList();

            int xyz = 0;

            TAG:
            for (Element song : songTitles){
                //System.out.println("W SearchMusicUtils songTitles = " + songTitles);
                songInfos = song.getElementsByTag("a");
                //System.out.println("W SearchMusicUtils songInfos = " + songInfos);
                SearchResult searchResult = new SearchResult();
                //System.out.println("##searchResult = " + searchResult);
                for (Element info : songInfos){
                    //收費的歌曲
                    if (info.attr("href").startsWith("http://y.baidu.com/song/")){
                        continue TAG;
                    }

                    //跳轉到百度音樂盒的歌曲
                    if (info.attr("href").equals("#") && !TextUtils.isEmpty(info.attr("data-songdata"))){
                        continue TAG;
                    }

                    //歌曲鏈接
                    if (info.attr("href").startsWith("/song")){//href="/song/s/570761c8f270856302a79"
                        searchResult.setMusicName(info.text());
                        searchResult.setUrl(info.attr("href"));
                    }

                    //歌手鏈接
                    if (info.attr("href").startsWith("/data")){//href="/data/artist/redirect?id=23571029"
                        searchResult.setArtist(info.text());//href="/data/artist/redirect?id=23571029">日本原聲帶
                    }

                    //專輯鏈接
                    if (info.attr("href").startsWith("/album")){//href="/album/102534774" title="ゴールデンマネジャー">《ゴールデンマ..》
                        searchResult.setAlbum(info.text().replaceAll("《|》",""));
                    }

                    xyz = xyz + 1;
                    System.out.println("~~searchResult"+ xyz + " : " + searchResult);
                }
                searchResults.add(searchResult);
            }
            return searchResults;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    public interface OnSearchResultListener {
        public void onSearchResult(ArrayList results);
    }

}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved