播放器组件 fragment
package com.wuxifu.widget;
import java.io.Serializable;
import com.example.tabhost002.R;
import com.wuxifu.musiclist.MusicList;
import com.wuxifu.new_utils.Newest;
import com.wuxifu.utils.Constant;
import com.wuxifu.widget.MyService.MyBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyPlayer extends Fragment implements OnClickListener
{
private MyBinder mbinder;
int i = 0;
private SeekBar seekBar;
private ImageView im_play;
private TextView tv_currenttime;
private TextView tv_totaltime;
private ImageView im_shuffle;
private ImageView im_join;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
View inflate = inflater.inflate(R.layout.play, null);
iniUI(inflate);
iniService();
return inflate;
}
private void iniService()
{
Intent service = new Intent(getActivity(), MyService.class);
ServiceConnection conn = new ServiceConnection()
{
@Override
public void onServiceDisconnected(ComponentName name)
{
}
@Override
public void onServiceConnected(ComponentName name,
IBinder service)
{
mbinder = (MyBinder) service;
// updateUI();
}
};
getActivity().bindService(service, conn,
Context.BIND_AUTO_CREATE);
// getActivity().
}
private void iniUI(View inflate)
{
im_play = (ImageView) inflate.findViewById(R.id.im_play);
ImageView im_pre = (ImageView) inflate
.findViewById(R.id.im_pre);
ImageView im_next = (ImageView) inflate
.findViewById(R.id.im_next);
im_shuffle = (ImageView) inflate
.findViewById(R.id.im_shuffle);
im_join = (ImageView)inflate.findViewById(R.id.im_join);
seekBar = (SeekBar) inflate.findViewById(R.id.seekBar1);
// 当seekbar被拉到别的进度的时候,通知mediaplayer从那处播放
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override
public void onStopTrackingTouch(SeekBar seekBar)
{
mbinder.seekTo(seekBar.getProgress());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
@Override
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser)
{
}
});
tv_currenttime = (TextView) inflate
.findViewById(R.id.tv_currenttime);
tv_totaltime = (TextView) inflate
.findViewById(R.id.tv_totaltime);
im_play.setOnClickListener(this);
im_join.setOnClickListener(this);
im_pre.setOnClickListener(this);
im_next.setOnClickListener(this);
im_shuffle.setOnClickListener(this);
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
// Intent service = new Intent(getActivity(), MyService.class);
// ServiceConnection conn = new ServiceConnection()
// {
// @Override
// public void onServiceDisconnected(ComponentName name)
// {
// }
//
// @Override
// public void onServiceConnected(ComponentName name,
// IBinder service)
// {
// mbinder = (MyBinder) service;
// // updateUI();
// }
// };
// getActivity().bindService(service, conn,
// Context.BIND_AUTO_CREATE);
// // getActivity().
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.im_play:
if (mbinder != null)
play();
break;
case R.id.im_pre:
if (mbinder != null)
play_pre();
break;
case R.id.im_next:
if (mbinder != null)
play_next();
break;
case R.id.im_shuffle:
if (mbinder != null)
im_shuffle();
break;
case R.id.im_join:
if (mbinder != null)
toMusicList();
break;
default:
break;
}
}
private void toMusicList()
{
startActivity(new Intent(getActivity(), MusicList.class));
}
int[] ids = new int[]
{ R.drawable.widget_4x4_repeate_order_n,
R.drawable.widget_4x4_repeate_rand_n,
R.drawable.widget_4x4_repeate_single_n };
String[] s = new String[]
{ "循环播放", "随机播放", "单曲播放" };
/**
* 播放模式
*/
private void im_shuffle001()
{
im_shuffle.setImageResource(ids[Constant.Play_mode++ % 3]);
Toast.makeText(getActivity(), s[Constant.Play_mode++ % 3],
Toast.LENGTH_SHORT).show();
// 调用service里的函数就可以得到service里的变量,可以改变service里播放的状态
mbinder.changePlayMode();
if (Constant.Play_mode == 3)
Constant.Play_mode = 0;
}
/**
* 播放模式加强版
*/
private void im_shuffle()
{
mbinder.changePlayMode();
int playMode = mbinder.getPlayMode();
im_shuffle.setImageResource(ids[playMode]);
Toast.makeText(getActivity(), s[playMode], Toast.LENGTH_SHORT)
.show();
}
private void play_next()
{
mbinder.play_next();
}
private void play_pre()
{
mbinder.play_pre();
}
private void play()
{
// 判断播放状态
if (mbinder.isPlaying())
{
// 正在播放再 按下就是要暂停
mbinder.pause();
// 改变src
im_play.setImageResource(R.drawable.widget_play);
} else
{
if (mbinder.isPause())
{
// 如果是暂停状态,再按就是继续播放
mbinder.play();
im_play.setImageResource(R.drawable.widget_4x4_pause_n);
} else
{
mbinder.play(Constant.URL_MUSIC);
mbinder.addSong(new Newest(1, "退后", "周杰伦",Constant.URL_MUSIC));
mbinder.addSong(new Newest(2, "退后", "周杰伦",Constant.URL_MUSIC2));
// 改变src
im_play.setImageResource(R.drawable.widget_4x4_pause_n);
//更新组件
refreshUI();
}
}
}
public void refreshUI()
{
tv_currenttime.postDelayed(new Runnable()
{
@Override
public void run()
{
updateUI();
tv_currenttime.postDelayed(this, 1000);
}
}, 1000);
}
private void updateUI()
{
// 更新的前提就是mbinder返回了,而且 mediaplayer准备好了(运行到onPrepared()),可以播放
tv_currenttime.setText(getCurrenttime());
tv_totaltime.setText(gettotaltime());
seekBar.setProgress(getCurrentPosition());
seekBar.setMax(getDuration());
}
public int getDuration()
{
return mbinder == null ? 0 : mbinder.getDuration();
}
public int getCurrentPosition()
{
return mbinder == null ? 0 : mbinder.getCurrentPosition();
}
public String gettotaltime()
{
return mbinder == null ? null : mbinder.gettotaltime();
}
public String getCurrenttime()
{
return mbinder == null ? null : mbinder.getCurrenttime();
}
public MyBinder getmBinder()
{
return mbinder;
}
public ImageView getPlayIm()
{
return im_play;
}
public void setImageResource_play()
{
im_play.setImageResource(R.drawable.widget_4x4_pause_n);
}
public void setCurrentPosition(int currentPosition)
{
seekBar.setProgress(currentPosition);
}
public void setDuration(int duration)
{
seekBar.setMax(duration);
}
public void setCurrentPosition001()
{
seekBar.setProgress(getCurrentPosition());
}
public void setDuration001()
{
seekBar.setMax(getDuration());
}
}
//////////////////////////////////////////////////service 后台播放music
package com.wuxifu.widget;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import com.example.tabhost002.DeleteService;
import com.example.tabhost002.R;
import com.wuxifu.new_utils.Newest;
import com.wuxifu.utils.Constant;
import com.wuxifu.widget.MyService.MyBinder;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.widget.RemoteViews;
public class MyService extends Service
{
private MediaPlayer mediaPlayer;//=new MediaPlayer();
private int mCurrentPlayMode = 0;
private int mCurrentMusicIndex = 0;
private ArrayList<Newest> musicList = new ArrayList<Newest>();
private ArrayList<Integer> musicIndex = new ArrayList<Integer>();
private MyBinder myBinder;
private NotificationManager manager;
public class MyBinder extends Binder implements Serializable
{
public String gettotaltime()
{
//return getTime(mediaPlayer.getDuration()/1000);
return getTime(getDuration()/1000);
}
private String getTime(int i)
{
StringBuilder sb = new StringBuilder();
int seconds=i%60;
int minutes=i/60;
if(minutes<10)
sb.append("0"+minutes);
else
sb.append(minutes+"");
sb.append(":");
if(seconds<10)
sb.append("0"+seconds);
else
sb.append(seconds+"");
return sb.toString();
}
/** 只有等mediaPlayer运行到onPrepared里 才可以getDuration
* @return
*/
public int getDuration()
{
if(isPrepared)
return mediaPlayer.getDuration();
return 0;
}
public String getCurrenttime()
{
//return getTime(mediaPlayer.getCurrentPosition()/1000);
return getTime(getCurrentPosition()/1000);
}
public void seekTo(int position)
{
mediaPlayer.seekTo(position);
}
/** 只有等mediaPlayer运行到onPrepared里 才可以getCurrentPosition
* @return
*/
public int getCurrentPosition()
{
if(isPrepared)
return mediaPlayer.getCurrentPosition();
return 0;
}
public boolean isPlaying()
{
return mediaPlayer.isPlaying();
}
boolean isPause;
boolean isPrepared;
public void pause()
{
mediaPlayer.pause();
isPause = true;
}
public void play(String string)
{
try
{
isPrepared=false;
mediaPlayer.reset();//重置 MediaPlayer 对象
mediaPlayer.setDataSource(string);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
isPrepared=true;
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
switch (mCurrentPlayMode)
{
case Constant.PLAY_MODE_LOOP:
//%=使得下标永远小于musicList.size()
if(musicList.size()-1>mCurrentMusicIndex)
{
mCurrentMusicIndex++;
mCurrentMusicIndex %= musicList.size();
}
break;
case Constant.PLAY_MODE_SHUFFLE:
if(musicList.size()-1>mCurrentMusicIndex)
{
mCurrentMusicIndex++;
mCurrentMusicIndex %= musicList.size();
mCurrentMusicIndex = musicIndex.get(mCurrentMusicIndex);
}
break;
case Constant.PLAY_MODE_SINGLE_LOOP:
break;
default:
break;
}
play(Constant.URL_HOST_HOME+musicList.get(mCurrentMusicIndex).getUrl());
}
});
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (SecurityException e)
{
e.printStackTrace();
} catch (IllegalStateException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
public void play()
{
mediaPlayer.start();
isPause=false;
}
public boolean isPause()
{
return isPause;
}
public void changePlayMode()
{
mCurrentPlayMode = ++mCurrentPlayMode % 3;
// switch (mCurrentPlayMode)
// {
// case Constant.PLAY_MODE_SHUFFLE:
// Collections.shuffle(musicIndex);
// break;
// case Constant.PLAY_MODE_SINGLE_LOOP:
// break;
// case Constant.PLAY_MODE_LOOP:
// break;
// default:
// break;
// }
}
public int getPlayMode()
{
return mCurrentPlayMode;
}
/**
* @param object 加一首歌
*/
public void addSong(Newest song)
{
musicList.add(song);
//有一首歌就加一个index到下面
musicIndex.add(musicList.size()-1);
}
public ArrayList<Newest> getmusicList()
{
return musicList;
}
public void play_next()
{
if(mCurrentMusicIndex<musicList.size()-1)
play(musicList.get(mCurrentMusicIndex+1).getUrl());
else
play(musicList.get(0).getUrl());
}
public void play_pre()
{
if(mCurrentMusicIndex>0)
play(musicList.get(mCurrentMusicIndex-1).getUrl());
else
play(musicList.get(mCurrentMusicIndex).getUrl());
}
}
public MyService()
{
}
@Override
public boolean onUnbind(Intent intent)
{
musicList.clear();
return super.onUnbind(intent);
}
@Override
public void onCreate()
{
super.onCreate();
mediaPlayer = new MediaPlayer();
mediaPlayer.setLooping(true);
myBinder = new MyBinder();
//在这里设播放完成事件你就死定了,没用!!!!!
// mediaPlayer.setOnCompletionListener(listener);
}
@Override
public IBinder onBind(Intent intent)
{
iniNotification();
return myBinder;
}
private void iniNotification()
{
manager= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification=new Notification(R.drawable.widget_4x4_like_p, "通知", System.currentTimeMillis());
//一点通知就消失
notification.flags=Notification.FLAG_AUTO_CANCEL;
Intent intent=new Intent(this, DeleteService.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, 0);
notification.setLatestEventInfo(this, "hello", "how do you do ", pendingIntent);
manager.notify(R.layout.notification, notification);
}
}