当前位置: 代码迷 >> Android >> Android上MP3播放器的实现源代码03
  详细解决方案

Android上MP3播放器的实现源代码03

热度:72   发布时间:2016-05-01 16:49:12.0
Android下MP3播放器的实现源代码03
类十一MusicActivity

package com.alex.media;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.Iterator;import java.util.TreeMap;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.database.Cursor;import android.media.AudioManager;import android.media.MediaPlayer;import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.provider.MediaStore;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.widget.ImageButton;import android.widget.SeekBar;import android.widget.TextView;import android.widget.SeekBar.OnSeekBarChangeListener;public class MusicActivity extends Activity {	private int[] _ids;	private int position;	private String _titles[] = null;	private Uri uri;	private ImageButton playBtn = null;//播放、暂停	//private Button stopBtn = null;//停止	private ImageButton latestBtn = null;//上一首	private ImageButton nextBtn = null;//下一首	private ImageButton forwardBtn = null;//快进	private ImageButton rewindBtn = null;//快退	private TextView lrcText = null;//歌词文本	private TextView playtime = null;//已播放时间	private TextView durationTime = null;//歌曲时间	private SeekBar seekbar = null;//歌曲进度	private SeekBar soundBar = null;//音量调节	private Handler handler = null;//用于进度条	private Handler fHandler = null;//用于快进	private int currentPosition;//当前播放位置	private int duration;	private DBHelper dbHelper = null;	private TextView name = null;		private TreeMap<Integer, LRCbean> lrc_map = new TreeMap<Integer, LRCbean>();	private Cursor myCur;	private static final String MUSIC_CURRENT = "com.alex.currentTime";	private static final String MUSIC_DURATION = "com.alex.duration";	private static final String MUSIC_NEXT = "com.alex.next";	private static final String MUSIC_UPDATE = "com.alex.update";	private static final int MUSIC_PLAY = 1;	private static final int MUSIC_PAUSE = 2;	private static final int MUSIC_STOP = 3;	private static final int PROGRESS_CHANGE = 4;	private static final int MUSIC_REWIND = 5;	private static final int MUSIC_FORWARD = 6;		private static final int STATE_PLAY = 1;	private static final int STATE_PAUSE = 2;	private int flag;		//关于音量的变量	private AudioManager mAudioManager = null;	private int maxVolume;//最大音量	private int currentVolume;//当前音量			@Override	protected void onCreate(Bundle savedInstanceState) {		// TODO Auto-generated method stub		super.onCreate(savedInstanceState);		setContentView(R.layout.main1);		Intent intent = this.getIntent();		Bundle bundle = intent.getExtras();		_ids = bundle.getIntArray("_ids");		position = bundle.getInt("position");		_titles = bundle.getStringArray("_titles");		lrcText = (TextView)findViewById(R.id.lrc);		name = (TextView)findViewById(R.id.name);		playtime = (TextView)findViewById(R.id.playtime);//已经播放的时间		durationTime = (TextView)findViewById(R.id.duration);		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 		maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//获得最大音量  		currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获得当前音量 				playBtn = (ImageButton)findViewById(R.id.playBtn);		playBtn.setOnClickListener(new View.OnClickListener() {						@Override			public void onClick(View v) {				switch (flag) {				case STATE_PLAY:					pause();					break;				case STATE_PAUSE:					play();					break;				}			}		});				seekbar = (SeekBar)findViewById(R.id.seekbar);		seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {						@Override			public void onStopTrackingTouch(SeekBar seekBar) {				play();			}						@Override			public void onStartTrackingTouch(SeekBar seekBar) {				pause();			}						@Override			public void onProgressChanged(SeekBar seekBar, int progress,					boolean fromUser) {				if (fromUser){					seekbar_change(progress);				}			}		});				rewindBtn = (ImageButton)findViewById(R.id.rewindBtn);		rewindBtn.setOnTouchListener(new OnTouchListener() {						@Override			public boolean onTouch(View v, MotionEvent event) {				switch (event.getAction()) {				case MotionEvent.ACTION_DOWN:					pause();					rewind();					break;				case MotionEvent.ACTION_UP:					play();					break;				}				return true;			}		});				forwardBtn = (ImageButton)findViewById(R.id.forwardBtn);		forwardBtn.setOnTouchListener(new OnTouchListener() {						@Override			public boolean onTouch(View v, MotionEvent event) {				switch (event.getAction()){				case MotionEvent.ACTION_DOWN:					pause();					forward();					break;				case MotionEvent.ACTION_UP:					play();					break;				}				return true;			}		});				latestBtn = (ImageButton)findViewById(R.id.latestBtn);		latestBtn.setOnClickListener(new View.OnClickListener() {						@Override			public void onClick(View v) {				latestOne();			}		});				nextBtn = (ImageButton)findViewById(R.id.nextBtn);		nextBtn.setOnClickListener(new View.OnClickListener() {						@Override			public void onClick(View v) {				nextOne();			}		});					}		@Override	protected void onStart() {		super.onStart();		setup();		play();			}		private void loadClip(){		seekbar.setProgress(0);		//int pos = _ids[position];		name.setText(_titles[position]);//设置歌曲名		Intent intent = new Intent();		intent.putExtra("_ids", _ids);		intent.putExtra("position", position);		intent.setAction("com.alex.media.MUSIC_SERVICE");		startService(intent);	}		private void init(){		IntentFilter filter = new IntentFilter();		filter.addAction(MUSIC_CURRENT);		filter.addAction(MUSIC_DURATION);		filter.addAction(MUSIC_NEXT);		filter.addAction(MUSIC_UPDATE);		registerReceiver(musicReceiver, filter);	}		private void setup(){		refreshView();		loadClip();		init();	}		/**	 * 音乐播放	 */	private void play(){		flag = STATE_PLAY;		playBtn.setBackgroundResource(R.drawable.pause_selecor);		Intent intent = new Intent();		intent.setAction("com.alex.media.MUSIC_SERVICE");		intent.putExtra("op",MUSIC_PLAY);		startService(intent);	}		/**	 * 音乐暂停	 */	private void pause(){		flag = STATE_PAUSE;		playBtn.setBackgroundResource(R.drawable.play_selecor);		Intent intent = new Intent();		intent.setAction("com.alex.media.MUSIC_SERVICE");		intent.putExtra("op",MUSIC_PAUSE);		startService(intent);	}		/**	 * 音乐停止	 */	private void stop(){		unregisterReceiver(musicReceiver);		Intent intent = new Intent();		intent.setAction("com.alex.media.MUSIC_SERVICE");		intent.putExtra("op", MUSIC_STOP);		startService(intent);	}		/**	 * 用户拖动进度条	 */	private void seekbar_change(int progress){		Intent intent = new Intent();		intent.setAction("com.alex.media.MUSIC_SERVICE");		intent.putExtra("op", PROGRESS_CHANGE);		intent.putExtra("progress", progress);		startService(intent);	}		/**	 * 快退	 */	private void rewind(){		Intent intent = new Intent();		intent.setAction("com.alex.media.MUSIC_SERVICE");		intent.putExtra("op", MUSIC_REWIND);		startService(intent);	}		/**	 * 快进	 */	private void forward(){		Intent intent = new Intent();		intent.setAction("com.alex.media.MUSIC_SERVICE");		intent.putExtra("op", MUSIC_FORWARD);		startService(intent);	}		/**	 * 上一首	 */		private void latestOne(){		if (position==0){			position = _ids.length-1;		} else if (position>0){			position--;		}		stop();		setup();		play();	}		/**	 * 下一首	 */	private void nextOne(){		if (_ids.length==1){			position = position;			Intent intent = new Intent();			intent.setAction("com.alex.media.MUSIC_SERVICE");			intent.putExtra("length", 1);			startService(intent);			play();			return;					} else if (position == _ids.length-1){			position = 0;		} else if (position < _ids.length-1){			position++;		}		stop();		setup();		play();	}		/**	 * 定义musicReceiver,接收MusicService发送的广播	 */	protected BroadcastReceiver musicReceiver = new BroadcastReceiver() {				@Override		public void onReceive(Context context, Intent intent) {			String action = intent.getAction();			if (action.equals(MUSIC_CURRENT)){				currentPosition =  intent.getExtras().getInt("currentTime");//获得当前播放位置				playtime.setText(toTime(currentPosition));				seekbar.setProgress(currentPosition);//设置进度条				Iterator<Integer> iterator=lrc_map.keySet().iterator();				while(iterator.hasNext()){					Object o = iterator.next();		        	LRCbean val = lrc_map.get(o);		        	if (val!=null){		        					        	if (currentPosition>val.getBeginTime()			        			&&currentPosition<val.getBeginTime()+val.getLineTime()){			        		lrcText.setText(val.getLrcBody());			        		break;			        	}		        	}				}			} else if (action.equals(MUSIC_DURATION)){				duration = intent.getExtras().getInt("duration");				seekbar.setMax(duration);				durationTime.setText(toTime(duration));							} else if (action.equals(MUSIC_NEXT)){				nextOne();			} else if (action.equals(MUSIC_UPDATE)){				position = intent.getExtras().getInt("position");				//refreshView();				//name.setText(_titles[position]);				setup();			}		}	};		@Override	protected void onStop() {		super.onStop();		unregisterReceiver(musicReceiver);					}		public boolean onKeyDown(int keyCode, KeyEvent event) {		if (keyCode == event.KEYCODE_BACK) {			Intent intent = new Intent();			intent.setClass(this, ListActivity.class);			startActivity(intent);			finish();		}		return true;    }	/**	 * 音量控制	 */	public boolean dispatchKeyEvent(KeyEvent event) { 		int action = event.getAction(); 		int keyCode = event.getKeyCode(); 		switch (keyCode) { 			case KeyEvent.KEYCODE_VOLUME_UP: 			if (action == KeyEvent.ACTION_UP) {				if (currentVolume<maxVolume){					currentVolume = currentVolume + 1;					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);				} else {					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);				}			} 			return false; 			case KeyEvent.KEYCODE_VOLUME_DOWN: 			if (action == KeyEvent.ACTION_UP) { 				if (currentVolume>0){					currentVolume = currentVolume - 1;					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume , 0);				} else {					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);				}			} 			return false; 			default: 			return super.dispatchKeyEvent(event); 		} 	}		/**	 * 解析歌词	 * @param path	 */	private void read(String path){		lrc_map.clear();    	TreeMap<Integer, LRCbean> lrc_read = new TreeMap<Integer, LRCbean>();    	String data = "";    	BufferedReader br = null;    	File file = new File(path);    	if (!file.exists()){    		lrcText.setText("歌词文件不存在...");    		return;    	}    	FileInputStream stream = null;		try {			stream = new FileInputStream(file);            br = new BufferedReader(new InputStreamReader(					stream, "GB2312"));		} catch (FileNotFoundException e) {			e.printStackTrace();		} catch (UnsupportedEncodingException e) {			e.printStackTrace();		}		try {			while((data=br.readLine())!=null){				if (data.length()>6){					if (data.charAt(3)==':'&&data.charAt(6)=='.'){//从歌词正文开始						data = data.replace("[", "");						data = data.replace("]", "@");						data = data.replace(".", ":");						String lrc[] = data.split("@");						String lrcContent= null;						if (lrc.length==2){							lrcContent = lrc[lrc.length-1];//歌词						}else{							lrcContent = "";						}						String lrcTime[] = lrc[0].split(":");												int m = Integer.parseInt(lrcTime[0]);//分						int s = Integer.parseInt(lrcTime[1]);//秒						int ms = Integer.parseInt(lrcTime[2]);//毫秒												int begintime = (m*60 + s) * 1000 + ms;//转换成毫秒						LRCbean lrcbean = new LRCbean();						lrcbean.setBeginTime(begintime);//设置歌词开始时间						lrcbean.setLrcBody(lrcContent);//设置歌词的主体						lrc_read.put(begintime,lrcbean);					}				}			}			stream.close();		} catch (IOException e) {			e.printStackTrace();		}				//计算每句歌词需要的时间		lrc_map.clear();		data = "";		Iterator<Integer> iterator = lrc_read.keySet().iterator();		LRCbean oldval = null;		int i = 0;		while (iterator.hasNext()){			Object ob = iterator.next();			LRCbean val = lrc_read.get(ob);			if (oldval==null){				oldval = val;			} else{				LRCbean item1 = new LRCbean();				item1 = oldval;				item1.setLineTime(val.getBeginTime()-oldval.getBeginTime());				lrc_map.put(new Integer(i), item1);				i++;				oldval = val;			}		}		    }		/**	 * 读取sd卡歌词	 */	public void refreshView() {		myCur = getContentResolver().query(				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,				new String[] { MediaStore.Audio.Media.TITLE,						MediaStore.Audio.Media.DURATION,						MediaStore.Audio.Media.ARTIST,						MediaStore.Audio.Media.ALBUM,						MediaStore.Audio.Media.DISPLAY_NAME }, "_id=?",				new String[] { _ids[position] + "" }, null);		myCur.moveToFirst();				String name = myCur.getString(4).substring(0,				myCur.getString(4).lastIndexOf("."));		read("/sdcard/" + name + ".lrc");	}		/**	 * 时间格式转换函数	 * @param time	 * @return	 */	public String toTime(int time) {		time /= 1000;		int minute = time / 60;		int hour = minute / 60;		int second = time % 60;		minute %= 60;		return String.format("%02d:%02d", minute, second);	}			}



类12  MusicListAdapter
package com.alex.media;import android.content.Context;import android.database.Cursor;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ImageView;import android.widget.TextView;public class MusicListAdapter extends BaseAdapter {	private Context myCon;	private Cursor myCur;	private int pos=-1;	public MusicListAdapter(Context con, Cursor cur) {		myCon = con;		myCur = cur;	}	@Override	public int getCount() {		return myCur.getCount();	}	@Override	public Object getItem(int position) {		return position;	}	@Override	public long getItemId(int position) {		return position;	}	@Override	public View getView(int position, View convertView, ViewGroup parent) {		convertView = LayoutInflater.from(myCon).inflate(R.layout.musiclist,				null);		myCur.moveToPosition(position);		TextView tv_music = (TextView) convertView.findViewById(R.id.music);		if (myCur.getString(0).length()>24){			try {				String musicTitle = bSubstring(myCur.getString(0).trim(),24);				tv_music.setText(musicTitle);			} catch (Exception e) {								e.printStackTrace();			}		}else {			tv_music.setText(myCur.getString(0).trim());		}		TextView tv_singer = (TextView) convertView.findViewById(R.id.singer);		if (myCur.getString(2).equals("<unknown>")){			tv_singer.setText("未知艺术家");		}else{			tv_singer.setText(myCur.getString(2));		}		TextView tv_time = (TextView) convertView.findViewById(R.id.time);		tv_time.setText(toTime(myCur.getInt(1)));		ImageView img = (ImageView)convertView.findViewById(R.id.listitem);		if (position == pos){			img.setImageResource(R.drawable.isplaying);		}else{			img.setImageResource(R.drawable.item);		}		return convertView;	}		public void setItemIcon(int position){		pos = position;	}	/**	 * 时间格式转换	 * @param time	 * @return	 */	public String toTime(int time) {		time /= 1000;		int minute = time / 60;		int hour = minute / 60;		int second = time % 60;		minute %= 60;		return String.format("%02d:%02d", minute, second);	}		/**	 * 字符串裁剪	 * @param s	 * @param length	 * @return	 * @throws Exception	 */	public static String bSubstring(String s, int length) throws Exception  	{  	 	    byte[] bytes = s.getBytes("Unicode");  	    int n = 0; // 表示当前的字节数  	    int i = 2; // 要截取的字节数,从第3个字节开始  	    for (; i < bytes.length && n < length; i++)  	    {  	        // 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节  	        if (i % 2 == 1)  	        {  	            n++; // 在UCS2第二个字节时n加1  	        }  	        else 	        {  	            // 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节  	            if (bytes[i] != 0)  	            {  	                n++;  	            }  	        }  	    }  	    // 如果i为奇数时,处理成偶数  	    if (i % 2 == 1)  	 	    {  	        // 该UCS2字符是汉字时,去掉这个截一半的汉字  	        if (bytes[i - 1] != 0)  	            i = i - 1;  	        // 该UCS2字符是字母或数字,则保留该字符  	        else 	            i = i + 1;  	    }  	 	    return new String(bytes, 0, i, "Unicode");  	}  }



类13  MusicService

package com.alex.media;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import android.app.Service;import android.content.BroadcastReceiver;import android.content.ContentValues;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.database.Cursor;import android.media.MediaPlayer;import android.media.MediaPlayer.OnPreparedListener;import android.net.Uri;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.provider.MediaStore;import android.telephony.TelephonyManager;public class MusicService extends Service implements MediaPlayer.OnCompletionListener{	private static final String MUSIC_CURRENT = "com.alex.currentTime";	private static final String MUSIC_DURATION = "com.alex.duration";	private static final String MUSIC_NEXT = "com.alex.next";	private static final String MUSIC_UPDATE = "com.alex.update";	private static final String MUSIC_LIST = "com.alex.list";	private static final int MUSIC_PLAY = 1;	private static final int MUSIC_PAUSE = 2;	private static final int MUSIC_STOP = 3;	private static final int PROGRESS_CHANGE = 4;	private static final int MUSIC_REWIND = 5;	private static final int MUSIC_FORWARD = 6;	private MediaPlayer mp = null;	int progress;	private Uri uri = null;	private int id=10000;	private Handler handler=null;	private Handler rHandler = null;	private Handler fHandler = null;	private int currentTime;	private int duration;	private DBHelper dbHelper = null;	private int flag;	private int position;	private int _ids[];	private int _id;	@Override	public void onCreate() {		super.onCreate();		if (mp != null) {			mp.reset();			mp.release();			mp = null;		}		mp = new MediaPlayer();		mp.setOnCompletionListener(this);				/**		 * 注册来电接收器		 */		IntentFilter filter = new IntentFilter();		filter.addAction("android.intent.action.ANSWER");		registerReceiver(InComingSMSReceiver, filter);				rHandler = new Handler();		fHandler = new Handler();		rHandler.removeCallbacks(rewind);		fHandler.removeCallbacks(forward);	}	@Override	public void onDestroy() {		super.onDestroy();		if (mp!=null){			stop();			mp = null;		}		if (dbHelper!=null){			dbHelper.close();			dbHelper = null;		}		if (handler!=null){			handler=null;		}	}		@Override	public void onStart(Intent intent, int startId) {		super.onStart(intent, startId);				/**		 * 初始化mp		 */		if ((flag==0)&&(intent.getExtras().getInt("list")==1)){			return;		}		if (intent.getIntArrayExtra("_ids")!=null){			_ids = intent.getIntArrayExtra("_ids");		}		int position1 = intent.getIntExtra("position", -1);		if (position1!=-1){			position = position1;			_id = _ids[position];		}				int length = intent.getIntExtra("length", -1);		if (_id!=-1){			if (id!=_id){				id=_id;				uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,						"" + _id);				DBOperate(_id);				try {					mp.reset();					mp.setDataSource(this, uri);																			} catch (Exception e) {					e.printStackTrace();				}			} else if (length==1){								try {					mp.reset();					mp.setDataSource(this, uri);				} catch(Exception e){					e.printStackTrace();				}			}		}		setup();		init();		if (position!=-1){			Intent intent1 = new Intent();			intent1.setAction(MUSIC_LIST);			intent1.putExtra("position", position);			sendBroadcast(intent1);		}				/**		 * 开始、暂停、停止		 */		int op = intent.getIntExtra("op", -1);		if (op!=-1){			switch (op) {			case MUSIC_PLAY://播放				if(!mp.isPlaying()){					play();				}				break;			case MUSIC_PAUSE://暂停				if (mp.isPlaying()){					pause();				}				break;			case MUSIC_STOP://停止				stop();				break;			case PROGRESS_CHANGE://改变歌曲进度			    currentTime = intent.getExtras().getInt("progress");			    mp.seekTo(currentTime);			    				break;			case MUSIC_REWIND://快退				rewind();				break;			case MUSIC_FORWARD://快进				forward();				break;			} 		}			}	@Override	public IBinder onBind(Intent intent) {		return null;	}		private void play(){		if (mp!=null){			mp.start();		}		flag = 1;		rHandler.removeCallbacks(rewind);		fHandler.removeCallbacks(forward);	}		private void pause(){		if (mp!=null){			mp.pause();		}		flag = 1;	}		private void stop(){		if (mp!=null){			mp.stop();			try {				mp.prepare();				mp.seekTo(0);			} catch (IllegalStateException e) {				e.printStackTrace();			} catch (IOException e) {				e.printStackTrace();			}			handler.removeMessages(1);			rHandler.removeCallbacks(rewind);			fHandler.removeCallbacks(forward);		}	}			private void init(){		final Intent intent = new Intent();		intent.setAction(MUSIC_CURRENT);		if (handler==null){			handler = new Handler(){				@Override				public void handleMessage(Message msg) {					super.handleMessage(msg);					if (msg.what==1){						if(flag==1){							currentTime = mp.getCurrentPosition();							intent.putExtra("currentTime", currentTime);							sendBroadcast(intent);						}						handler.sendEmptyMessageDelayed(1, 600);					}				}			};		}	}		private void setup(){		final Intent intent = new Intent();		intent.setAction(MUSIC_DURATION);		try {			if (!mp.isPlaying()){				mp.prepare();			}			mp.setOnPreparedListener(new OnPreparedListener() {				@Override				public void onPrepared(MediaPlayer mp) {					handler.sendEmptyMessage(1);				}			});		} catch (IllegalStateException e) {			e.printStackTrace();		} catch (IOException e) {			e.printStackTrace();		}		duration = mp.getDuration();		intent.putExtra("duration", duration);		sendBroadcast(intent);	}		private void rewind(){//快进		rHandler.post(rewind);	}		private void forward(){		fHandler.post(forward);	}		Runnable rewind = new Runnable() {				@Override		public void run() {			if (currentTime>=0){				currentTime = currentTime - 5000;				mp.seekTo(currentTime);				rHandler.postDelayed(rewind, 500);			}					}	};		Runnable forward = new Runnable() {				@Override		public void run() {			if (currentTime<=duration){				currentTime = currentTime + 5000;				mp.seekTo(currentTime);				fHandler.postDelayed(forward, 500);			}		}	};		@Override	public void onCompletion(MediaPlayer mp) {		/*Intent intent = new Intent();		intent.setAction(MUSIC_NEXT);		sendBroadcast(intent);		System.out.println("onCompletion...");*/		if (_ids.length==1){			position = position;					} else if (position == _ids.length-1){			position = 0;		} else if (position < _ids.length-1){			position++;		}		uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,				"" + _ids[position]);		DBOperate(_ids[position]);		id=_ids[position];		try {			mp.reset();			mp.setDataSource(this, uri);											} catch (Exception e) {			e.printStackTrace();		}		setup();		init();		stop();		play();				//通知音乐列表更新		Intent intent = new Intent();		intent.setAction(MUSIC_LIST);		intent.putExtra("position", position);		sendBroadcast(intent);				//通知播放界面更新		Intent intent1 = new Intent();		intent1.setAction(MUSIC_UPDATE);		intent1.putExtra("position", position);		sendBroadcast(intent1);							}		/**	 * 数据库操作	 * @param pos	 */	private void DBOperate(int pos){		dbHelper = new DBHelper(this, "music.db", null, 2);		Cursor c = dbHelper.query(pos);		Date currentTime = new Date();   		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   		String dateString = formatter.format(currentTime); 		if (c==null||c.getCount()==0){//如果查询结果为空						ContentValues values = new ContentValues();			values.put("music_id", pos);			values.put("clicks", 1);			values.put("latest", dateString);			dbHelper.insert(values);		} else{			c.moveToNext();			int clicks = c.getInt(2);			clicks++;			ContentValues values = new ContentValues();			values.put("clicks", clicks);			values.put("latest", dateString);			dbHelper.update(values, pos);		}		if (c!=null){			c.close();			c = null;		}		if (dbHelper!=null){			dbHelper.close();			dbHelper = null;		}	}		/**	 * 来电广播接收器	 */	protected BroadcastReceiver InComingSMSReceiver = new BroadcastReceiver() {		@Override		public void onReceive(Context context, Intent intent) {			System.out.println("android.intent.action.ANSWER");			if (intent.getAction().equals(Intent.ACTION_ANSWER)){				TelephonyManager telephonymanager = 					(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);				switch (telephonymanager.getCallState()) {					case TelephonyManager.CALL_STATE_RINGING:						pause();						break;					case TelephonyManager.CALL_STATE_OFFHOOK:						play();						break;					 default:						 break;				}			}		}	};		}


类14  RecentlyActivity

package com.alex.media;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.database.Cursor;import android.media.AudioManager;import android.os.Bundle;import android.provider.MediaStore;import android.view.KeyEvent;import android.view.View;import android.widget.AdapterView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.AdapterView.OnItemClickListener;import android.widget.LinearLayout.LayoutParams;import com.alex.media.ClicksActivity.ListItemClickListener;public class RecentlyActivity extends Activity {	private DBHelper dbHelper = null;	private ListView listview;	private int[] _ids;	private String[]_titles;	Cursor cursor = null;	int[] music_id;	//关于音量的变量	private AudioManager mAudioManager = null;	private int maxVolume;//最大音量	private int currentVolume;//当前音量	@Override	protected void onCreate(Bundle savedInstanceState) {		// TODO Auto-generated method stub		super.onCreate(savedInstanceState);		dbHelper = new DBHelper(this, "music.db", null, 2);		cursor = dbHelper.queryRecently();		cursor.moveToFirst();		int num;		if (cursor!=null){			num = cursor.getCount();			System.out.println("clicks:" + num);		} else{			return;		}		String idString ="";		if (num>=10){			for(int i=0;i<10;i++){				music_id = new int[10];				music_id[i]=cursor.getInt(cursor.getColumnIndex("music_id"));				if (i<9){					idString = idString+music_id[i]+",";				} else{					idString = idString+music_id[i];				}				cursor.moveToNext();			} 		}else if(num>0){			for(int i=0;i<num;i++){				music_id = new int[num];				music_id[i]=cursor.getInt(cursor.getColumnIndex("music_id"));				if (i<num-1){					idString = idString+music_id[i]+",";				} else{					idString = idString+music_id[i];				}				cursor.moveToNext();			}		}		if (cursor!=null){			cursor.close();			cursor=null;		}		listview = new ListView(this);		Cursor c = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,        			new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME} , MediaStore.Audio.Media._ID + " in ("+ idString + ")", null,null);				  c.moveToFirst();	        _ids = new int[c.getCount()];	        _titles = new String[c.getCount()];	        for(int i=0;i<c.getCount();i++){	        	_ids[i] = c.getInt(3);	        	_titles[i] = c.getString(0);	        		        	c.moveToNext();	        }	        listview.setAdapter(new MusicListAdapter(this, c));	        listview.setOnItemClickListener(new ListItemClickListener());	        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 			maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//获得最大音量  			currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获得当前音量 			LinearLayout list = new LinearLayout(this);			list.setBackgroundResource(R.drawable.listbg);	        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(	        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);	        list.addView(listview,params);	        setContentView(list);	    }	   	    class ListItemClickListener implements OnItemClickListener{	    	@Override	    	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {	    		// TODO Auto-generated method stub	    		Intent intent = new Intent(RecentlyActivity.this,MusicActivity.class);	    		intent.putExtra("_ids", _ids);	    		intent.putExtra("_titles", _titles);	    		intent.putExtra("position", position);	    		startActivity(intent);	    		finish();	    	}	    		    }	    public boolean onKeyDown(int keyCode, KeyEvent event) {			if (keyCode == event.KEYCODE_BACK) {				Intent intent = new Intent();				intent.setClass(this, MainActivity.class);				startActivity(intent);				finish();			}			return true;	    }	    public boolean dispatchKeyEvent(KeyEvent event) { 			int action = event.getAction(); 			int keyCode = event.getKeyCode(); 			switch (keyCode) { 				case KeyEvent.KEYCODE_VOLUME_UP: 				if (action == KeyEvent.ACTION_UP) {					if (currentVolume<maxVolume){						currentVolume = currentVolume + 1;						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);					} else {						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);					}				} 				return false; 				case KeyEvent.KEYCODE_VOLUME_DOWN: 				if (action == KeyEvent.ACTION_UP) { 					if (currentVolume>0){						currentVolume = currentVolume - 1;						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume , 0);					} else {						mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);					}				} 				return false; 				default: 				return super.dispatchKeyEvent(event); 			} 		}}



类15  ScanSdReceiver
package com.alex.media;import android.app.AlertDialog;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.database.Cursor;import android.provider.MediaStore;import android.widget.Toast;public class ScanSdReceiver extends BroadcastReceiver {	private AlertDialog.Builder  builder = null;	private AlertDialog ad = null;	private int count1;	private int count2;	private int count;	@Override	public void onReceive(Context context, Intent intent) {		String action = intent.getAction();		if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)){			Cursor c1 = context.getContentResolver()			.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,					new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME },					null, null, null);			count1 = c1.getCount();			System.out.println("count:"+count);			builder = new AlertDialog.Builder(context);			builder.setMessage("正在扫描存储卡...");			ad = builder.create();			ad.show();					}else if(Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)){			Cursor c2 = context.getContentResolver()			.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,					new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME },					null, null, null);			count2 = c2.getCount();			count = count2-count1;			ad.cancel();			if (count>=0){				Toast.makeText(context, "共增加" + count + "首歌曲", Toast.LENGTH_LONG).show();			} else {				Toast.makeText(context, "共减少" + count + "首歌曲", Toast.LENGTH_LONG).show();			}						}			}		}


类16  TestMain


package com.alex.media;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import android.app.AlertDialog;import android.app.TabActivity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.database.Cursor;import android.media.AudioManager;import android.os.Bundle;import android.provider.MediaStore;import android.view.KeyEvent;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.TabHost;import android.widget.AdapterView.OnItemClickListener;import android.widget.LinearLayout.LayoutParams;public class TestMain extends TabActivity implements TabHost.TabContentFactory{		@Override	protected void onStart() {		IntentFilter filter = new IntentFilter();        filter.addAction(MUSIC_LIST);		registerReceiver(changeItem, filter);		super.onStart();	}	private static final String MUSIC_LIST = "com.alex.list";	private ListView listview;	private int[] _ids;	private String[]_titles;	private int pos;	private  MusicListAdapter adapter;	private ScanSdReceiver scanSdReceiver = null;	private AlertDialog ad = null;	private AlertDialog.Builder  builder = null;	private Cursor c;	private String[] albums;	private String[] artists;		//关于音量的变量	private AudioManager mAudioManager = null;	private int maxVolume;//最大音量	private int currentVolume;//当前音量	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		TabHost th = getTabHost();		th.addTab(th.newTabSpec("list").setIndicator("音乐列表").setContent(this));		th.addTab(th.newTabSpec("artists").setIndicator("艺术家").setContent(this));		th.addTab(th.newTabSpec("albums").setIndicator("专辑").setContent(this));                //测试是否有音乐在播放        Intent intent = new Intent();        intent.setAction("com.alex.media.MUSIC_SERVICE");        intent.putExtra("list", 1);        startService(intent);        	}		@Override	public View createTabContent(String tag) {		if (tag.equals("list")){			c = this.getContentResolver()    		.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,    				new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME },    				null, null, null);		    if (c==null || c.getCount()==0){		    	builder = new AlertDialog.Builder(this);				builder.setMessage("存储列表为空...").setPositiveButton("确定", null);				ad = builder.create();				ad.show();		    }		    c.moveToFirst();		    _ids = new int[c.getCount()];		    _titles = new String[c.getCount()];		    for(int i=0;i<c.getCount();i++){		    	_ids[i] = c.getInt(3);		    	_titles[i] = c.getString(0);		    	c.moveToNext();		    }		    listview = new ListView(this);		    listview.setOnItemClickListener(new ListItemClickListener());		    adapter = new MusicListAdapter(this, c);	        listview.setAdapter(adapter);		} else if (tag.equals("artists")){			c = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,					new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME}, 					null, 					null,					null);			c.moveToFirst();			int num = c.getCount();			HashSet set = new HashSet();			for (int i = 0; i < num; i++){				if (c.getString(2).equals("<unknown>")){					set.add("未知艺术家");				}else{					set.add(c.getString(2));					c.moveToNext();				}			}			num = set.size();			Iterator it = set.iterator();			artists = new String[num];			int i = 0;			while(it.hasNext()){				artists[i] = it.next().toString();				i++;			}			listview = new ListView(this);			listview.setAdapter(new ArtistListAdapter(this, artists));			listview.setOnItemClickListener(new ArtistsItemClickListener());		} else if (tag.equals("albums")){			Cursor c = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,					new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media.ALBUM,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME}, 					null, 					null,					MediaStore.Audio.Media.ALBUM);			c.moveToFirst();			int num = c.getCount();			HashSet set = new HashSet();			for (int i = 0; i < num; i++){				set.add(c.getString(3));				c.moveToNext();			}			num = set.size();			Iterator it = set.iterator();			albums = new String[num];			int i = 0;			while(it.hasNext()){				albums[i] = it.next().toString();				i++;			}			String album="";			for (int j=0;j<num; j++){				if (j<num-1){					album = album + "'" + albums[j] + "',"; 				} else{					album = album + "'" + albums[j] + "'";				}			}						Cursor c1 = this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,					new String[]{MediaStore.Audio.Media.TITLE,					MediaStore.Audio.Media.DURATION,					MediaStore.Audio.Media.ARTIST,					MediaStore.Audio.Media.ALBUM,					MediaStore.Audio.Media._ID,					MediaStore.Audio.Media.DISPLAY_NAME}, 					null,					null,					MediaStore.Audio.Media.ALBUM);			c1.moveToFirst();			HashMap<String, String> map = new HashMap<String, String>();			int num1 = c1.getCount();			for (int j=0;j<num1;j++){				map.put(c1.getString(3), c1.getString(2));				c1.moveToNext();			}			listview = new ListView(this);			listview.setAdapter(new AlbumListAdapter(this, albums,map));			listview.setOnItemClickListener(new AlbumsItemClickListener());		}                mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 		maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//获得最大音量  		currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//获得当前音量 		LinearLayout list = new LinearLayout(this);		list.setBackgroundResource(R.drawable.listbg);        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(        LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);        list.removeAllViews();        list.addView(listview,params);		return list;	}			class ListItemClickListener implements OnItemClickListener{    	@Override    	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {    		// TODO Auto-generated method stub    		Intent intent = new Intent(TestMain.this,MusicActivity.class);    		intent.putExtra("_ids", _ids);    		intent.putExtra("_titles", _titles);    		intent.putExtra("position", position);    		startActivity(intent);    		finish();    	}    	    }	class ArtistsItemClickListener implements OnItemClickListener{    	@Override    	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {    		Intent intent = new Intent();    		intent.setClass(TestMain.this, ArtistActivity.class);    		intent.putExtra("artist", artists[position]);    		startActivity(intent);    	}    }		class AlbumsItemClickListener implements OnItemClickListener{    	@Override    	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {    		Intent intent = new Intent();    		intent.setClass(TestMain.this, AlbumActivity.class);    		intent.putExtra("albums", albums[position]);    		startActivity(intent);    	}    }			               public boolean onKeyDown(int keyCode, KeyEvent event) {		if (keyCode == event.KEYCODE_BACK) {			if (scanSdReceiver!=null)      				unregisterReceiver(scanSdReceiver);			Intent intent = new Intent();			intent.setClass(this, MainActivity.class);			startActivity(intent);			finish();		}		return true;    }    public boolean dispatchKeyEvent(KeyEvent event) { 		int action = event.getAction(); 		int keyCode = event.getKeyCode(); 		switch (keyCode) { 			case KeyEvent.KEYCODE_VOLUME_UP: 			if (action == KeyEvent.ACTION_UP) {				if (currentVolume<maxVolume){					currentVolume = currentVolume + 1;					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);				} else {					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);				}			} 			return false; 			case KeyEvent.KEYCODE_VOLUME_DOWN: 			if (action == KeyEvent.ACTION_UP) { 				if (currentVolume>0){					currentVolume = currentVolume - 1;					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume , 0);				} else {					mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);				}			} 			return false; 			default: 			return super.dispatchKeyEvent(event); 		} 	}    private BroadcastReceiver changeItem = new BroadcastReceiver() {				@Override		public void onReceive(Context context, Intent intent) {			if (intent.getAction().equals(MUSIC_LIST)){				pos = intent.getExtras().getInt("position");				adapter.setItemIcon(pos);//改变列表项图标				adapter.notifyDataSetChanged();//通知UI更新			}					}	};		@Override	protected void onStop() {		super.onStop();		unregisterReceiver(changeItem);	}}
1 楼 zxc3210 2011-08-24  
请问怎读到歌词
  相关解决方案