Updating Ui Components in Activity based on MediaPlayer object from Service While Playing music files in background

99封情书 提交于 2019-12-11 03:32:33

问题


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.

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.


回答1:


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"));   



回答2:


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



来源:https://stackoverflow.com/questions/16832389/updating-ui-components-in-activity-based-on-mediaplayer-object-from-service-whil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!