How to change the media player from a different activity
-
28-10-2019 - |
Вопрос
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
Решение
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);
Другие советы
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
Не связан с StackOverflow