How to change the media player from a different activity

允我心安 提交于 2019-12-10 12:22:23

问题


I was wondering if I can declare a media player variable in one activity and then pause or stop it in a separate activity. How would I go about this or is there another way? Thanks


回答1:


I am not a fan of static vars. I'd prefer doing something like this

Android Manifest

<activity name="Player" android:launchMode="singleTop"/>

This former ensures that you have only one instance of the activity running, and that all intents leading to starting that activity are delivered via its onNewIntent()

class Player extends Activity{
  public static final String ACTION_PLAY = "com....PLAY";
  public static final String ACTION_PAUSE = "com...PAUSE";

  public void onNewIntent(Intent intent){
    if(intent.getAction().equals(ACTION_PLAY)){
      //Play
    }
    else if(intent.getAction().equals(ACTION_PAUSE){
      //Pause
    }
  }
}

And from the calling activity, you could invoke

Intent playIntent = new Intent(this, Player.class);
playIntent.setAction(Player.ACTION_PLAY);

and

Intent pauseIntent = new Intent(this, Player.class);
pauseIntent.setAction(Player.ACTION_PAUSE);



回答2:


Either you can use static variable of MediaPlayer in your activity, so that you can access your media player by using YourActivityName.mediaplayer.stop()
or
use a service class
I prefer service class



来源:https://stackoverflow.com/questions/8875094/how-to-change-the-media-player-from-a-different-activity

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