当退出一个界面时,音乐播放不能停止,因此需要把播放音乐的代码写在service中,
public class MainActivity extends Activity {
private ListView mListView;
private File[] musics;
private MusicAdapter musicAdapter;
private MyReceiver myReceiver;
private SeekBar mSeekBar;
private TextView mTextViewAll;
private TextView mTextViewCurrent;
private Button mButtonPause;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listview);
mButtonPause = (Button) findViewById(R.id.button_pause);
myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.play.music");
registerReceiver(myReceiver, filter);
File sdcard = Environment.getExternalStorageDirectory();
File musicDir = new File(sdcard,"/Music");
Log.d("music",musicDir.getAbsolutePath());
musics = musicDir.listFiles();
musicAdapter = new MusicAdapter(getLayoutInflater(),musics);
mListView.setAdapter(musicAdapter);
mTextViewAll = (TextView) findViewById(R.id.textview_all);
mTextViewCurrent = (TextView) findViewById(R.id.textview_current);
mSeekBar = (SeekBar) findViewById(R.id.seekBar);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> adapterView, View view, int position, long l) {
String music = musics[position].getAbsolutePath();
Intent intent = new Intent(getApplicationContext(),MusicService.class);
intent.putExtra("type",Config.START_NEW_MUSIC);
intent.putExtra("musicName",music);
startService(intent);
}
});
mButtonPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),MusicService.class);
intent.putExtra("type", 3);
startService(intent);
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Intent intent = new Intent(getApplicationContext(),MusicService.class);
intent.putExtra("type",Config.SEEKBAR_TO);
intent.putExtra("progress",seekBar.getProgress());
startService(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
}
class MyReceiver extends BroadcastReceiver{
SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
@Override
public void onReceive(Context context, Intent intent) {
int type = intent.getIntExtra("type",Config.START_NEW_MUSIC);
switch (type){
case 0:
int duration = intent.getIntExtra("duration",0);
mSeekBar.setMax(duration);
String hms = formatter.format(duration);
mTextViewAll.setText("音乐时长:"+hms);
break;
case 1:
int currentTime = intent.getIntExtra("duration",0);
mSeekBar.setProgress(currentTime);
String hms2 = formatter.format(currentTime);
mTextViewCurrent.setText("播放时间:"+hms2);
break;
}
}
}
}
歌曲的播放放在服务中,onStartCommand是整个服务的开始,开始播放音乐;
MusicPlayThread 是一个新的线程,用于获取播放的时间,用于显示进度条的走动和播放时间,不断的刷新view;
int duration 得到音乐本身的时间,用intent传到activity。
public class MusicService extends Service {
private MediaPlayer mediaPlayer;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int type = intent.getIntExtra("type",Config.SEEKBAR_TO);
switch (type){
case Config.START_NEW_MUSIC:
startNewMusic(intent);
break;
case Config.SEEKBAR_TO:
if (mediaPlayer!=null){
int progress = intent.getIntExtra("progress",0);
mediaPlayer.seekTo(progress);
}
break;
case 3:
if (mediaPlayer!=null){
mediaPlayer.pause();
}
break;
}
return super.onStartCommand(intent, flags, startId);
}
private void startNewMusic(Intent intent) {
String musicPath = intent.getStringExtra("musicName");
if (mediaPlayer == null){
mediaPlayer = new MediaPlayer();
}
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(musicPath);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
int duration = mediaPlayer.getDuration();//得到当前播放时间
Intent intent = new Intent("com.play.music");
intent.putExtra("type",0);
intent.putExtra("duration", duration);
sendBroadcast(intent);
MusicPlayThread thread = new MusicPlayThread();
thread.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
class MusicPlayThread extends Thread{
@Override
public void run() {
while (mediaPlayer.isPlaying()){
int time = mediaPlayer.getCurrentPosition();
Intent intent = new Intent("com.play.music");
intent.putExtra("type",1);
intent.putExtra("duration",time);
sendBroadcast(intent);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
super.run();
}
}
}
这是适配器,用于显示歌曲列表,其中MediaMetadataRetriever 以下的部分可以获取mp3文件中的图片和作者名字
public class MusicAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private File[] musics;
public MusicAdapter(LayoutInflater layoutInflater, File[] musics) {
this.musics = musics;
this.mInflater = layoutInflater;
}
@Override
public int getCount() {
return musics.length;
}
@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 viewGroup) {
ViewHolder vh = null;
if (convertView == null){
vh = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_music,null);
vh.tvName = (TextView) convertView.findViewById(R.id.textview);
vh.tvAuthor = (TextView) convertView.findViewById(R.id.text_author);
vh.imageView = (ImageView) convertView.findViewById(R.id.imageview);
convertView.setTag(vh);
}else {
vh = (ViewHolder) convertView.getTag();
}
vh.tvName.setText(musics[position].getName());
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(musics[position].getAbsolutePath());
String author = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
if (author!=null){
vh.tvAuthor.setText(author+" ");
}else{
vh.tvAuthor.setText("<未知> ");
}
byte[] image = mmr.getEmbeddedPicture();
if (image!=null){
Bitmap bitmap = BitmapFactory.decodeByteArray(image,0,image.length);
vh.imageView.setImageBitmap(bitmap);
}else {
vh.imageView.setImageResource(R.mipmap.music);
}
return convertView;
}
class ViewHolder{
TextView tvName;
TextView tvAuthor;
ImageView imageView;
}
}
"http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
"@+id/listview"
android:layout_width="match_parent"
android:layout_weight="1"
android:layout_height="wrap_content">
"match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
"@+id/textview_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="音乐时长:"/>
"@+id/textview_current"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放时间:"/>
"match_parent"
android:layout_height="wrap_content"
android:id="@+id/seekBar"
android:layout_gravity="center_horizontal"
android:layout_weight="1" />
这是listview里面的内容,用adapter适配到listview中,显示歌曲的详细信息
"@+id/imageview"
android:layout_width="50dp"
android:layout_height="50dp" />
"@+id/text_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="作者"/>
"@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="歌曲名"
android:textSize="20dp"/>