In My Application im using following code to play audio file
Uri data = Uri.parse("file:/" + songnameandpath);
intent.setDataAndType(data, "audio/*");
PackageManager packageManager = getActivity()
.getPackageManager();
List<ResolveInfo> activities = packageManager
.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
if (isIntentSafe) {
startActivity(intent);
so now when user clicks on back button audio get stopped what if i want to play audio even if the user presses back button on activity and moreover it has to play in background exactly how audio will in mobiles.
Sample code will helps me a lot.
Thanks in advance
Have you tried working with media player?
here is the code that worked for me, just delete the on pause/destroy methods or redefine them and you will have sound playing even when the user presses back..
public class MainActivity extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp= MediaPlayer.create (this, R.raw.sound); // sound is for example your mp3 song
mp.start ();
}
protected void onDestroy() {
super.onDestroy();
mp.release();
}
protected void onPause() {
super.onPause();
mp.pause();
}
protected void onResume() {
super.onResume();
mp.start();
}
protected void onStart() {
super.onStart();
}
}
update
The MediaPlayer will continue playing file even after the activity is finished unless you explicitly stop it by stop function
Related
I'm developing an Android App in Android Studio and in that a sound has to play on the WebView. But when I close the app, it automatically stops playing the audio. Now I want to know how do I make the audio to play in the background even if I close the app. (Kindly provide the code, I'm new to android development.) Thanks in advance.
I am sorry, I think it's impossible.
To play a sound in background, you need to play the audio in Service.
It's only one way to play background sound.
I will show a code for that:
public class serv extends Service{
MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
mp = MediaPlayer.create(this, R.raw.b);
mp.setLooping(false);
}
public void onDestroy()
{
mp.stop();
}
public void onStart(Intent intent,int startid){
Log.d(tag, "On start");
mp.start();
}
}
Maybe the title isn't explicit enough, let me explain.
I am working on an already existing code, Java for Android app. The actual app have a mediaplayer playing audio stream, with only a play/pause button in the layout.
The played is initialized and used in an activity.
When the phone is locked, the stream continues to play but there is no notification displayed with the next previous etc buttons.
Using this tutorial i managed to dispay the notification on lock screen and on notification area when i call this service from the activity:
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PAUSE);
startService(intent);
But it's obviously not working well as the already existing session is not linked to the new created controller on the notification.
So i'm wondering if it's better to:
Use the new service i created and try to link it to existing session
Dish the previous mediaplayer from the activity and handle all the media things in service
Keep all the media handling in the activity
I'm not very familiar with Medias handling in Android.
Here is some preview of the actual code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exercices);
setFinishOnTouchOutside(false);
mContext = this;
// Init of MediaSession
//mSession = new MediaSessionCompat(this, "MusicService");
//mSession.setCallback(new MediaSessionCallback());
//mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
//setSessionToken(mSession.getSessionToken());
mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mRemoteControlResponder = new ComponentName(getPackageName(),
RemoteControlReceiver.class.getName());
mStateBuilder = new PlaybackStateCompat.Builder()
.setActions(
PlaybackStateCompat.ACTION_PLAY |
PlaybackStateCompat.ACTION_PLAY_PAUSE);
initializeViews();
initializeActions();
}
public void initializeActions() {
recyclerExercisesView.setLayoutManager(new LinearLayoutManager(mContext));
pAdapterExercise = new ExercisesPlayerAdapter(mContext, allExercisesList, isGuest, new ExercisesPlayerAdapter.RecyclerItemClickListener() {
#Override
public void onClickListener(Exercise exercice, int position) {
//Toast.makeText(DetailsSceanceActivity.this, exercice.getPath(), Toast.LENGTH_SHORT).show();
iv_play.setEnabled(true);
seekBar_progress.setEnabled(true);
if (!chronoLaunch && firstLaunch) {
startChrono();
startSensors();
}
firstLaunch = false;
changeSelectedExercice(position);
prepareExercise(exercice);
}
});
recyclerExercisesView.setAdapter(pAdapterExercise);
mMediaController = new MediaController(this);
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PAUSE);
startService(intent);
// inint mediaplayer
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// play song
togglePlay(mp);
//mMediaController.setMediaPlayer(this);
}
});
}
I also saw few samples with MediaSessionCompat. Better use MediaSession or MediaSessionCompat?
Thanks
I have a bound service that I want to stop through a notification click.
In my main_activity I do this onDestroy to unbind my service:
public void onDestroy(){
super.onDestroy();
if(mediaPlayerBound){
System.out.println(mediaPlayerBound);
unbindService(mServCon);
mMediaPlayerServiceBound = false;
}
This part works fine as I get that mediaPlayerBound is true and so the service is getting unbound.
Then in my service:
I call the following after receiving a broadcast.
stopForeground(true);
stopSelf();
Lastly:
in OnDestroy within the service I use:
public void onDestroy(){
this.unregisterReceiver(nextBroadCast);
System.out.println("Stopped Service");
}
Now my question is, I started playing a song with the mediaPlayer but it persists even after I have gotten confirmation that that the service has reached onDestroy. What do I do to stop it from playing as soon as I call stopSelf(); ?
In service I read it somewhere that you will not always watch onDestroyed has been called. There are many terms and condition. but as you said you are receiving this event then try the below code. but I am guessing you are able to get your media player instance in it. so here is a workaround
#Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(nextBroadCast);
yourMediaPlayer= MediaPlayer.create(x.this,R.raw.sound);
if(yourMediaPlayer.isPlaying())
{
yourMediaPlayer.stop();
yourMediaPlayer.release();
}
}
add this code in your service file . onTaskRemoved is call when your app is closing.so it stop service
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
if(player.isPlaying())
{
player.stop();
}
player.release();
stopSelf();
}
#Override
public void onDestroy() {
if(player.isPlaying())
{
player.stop();
}
player.release();
stopSelf();
}
And in Your Activity place code when you want stop runing service .
Intent i=new Intent(this, MediaSongServiece.class);
stopService(i);
A short note is that if you used MediaPlayer to play music, you would stop MediaPlayer.
Put this source in Destroy().
private void stopPlay() {
this.unregisterReceiver(nextBroadCast);
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
This question has been asked a few times, but none of the answers have helped me solve my problem so I'm posting my version of it.
I'm creating an app that plays a list of songs through a service. The problem is that I got a null exception error from the mediaPlayer after I rotate the device. As you can see below, I first start and then bind to my service in the onResume method. Likewise, I unbind and stop the service in the onDestroy method.
protected void onResume() {
if (playIntent == null) {
playIntent = new Intent(MainActivity.this, MediaService.class);
// if (n < 0) {
startService(playIntent);
bindService(playIntent, mediaConnection, Context.BIND_AUTO_CREATE);
Log.d("Check", "Started Service");
// }
}
super.onResume();
}
In my service, I set up the mediaPlayer in the service's onCreate method as below. I have a few things in the onStartCommand method (like creating a notification to show in the action bar). I also return Start_sticky in onStartCommand method.
Unfortunately, like I said, when I rotate the device, I get a null exception from the mediaPlayer.
Please help; I've been trying to fix this for days.
static private MediaPlayer player;
private final IBinder musicBind = new MediaBinder();
Notification notification;
private int playbackDuration;
static Uri paths[][] = new Uri[MainActivity.NUMBER_OF_ARTISTS][MainActivity.NUMBER_OF_TRACKS];
public void onCreate() {
// create the service
super.onCreate();
player = new MediaPlayer();
player.reset();
player.setLooping(true);
initMediaPlayer();
Log.d("Check", "In Service's OnCreate method");
I am working on a music player
The logic is like this:
First, I click on the play button , if there is music playing, stop the service , otherwise , start it.
Play / Pause Button:
playM.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AudioManager manager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);
if (!manager.isMusicActive()) {
playM.setText("Pause");
Intent svc=new Intent(getContext(), Music.class);
svc.putExtra("uri", tt1.getText().toString());
getContext().startService(svc);
} else {
playM.setText("Play");
//if (mPlayer != null && mPlayer.isPlaying()) {
Intent svc=new Intent(getContext(), Music.class);
getContext().stopService(svc);
//}
}
}
});
Service:
public int onStartCommand(Intent intent, int flags, int startId) {
path = (String) intent.getExtras().get("uri");
Uri uriMusic = Uri.parse(path);
player = MediaPlayer.create(this, uriMusic);
player.start();
player.setLooping(true); // Set looping
return 1;
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
The problem is, if the music is playing by another apps, my music player will crash. But I can not find any way to track the service status. For example, if I play the music, close the app , the music is still playing , but when I open the app again , how to know the specific service (play music which is fire by my app only, in this case) is running? Thanks