I am beginner at Android App I have new app which call html files from assets file one of the task on this app is when user selected check box input to value "on" the mp3 play and when user goout from app as press back button or press home button the sound stopped and close the app. I did my interface between html and main activity to call java methods at html. When I added my code to stop the sound it does not play . I tried to add this line of code in main activity oncreate method .
mp= MediaPlayer.create(mContext,R.raw.sound);
the sound stopped when press back or home or turnoff buttons . but the sound work when i open the app but this what i doesnot need i need this is when user select the checkbox . so how can i do it .
#Override
protected void onPause()
{
super.onPause();
if(mp.isPlaying())
mp.pause(); //stop the sound
}
#Override
protected void onResume()
{
super.onResume();
mp.start();
}
public class WebAppInterface {
Context mContext;
private MediaPlayer mp;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void playsound(String value ) {
if (value.equals("on")) {
mp= MediaPlayer.create(mContext,R.raw.sound);
mp.setLooping(true);
mp.start();
}
else
{ mp.stop();}
}
}
I am assuming the issue is that the sound plays regardless whether you have selected the checkbox or not. A way to fix this would be to confirm whether the checkbox is checked or not in the onResume() method, instead of just starting regardless.
public class WebAppInterface extends Ramadan {
Context mContext;
private MediaPlayer mp;
private static boolean checked = false;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void playsound(String value , MediaPlayer mp ) {
if (value.equals("on")) {
checked = true;
mp= MediaPlayer.create(mContext,R.raw.sound);
mp.setLooping(true);
mp.start();
}
else
{
checked = false;
mp.stop();
}
}
}
in your main class:
#Override
protected void onPause()
{
super.onPause();
if(mp.isPlaying())
mp.pause(); //stop the sound
}
#Override
protected void onResume()
{
super.onResume();
if(WebAppInterface.checked)
{
mp.start();
}
}
Related
hi i'm trying to create a simple Online Radio i want to keep radio playing in bakcground and i know i should use Service but i don't how to use it please help me to make my app radio keep playing in background
this my code :
Button b_play ;
MediaPlayer mediaPlayer ;
boolean prepared = false;
boolean started = false;
String stream = "http://stream.radio.co/s98f81d47e/listen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_play = (Button)findViewById(R.id.b_play);
b_play.setEnabled(false);
b_play.setText("Loading");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
b_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(started){
started = false;
mediaPlayer.pause();
b_play.setText("Play");
}else{
started = true;
mediaPlayer.start();
b_play.setText("Pause");
}
}
});
}
class PlayerTask extends AsyncTask<String, Void ,Boolean>{
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
b_play.setEnabled(true);
b_play.setText("Play");
}
}
#Override
protected void onPause() {
super.onPause();
if(started){
mediaPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if(started){
mediaPlayer.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(prepared){
mediaPlayer.release();
}
}
}
Play the music from the foreground service.
Official Android documentation says:
that is a service that the user is actively aware of and is not a
candidate for the system to kill when low on memory. A foreground
service must provide a notification for the status bar, which is
placed under the Ongoing heading. This means that the notification
cannot be dismissed unless the service is either stopped or removed
from the foreground.
In your case a radio that plays music from a service should be set to run in the foreground, because the user is explicitly aware of its operation. The notification in the status bar might indicate the current song and allow the user to launch an activity to interact with the music player.
Here is an example
I am creating a game, I want to play a background music for one activity only(For main menu of game), my code shown below, The problem is that the music plays more than one time, I want to play the same music also when activity Resumes.
public class Menu extends Activity {
MediaPlayer mp
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
public void play(View ButtonClicked) {
mp.stop();
mp.release();
//mp = MediaPlayer.create(Menu.this, R.raw.l);
//mp.start();
goToActivity(Game.class);
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//coins
coin.setText(data.getString("coin"));
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
//mps.release();
}
In your onResume don't initialise MediaPlayer again and again. It creates new instance every time when you come to onResume. So add a check in onResume like this :
#Override
protected void onResume() {
super.onResume();
if (mp==null)
mp=MediaPlayer.create(MainActivity.this,R.raw.adalante);
if (!mp.isPlaying())
mp.start();
}
and additionally add this for prevention to play when activity goes to onPause
#Override
protected void onPause() {
super.onPause();
mp.pause();
}
i'am trying to develop an app in android with 2 buttons. the first button must pause and restart the music if you state is on or off. but this code doesn't works, why?
public class MainActivity extends Activity {
MediaPlayer sound;
Boolean pulsado=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
sound=MediaPlayer.create(getBaseContext(),R.raw.gaitas);
sound.setLooping(true);
sound.start();
}
public void boton1(View v){
if(pulsado==false){
sound.stop();
pulsado=true;
}else{
sound.reset();
}
}
public void boton2(View v){
Intent i=new Intent(this,ActivityB.class);
startActivity(i);
}
Android documentation says about MediaPlayer.reset() -- Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
For your purpose, you could use MediaPlayer.create(...) again to setDataSource to the MP and prepare it for playing.
if (pulsado == false) {
sound.stop();
sound.reset();
pulsado = true;
} else {
sound = MediaPlayer.create(getBaseContext(), R.raw.song);
sound.setLooping(true);
sound.start();
pulsado = false;
}
If you are looking for pausing the song, you could rather call sound.pause() and in else block simple sound.start() should be enough to resume the song.
I start mediaplayer like this:
if (mp != null) {
mp.stop();
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, R.raw.background);
mp.start();
How can I stop in another activity? It continues to play in another activity. How can I use onDestroy in another activity?
Use the Separate class like below in your project.
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
public class AudioPlay {
public static MediaPlayer mediaPlayer;
private static SoundPool soundPool;
public static boolean isplayingAudio=false;
public static void playAudio(Context c,int id){
mediaPlayer = MediaPlayer.create(c,id);
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
if(!mediaPlayer.isPlaying())
{
isplayingAudio=true;
mediaPlayer.start();
}
}
public static void stopAudio(){
isplayingAudio=false;
mediaPlayer.stop();
}
}
Playing the song
`AudioPlay.playAudio(mContext, R.raw.audiofile);` // play it from your preferred activity. and you can change raw file to your path also its depends upon your requirement.
then
stop the audio using this lines AudioPlay.stopAudio(); from any activity.
hope this helps.
In 1st activity override onPause
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mp.stop();
}
This is my Kotlin solution:
package com.programacionymas.myapp.services
import android.content.Context
import android.media.MediaPlayer
object AudioPlay {
var mediaPlayer: MediaPlayer? = null
var lastResource: Int? = null
fun playAudio(c: Context, id: Int, isLooping: Boolean = true) {
createMediaPlayer(c, id)
mediaPlayer?.let {
it.isLooping = isLooping
if (!it.isPlaying) {
it.start()
}
}
}
private fun createMediaPlayer(c: Context, id: Int) {
// in case it's already playing something
mediaPlayer?.stop()
mediaPlayer = MediaPlayer.create(c, id)
lastResource = id
}
// usually used inside the Activity's onResume method
fun continuePlaying(c: Context, specificResource: Int? = null) {
specificResource?.let {
if (lastResource != specificResource) {
createMediaPlayer(c, specificResource)
}
}
mediaPlayer?.let {
if (!it.isPlaying) {
it.start()
}
}
}
fun pauseAudio() {
mediaPlayer?.pause()
}
}
I started from itsrajesh4uguys's Java answer, and I applied these changes:
Remove the Boolean attribute, since it was not being used
Add an attribute to track the last loaded resource, this way I can continue playing it or replace with other resource
Call the stop function before creating a new instance, to avoid overlapping
Finally I use it this way:
In the onCreate method:
AudioPlay.playAudio(this, R.raw.background_music)
In the onResume method:
AudioPlay.continuePlaying(this, R.raw.background_music)
In my case I had to specify the resource, because some of my Activities start playing another music sounds.
you cannot call stop an activity but from the activity itself to
achive this you can send the media player in a service and bind to the service in the activities you want to access it
As you have started media player in first activity and wanted to stop in another activity, just call your second layout in first activity using layout inflater self instead of creating another activity.. and on second layout file just stop the media player by pressing a button
public class FirstAvtivity extends Activity
{
MediaPlayer mPlayer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity_layoutfile);
Button b=(Button)findViewById(R.id.button1);
//start the media player like how you were starting in your activity
// then after clicking button you will be navigated to new layout , there
// you can stop media player
mPlayer.start();
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateLayout();
}
});
}
private void newUpdateLayout() {
LayoutInflater inflater = LayoutInflater.from(this);
setContentView(inflater.inflate(R.layout.second_disapr_scr, null));
finalDismiss=(Button)findViewById(R.id.final_dismiss);
finalDismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(),"welcome to second
avtivity",Toast.LENGTH_SHORT).show();
mPlayer.stop();
finish();
}
});
}
}
I am new to android. i know that we can not access control of activity from service. But i want to change the ImageSource of the button whenever i call the method of the service.
here is the method that i created in service :
public void play()
{
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play); // not allowed
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause); // not allowed
}
}
}
in activity i am calling this method on play button click. How to implement this functionality in service. how can i change the image source of the button. Please clear my doubt. Thanx.
Create custom event object for those events and register your activity as listener.
Note: Don't forget to unregister it because it might cause a memory leak.
Try this code
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
public static MainActivity mThis;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mThis = this;
}
}
public void play()
{
Button btnPlay=((Button)MainActivity.mThis.findViewById(R.id.btnPlay));
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
}
} else {
// Resume song
if (mp != null) {
mp.start();
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
}
}