First Activity
package com.example.birthdaywish;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void wishButton(View view) {
final EditText editText = findViewById(R.id.editTextTextPersonName);
String name = editText.getText().toString();
Intent intent = new Intent(this, screen2.class);
intent.putExtra("name", name);
startActivity(intent);
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.happy_birthday_song);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
}
}
Above is my first activity. In which i have played music on button click at the same time button click will also open second activity.
Second Activity
package com.example.birthdaywish;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.w3c.dom.Text;
public class screen2 extends AppCompatActivity {
@SuppressLint("SetTextI18n")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen2);
TextView enteredName = findViewById(R.id.textView2);
String name = getIntent().getStringExtra("name");
enteredName.setText("Happy Birthday " +name);
}
public void displayMessage(View view) {
}
}
Now when the display message button is pressed, I want to stop the music that is played in first activity. Or can I do it in any other way like, creating a common function for Musicplayer having start and stop method and I can call them whenever I want to start or stop music in any activity?
2
Answers
I can see two options:
MediaPlayer
static object.ViewModel
in which you can accessMediaPlayer
.Make a Utils class in which you will create the Global method for playing & pausing the Music player.
In that Utils class:
Use this method whenever you want to play the media like this:
Now, if you want to implement Global pause, resume & stop functionality, then use this (create these methods in the same Utils class)
Use these methods wherever you want in your app just by calling them like the first method.
NOTE : The difference here between
pause()
&stop()
is that you have to prepare the mediaplayer again if you usestop()
, whereaspause()
doesn’t require it.