本程序为直接在Activity中计算并更新后台服务音乐播放进度,没有使用到广播
在学习广播之前,艰难的通过这个方法来实现了更新音乐播放进度,不推荐使用,不过感兴趣的可以研究一下。
大概的思路就是通过异步任务类来模拟耗时操作,然后计算出开始播放的时间与当前时间的差,然后跟音乐的总时间相比得到ProgressBar的进度,然后每一秒更新一次。
暂停时可以将暂停的时间加到开始时间上,实现无断点更新
效果图如下:
主函数代码:MusicActivity.java
public class MusicActivity extends AppCompatActivity {
private ListView lv;
private List lvList;
private List<Mp3Info> mp3InfoList;
private ImageButton bt1,bt2;
private ImageView iv1;
private TextView tv1,tv2;
private ProgressBar pb;
private Boolean flag;
private int location;
private long startTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
lv= (ListView) findViewById(R.id.lv);
bt1= (ImageButton) findViewById(R.id.bt1);
bt2= (ImageButton) findViewById(R.id.bt2);
tv1= (TextView) findViewById(R.id.tv1);
tv2= (TextView) findViewById(R.id.tv2);
iv1= (ImageView) findViewById(R.id.iv1);
pb= (ProgressBar) findViewById(R.id.pb);
location=0;
flag=false;
LoadLvList();
ArrayAdapter aa=new ArrayAdapter(this,android.R.layout.simple_list_item_1,lvList);
lv.setAdapter(aa);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
location=position;
setPlay(position);
}
});
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MusicActivity.this, MyService.class);
intent.putExtra("tag",1);
startService(intent);
if(flag==true){
bt1.setImageResource(R.mipmap.btn_pause);
flag=false;
}else{
bt1.setImageResource(R.mipmap.btn_play);
flag=true;
}
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
location=location+1;
setPlay(location);
}
});
}
public void LoadLvList() {
mp3InfoList=new ArrayList<Mp3Info>();
mp3InfoList= MediaUtil.getMusicInfo(this);
lvList=new ArrayList();
for(int i=0;i<mp3InfoList.size();i++){
lvList.add(mp3InfoList.get(i).getTitle());
}
}
public void setPlay(int location){
Intent intent=new Intent(MusicActivity.this, MyService.class);
Mp3Info mp3Info=mp3InfoList.get(location);
intent.putExtra("tag",0);
intent.putExtra("url",mp3Info.getUrl());
intent.putExtra("id",mp3Info.getId());
intent.putExtra("title",mp3Info.getTitle());
intent.putExtra("artist",mp3Info.getArtist());
intent.putExtra("albumId",mp3Info.getAlbumId());
startService(intent);
tv1.setText(mp3Info.getTitle());
tv2.setText(mp3Info.getArtist());
Bitmap bitmap = MediaUtil.getArtwork(getBaseContext(), mp3Info.getId(),
mp3Info.getAlbumId(), true, false);
iv1.setImageBitmap(bitmap);
if(flag==false){
bt1.setImageResource(R.mipmap.btn_play);
flag=true;
}
int duration=(int)mp3Info.getDuration();
new MyProgress().execute(duration);
}
public class MyProgress extends AsyncTask<Integer,Integer,Integer> {
@Override
protected void onPreExecute() {
super.onPreExecute();
startTime=System.currentTimeMillis();
pb.setMax(100);
pb.setProgress(0);
}
@Override
protected Integer doInBackground(Integer... params) {
int i=0;
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}if(flag==true) {
Long currentTime = System.currentTimeMillis();
int progress = (int) ((currentTime - startTime) * 100 / params[0]);
Log.d("===progress", "" + progress);
Log.d("===currentTime", "" + currentTime);
Log.d("===startTime", "" + startTime);
Log.d("===duration", "" + params[0]);
if (progress <= 100) {
publishProgress(progress);
}
}else{
startTime=startTime+1000;
continue;
}
if(1000*i>=params[0]){
break;
}
i++;
}
return 0;
}
@Override
protected void onProgressUpdate(Integer... values) {
Log.d("===","更新进度"+values[0]);
super.onProgressUpdate(values[0]);
pb.setMax(100);
pb.setProgress(values[0]);
}
@Override
protected void onPostExecute(Integer integer) {
Log.d("===","异步类执行完毕");
super.onPostExecute(integer);
setPlay(location);
}
}
}
- service部分的代码:MyService.java
public class MyService extends Service {
private MediaPlayer mediaPlayer;
private NotificationManager nm;
private NotificationCompat.Builder builder;
private Notification nf;
public MyService() {
}
public class MyBind extends Binder {
public MyService getService() {
return MyService.this;
}
}
public void test() {
Log.d("====", "我是Service里的方法");
stopSelf();
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = new MediaPlayer();
Log.d("====", "服务创建");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("====", "服务启动--非绑定方式");
if(intent!=null){
int tag=intent.getIntExtra("tag",3);
switch (tag){
case 0:
String url=intent.getStringExtra("url");
String title=intent.getStringExtra("title");
String artist=intent.getStringExtra("artist");
long id=intent.getLongExtra("id",0);
long albumId=intent.getLongExtra("albumId",0);
try {
if(mediaPlayer!=null){
mediaPlayer.reset();
}
mediaPlayer.setDataSource(this, Uri.parse(url));
mediaPlayer.prepare();
mediaPlayer.setLooping(true);
mediaPlayer.start();
showNotification(title,artist,id,albumId);
} catch (IOException e) {
e.printStackTrace();
}
break;
case 1:
if(mediaPlayer!=null){
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}else{
mediaPlayer.start();
}
}
break;
default:
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
private void showNotification(String title, String artist,long id,long albumId) {
nm= (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
builder= new NotificationCompat.Builder(getBaseContext());
RemoteViews contentView=new RemoteViews(getPackageName(),R.layout.notification_music_layout);
contentView.setTextViewText(R.id.tv1,title);
contentView.setTextViewText(R.id.tv2,artist);
Bitmap bitmap = MediaUtil.getArtwork(this, id,
albumId, true, false);// 获取专辑位图对象,为大图
contentView.setImageViewBitmap(R.id.iv1,bitmap);
builder.setContent(contentView).setSmallIcon(R.mipmap.ic_launcher);
nf=builder.build();
nm.notify(0,nf);
}
@Override
public IBinder onBind(Intent intent) {
Log.d("====", "服务启动--绑定方式");
return new MyBind();
}
@Override
public boolean onUnbind(Intent intent) {
Log.d("====", "服务启动--绑定方式--解除绑定");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
Log.d("====", "服务销毁");
}
}
- 布局代码(用到的两个布局差不多):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.ygd.jreduch10.MusicActivity">
<ListView
android:id="@+id/lv"
android:layout_above="@+id/pb"
android:layout_width="match_parent"
android:layout_height="match_parent"></ListView>
<ProgressBar
android:id="@+id/pb"
android:background="#FFFF"
style="?android:attr/progressBarStyleHorizontal"
android:layout_above="@+id/rl"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="@+id/rl"
android:background="#a19f9f"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv1"
android:src="@mipmap/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_marginLeft="20dp"
android:id="@+id/tv1"
android:textSize="20sp"
android:text="HelloMusic"
android:textColor="#FFFF"
android:layout_toRightOf="@+id/iv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv2"
android:layout_marginLeft="20dp"
android:textColor="#FFFF"
android:layout_toRightOf="@+id/iv1"
android:layout_below="@+id/tv1"
android:text="HelloSinger"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="@+id/bt1"
android:layout_marginRight="20dp"
android:layout_toLeftOf="@+id/bt2"
android:src="@mipmap/btn_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="@+id/bt2"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:src="@mipmap/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>