Hello guys, I'm an absolute beginner in Android development.
I'm just now creating a simple android application and I use a "BackgroundService" for the background music.
I manage to play music; my problem is that when I close my app or press the home button, the music doesn't stop.
Can you guys help me?
Here's my code:
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.sample);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
on the onPause method, add also
player.stop();
player.release();
hope this helps
You should really understand the concepts of a Service. Service is used for managing heavy tasks that runs in the background and don't require a UI. In simpler terms, Service is used to do heavy task in the background even if the activity is no longer visible.
Service will remain alive even if your activity is destroyed. You have to stop the Service manually. In the onPause() of your activity, try to stop the Service.
stopService(this, serviceClassName.class)
and in the onPause() of the Service you should stop and release the player
player.stop();
player.release();
See this link to learn more about Service and its life cycle. developers.android.com
Related
I am creating an app similar to other audio streaming apps. Is there a way to let a third party player stream music even though the screen of the mobile phone is locked or I am using other application?
You require to create the unbound service to play the media in background while other app may be opened or screen might be lock.
You can refer this for understanding in detail regarding use of services: https://developer.android.com/guide/components/services.html
Like this:
Create Intent first
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
Create class for the service to run in the background:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Do not forget to call service in manifest file
<service android:enabled="true" android:name=".BackgroundSoundService " />
Hope this helps you.
In my app there is a background music, for what I have a service. It works fine, but it "keeps playing" when either I close the app or turn off the screen.
Should I change something in onPause or onStop?
My code:
public class MyService extends Service {
private final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.id);
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
protected void onStop() {
player.pause();
}
public void onPause() {
player.pause();
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
As screen turns off your activity becomes invisible which triggers onPause followed by onStop
Screen on, on the other hand, triggers onStart followed by onResume.
when ever you want to stop service use
stopService(new Intent(ActivityName.this, ServiceClassName.class));
Probably copies of the player are created somehow. Try to make MediaPlayer variable static and then try to deallocate it after pausing onPause(). Anyway it is weird, that you are creating MediaPlayer instance in service.
I've got a service which plays background music in all of my activities, but doesn't turn off while onPause or onStop. I want my music to turn off while apps close or screen turn off, doesnt matter in which activity usesr currently is.
The problem is this:
I have a service. In every activity I coded what to do onPause and onStop. It works fine, but service also stops when I switch to another activity.
Code:
public class MyService extends Service {
private final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.id);
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
protected void onStop() {
player.pause();
}
public void onPause() {
player.pause();
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
You will have to stop the service in the onDestroy method of your main activity. Check this answer
public class BackgroundMusicService extends Service
{
int currentPos;
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
MediaPlayer player;
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.tornado);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player.seekTo(currentPos);
player.start();
return 1;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
#Override
public void onRebind(Intent intent) {
}
public void onPause()
{
player.pause();
}
#Override
public void onDestroy() {
player.stop();
currentPos = player.getCurrentPosition();
}
}
This is the service that play the background music, how to pause the service when the home button is pressed and resume the service when the program is resume? and here is my MainActivity:
public class MainActivity extends ActionBarActivity
{
int request_code = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getBaseContext(), BackgroundMusicService.class));
}
#Override
protected void onDestroy()
{
super.onDestroy();
stopService(new Intent(getBaseContext(), BackgroundMusicService.class));
}
}
I think need to use onPause() and onResume() function, but how to use it? and it should be use in service class or the activity class?
One more thing need to consider, I used multiple intent, and make sure that when I change to 2nd or others intents, the service is still running, means that changing intent will not stop playing the background music...unless home button is pressed or quit the program(this one I already done).
You have your onPause and onResume methods. You generally don't need to extend the Application class but instead use it in your Activity (esp if your app only has one Activity).
However, why start and stop the service? Why not just pause/unpause the music? You can send an intent to pause/unpause (or even toggle) the music playback.
I am developing an entertainment app in android. I want to play background music, and I want to use service for that. App have 3 activities and music must be played across all activities. Also, when activity is paused, music must PAUSE and stopped when destroyed. Can anyone tell me how to do this ? any links or examples ?
Thank you.
Do it without service
https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion
If you are so serious about doing it with services using mediaplayer
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Please call this service in Manifest
Make sure there is no space at the end of the .BackgroundSoundService string
<service android:enabled="true" android:name=".BackgroundSoundService" />
way too late for the party here but i will still add my $0.02, Google has released a free sample called universal music player with which you can learn to stream music across all android platforms(auto, watch,mobile,tv..) it uses service to play music in the background, do check it out very helpful. here's the link to the project
https://github.com/googlesamples/android-UniversalMusicPlayer
#Synxmax's answer is correct when using a Service and the MediaPlayer class, however you also need to declare the Service in the Manifest for this to work, like so:
<service
android:enabled="true"
android:name="com.package.name.BackgroundSoundService" />
i had problem to run it and i make some changes to run it with mp3 source. here is BackfrounSoundService.java file. consider that my mp3 file is in my sdcard in my phone .
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d("service", "onCreate");
player = new MediaPlayer();
try {
player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/your file.mp3");
} catch (IOException e) {
e.printStackTrace();
}
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("service", "onStartCommand");
try {
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Theres an excellent tutorial on this subject at HelloAndroid regarding this very subject. Infact it was the first hit i got on google. You should try googling before asking here, as it is good practice.
Create a foreground service with the START_STICKY flag.
#Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
if (startIntent != null) {
String action = startIntent.getAction();
String command = startIntent.getStringExtra(CMD_NAME);
if (ACTION_CMD.equals(action)) {
if (CMD_PAUSE.equals(command)) {
if (mPlayback != null && mPlayback.isPlaying()) {
handlePauseRequest();
}
} else if (CMD_PLAY.equals(command)) {
ArrayList<Track> queue = new ArrayList<>();
for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
queue.add((Track) Parcels.unwrap(input));
}
int index = startIntent.getIntExtra(ARG_INDEX, 0);
playWithQueue(queue, index);
}
}
}
return START_STICKY;
}
This can then be called from any activity to play some music
Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)
You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.
Here's a good tutorial about Playing music in the background on Android
I have found two great resources to share, if anyone else come across this thread via Google, this may help them ( 2018 ).
One is this video tutorial in which you'll see practically how service works, this is good for starters.
Link :- https://www.youtube.com/watch?v=p2ffzsCqrs8
Other is this website which will really help you with background audio player.
Link :- https://www.dev2qa.com/android-play-audio-file-in-background-service-example/
Good Luck :)