How to turn off music bgm(Background Music) from other java - java

I am making an app where bgm start from main page. But I couldn't find a way to turn it off when starts learning.
Can I remotely switch off bgm from different java file
This is my 1st java,mainmenu.class
public class mainmenu extends AppCompatActivity {
MediaPlayer bkgrdmsc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
Button btn = (Button) findViewById(R.id.mula);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_belajar_latihan = new Intent(getApplicationContext(), taqi.mengaji.belajar_latihan.class);
startActivity(ke_belajar_latihan);
}
});
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
bkgrdmsc.start();
}
}
This is the other file I want to remotely off the bgm when starting the learning session(as student start to learn)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.belajar_hija_baris);
Button btn=(Button) findViewById(R.id.hijaiyyah);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ke_hijaiyah=new Intent(getApplicationContext(),taqi.mengaji.hijaiyyah.class);
startActivity(ke_hijaiyah);
}
});
}
I want R.id.hijaiyyah to navigate to learn xml also stop bgm
Please help I'm a newbie XD

Make an singleton class and add you music playing code into it for stopping and starting and use that singleton class in all your 2 activities for eg:
public class MusicManager {
private static MusicManager refrence = null;
public static MusicManager getInstance(){
if(refrence == null){
refrence = new MusicManager ();
}
return refrence;
}
}
Add a public method to this singleton class to start and stop music
public void initalizeMediaPlayer(Context context, int musicId){
// add initalization of media player in it and loop it
MediaPlayer bkgrdmsc;
bkgrdmsc = MediaPlayer.create(this, R.raw.song);
bkgrdmsc.setLooping(true);
}
public void startPlaying(){
bkgrdmsc.start();
}
public void stopPlaying(){
bkgrdmsc.stop();
}
//Add stuff like pausing and resuming if you desire
To use this class add this to any activity you want to play music:
MusicManager.getInstance().initalizeMediaPlayer(this, R.raw.menu); // to initalize of media player
MusicManager.getInstance().startPlaying();// to start playing music
MusicManager.getInstance().stopPlaying(); // to stop playing music
You can also use service to perform this task as service runs in background. You can start and stop service any time in your code.

Related

Android Studio Soundboard buttons won't play sound after switching activity i can press them only like 7 times before they stop

In Android studios i made Soundboard in which i have 4 activities when i'm on first activity i can press sounds all day and they play but right after i click next for second activity when i try to play them they won't play sound. I can click like 7 times and they stop.
I look everywhere but nothing works i even changed whole code again still same thing happens.
Button button1;
Button theuniverserequired, iusedthestones, etc more sounds....
iaminevitable = (Button) findViewById(R.id.iaminevitable);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.iaminevitable);
iaminevitable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
iusedthestones = (Button) findViewById(R.id.iusedthestones);
final MediaPlayer mp2 = MediaPlayer.create(this,
R.raw.iusedthestones);
iusedthestones.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp2.start();
}
}); etc....
button1 = findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent int1 = new Intent(MainActivity.this, Activity2.class);
startActivity(int1);
}
});
there is nothing in error messages for why is this happening
First off: Declare your MPs outside your onCreate to prevent it from garbage collected when activity is paused
private MediaPlayer mp,mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mp = new MediaPlayer.create(...
mp2 = new MediaPlayer.create(...
Further more: Drop off resources used by MPs when activity stops to avoid memory leaks which may force your app to crash on continuous usage.
#Override
protected void onStop() {
super.onStop();
if (mp != null) {
mp.reset();
mp.release();
mp = null;
}
if (mp2 != null) {
mp2.reset();
mp2.release();
mp2 = null;
}
}

Popup with call email and sms function

I am a beginner in android app development.. i have made an app now and there is a pop up in it which shows a persons name and details.. i have added 3 buttons there like CALL,SMS,EMAIL.. i went for call activity, but its not working. no error is there still call button is not making calls.. The same code i have tried in a new project, there it works well.. but when i do it on that popup, call is not working... please help me
public class popupinv extends AppCompatActivity {
public Button b;
public void init(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_popupinv);
init();
b= (Button) findViewById(R.id.call);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent=new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123456));
startActivity(callIntent);
}
});
}
}

calling a method after starting an activity

I'm making an Android whack a mole game. I have the main activity which is basically the launcher, when you press the Play button the game activity starts. This works fine as it shows the background image and all molehills but I don't know how to call the method to start the game.
I've tried to call it from inside onCreate() but this ends up "playing the game" itself.
I've tried to call it right after the startActivity(intent) but the app crashes. And also I've tried to create an instance of the game class and call the play() method after the start activity but it doesn't work aswell. I don't know how to start the game method once the game activity is loaded.
I hope I explained well, thank you.
public class MainActivity extends AppCompatActivity {
ImageButton btnStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide TitleBar
try { this.getSupportActionBar().hide();}
catch (NullPointerException e){}
setContentView(R.layout.activity_main);
btnStart = (ImageButton)findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), GameView.class);
startActivity(intent);
}
});
}
And this is the code for the game_activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide TitleBar
try { this.getSupportActionBar().hide();}
catch (NullPointerException e){}
setContentView(R.layout.activity_game_view);
game();
}
The game() method is a typical game loop.
public void game() {
Random random = new Random();
int index;
/*
* Casting array to store all ImageView on the game
*/
imgViewArray[0] = (ImageView)findViewById(R.id.img1);
imgViewArray[1] = (ImageView)findViewById(R.id.img2);
imgViewArray[2] = (ImageView)findViewById(R.id.img3);
imgViewArray[3] = (ImageView)findViewById(R.id.img4);
imgViewArray[4] = (ImageView)findViewById(R.id.img5);
imgViewArray[5] = (ImageView)findViewById(R.id.img6);
imgViewArray[6] = (ImageView)findViewById(R.id.img7);
imgViewArray[7] = (ImageView)findViewById(R.id.img8);
imgViewArray[8] = (ImageView)findViewById(R.id.img9);
imgViewArray[9] = (ImageView)findViewById(R.id.img10);
int j=0;
while (j < 10) {
// Get a random image to animate
index = random.nextInt(10);
switch(index) {
case 0: imgViewArray[0].setImageResource(images[6]);
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
imgViewArray[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgViewArray[0].setImageResource(images[0]);
}
});
}
},
300 // The code executes after 300ms
);
break;
I think you should put the game() call inside onResume().
There are many ways to solve the problem:
Using EventBus
Send the start game Event from Main Activity and register for the Event in the Game activity.
This is my favorite way to handle the problem. It's because the simplicity and prevent us from tightly coupled code. The major problem with using EventBus is we will lost in the sea of Event if there are too much Event in the the app.
How to do:
First, create the Event. This is just a simple class:
public class StartGameEvent {
}
Second, register for the event in the game activity:
public class GameActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
EventBus.getDefault().register(this);
}
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
}
Third, subscribe for the event:
public class GameActivity extends Activity {
...
#Subscribe
public void onMessageEvent(StartGameEvent event) {
game();
}
}
Last, send the event from Main activity:
EventBus.getDefault().post(new StartGameEvent());
Using LocalBroadcastManager
You need to create the message and broadcast it in from your Main activity:
Intent intent = new Intent("playEvent");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
Then, in the game activity, you need to register as receiver:
#Override
public void onCreate(Bundle savedInstanceState) {
// register for the event
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
new IntentFilter("playEvent"));
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
game();
}
};
#Override
protected void onDestroy() {
// Unregister here
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(mReceiver);
super.onDestroy();
}
I slightly modifying the code from How to use LocalBroadcastManager? for your case.
Using a static method in Game activity
This is the simplest way but highly discouraged. Because we can't ensure the state of the activity. Do not use this in production code. This is for learning sake only.
You can make the game() method as a static method like this:
public class GameActivity extends Activity {
...
public static void game() {
// game logic.
}
}
Then call the method when you want with:
GameActivity.game();

How to stop a MediaPlayer using a button

The code I have so far is:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void SoundPlayer(View view) {
MediaPlayer soundMediaPlayer1 = MediaPlayer.create(this, R.raw.gun_sound);
soundMediaPlayer1.start();
}
public void DogSound(View view) {
MediaPlayer soundMediaPlayer2 = MediaPlayer.create(this, R.raw.cat_sound);
soundMediaPlayer2.start();
}
public void NewSound(View view) {
MediaPlayer soundMediaPlayer3 = MediaPlayer.create(this, R.raw.new_sound);
soundMediaPlayer3.start();
}
public void LaughTrack(View view) {
MediaPlayer soundMediaPlayer12 = MediaPlayer.create(this, R.raw.laugh_sound);
soundMediaPlayer12.start();
}
public void HorseSound(View view) {
MediaPlayer soundMediaPlayer4 = MediaPlayer.create(this, R.raw.horse_sound);
soundMediaPlayer4.start();
}
public void HeySound(View view) {
MediaPlayer soundMediaPlayer5 = MediaPlayer.create(this, R.raw.hey_sound);
soundMediaPlayer5.start();
}
private void Stop() {
startActivity(new Intent(this, MainActivity.class));
}
public void stop(View view) {
Stop();
}
}
The problem I face is that all the sounds overlaps and plays. I have a STOP button set up, but have no idea has to how to make it stops the media. Any feedback is helpful.
Thank you.
First of all, I would use only one Instance of the MediaPlayer. You can then use mediaPlayer.stop() to stop a sound and prepare the next one.
See the state diagram on https://developer.android.com/reference/android/media/MediaPlayer.html
1) Make the object of MediaPlayer in onCreate method don't create in every new method.
2) Before playing the music in another method first use stop() function to stop current playing sound(like mediaPlayer.stop(); ) then play the sound by start().

Android MediaPlayer start called in State 1. Error -38,0

Good day! As usual - I am starting to learn Android programming and have faced unexpected difficulty while trying to create basic MediaPlayer app. Audio file is stored in res/raw. It is accessed with create(). I have read a few manuals on how to build a media player app and was convinced that using prepare() and prepareAsync() was not necessary in case if file is stored in res/raw folder. So here is my initial code
private MediaPlayer playerM = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button playButton = (Button) findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playMusic(R.raw.sleep_away);
}
});
Button stopButton = (Button) findViewById(R.id.pauseButton);
stopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopMusic();
}
});
}
private void playMusic(int rid) {
playerM.create(this, rid);
playerM.start();
}
private void stopMusic() {
playerM.stop();
}
}
Since that I have made numerous changes, but nothing helped. According to dev.android manual on MediaPlayer the code above should work. However it results in the following errors:
E/MediaPlayer: start called in state 1, mPlayer(0x0)
E/MediaPlayer: error (-38, 0)
E/MediaPlayer: Error (-38,0)
Probably I am just making some blunt mistake. Any help would be much appreciated.
Solved by myself
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
Uri myUri = Uri.parse("android.resource://" + v.getContext().getPackageName() + "/" + R.raw.sleep_away);
System.out.println(myUri);
playerM.setDataSource(v.getContext(), myUri);
playerM.prepare();
playerM.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer playerM){
playerM.start();
}
});
}catch(IOException e){
e.printStackTrace();
}
}
});
I know I should add other methods to change State, but the main purpose was to get it to play file.

Categories