简体   繁体   中英

How to change the media player from a different activity

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM