Search code examples
androidandroid-studioandroid-activitysingletonandroid-music-player

Can I make one function for all activity, to play, pause music


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?


Solution

  • I can see two options:

    1. Make MediaPlayer static object.
    2. Consider implementing Single Activity approach. You will have two fragments and shared ViewModel in which you can access MediaPlayer.