如何从不同的活动改变媒体播放器媒体播放器、不同

2023-09-07 11:24:39 作者:墨雨汐

我在想,如果我能在一个活动声明一个媒体播放器变量,然后暂停或在一个单独的活动停止。我怎么会去这样或有另一种方式?谢谢

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

推荐答案

我不是静态的VAR的粉丝。我想preFER做这样的事情。

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

Android清单

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

这前确保您有活动的运行只有一个实例,而导致启动该活动所有的意图都通过交付了 onNewIntent()

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

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