Updating Ui Components in Activity based on MediaP

2019-07-16 04:44发布

I am creating an Android music player based on the tutorial from Android Hive here is the link.

http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

Which is tutorial for creating an music player like this.

enter image description here

Now I have successfully created my customized music player using this tutorial but their is a problem in that i.e. it doesn't play music in background. So searched for it and found this post

Playing BG Music Across Activities in Android

and I have found that I have to run MediaPlayer class from Android Service. So I used Android Service , created methods for play and pause and now my background music is running successfully.

Now here is the main problem

How can I update this components from the service which are dependent on MediaPlayer object like seekbar, Timer e.t.c. I am not able to get that.

Because these are dependent on media player object and MediaPlayer object is now in Service.

2条回答
我想做一个坏孩纸
2楼-- · 2019-07-16 05:10

I am just near to finish my Music app now. I have study this code of the Android Default Music app. which help me a lot.

You can see that here: Platform_pkg_App_for_Music

查看更多
▲ chillily
3楼-- · 2019-07-16 05:18

Best way is to use Custom BroadcastReceiver , You can send song name , artist etc details in PutExtra and inside Activity you need to create OnReceiver() and you can get this details using intent.getStringExtra("message");

Write this in ServiceA.java

 Intent intent = new Intent();
 intent.putExtra("message","hi");
 intent.setAction("com.android.activity.SEND_DATA");
 context.sendBroadcast(intent); 

Write this in ActivityA.java

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
   // Extract data included in the Intent
   String message = intent.getStringExtra("message");
   Log.d("receiver", "Got message: " + message);
  }
};

Now register Receiver

LocalBroadcastManager.getInstance(mContext).registerReceiver(mMessageReceiver,
  new IntentFilter("com.android.activity.SEND_DATA"));   
查看更多
登录 后发表回答