Quit app when pressed home button in android - android

I have an application which has background music in it. When I am pressing the home button, the background music is still playing. After that when I am clicking the recent apps button, to the right of the home button, and closing the app by swiping or pressing X, it is restarting as if the application is started again instead of closing the currently playing music. How do I solve this problem?
Where do I add the onTaskRemoved() method?
package com.example.dmacs.myapplication;
/**
* Created by dmacs on 4/8/16.
*/
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import java.util.Random;
/**
* Created by digen on 3/8/16.
*/
public class BackgroundAudioService extends Service implements MediaPlayer.OnCompletionListener {
MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
int mfile[] = new int[5];
mfile[0]= R.raw.bgm1;
mfile[1]= R.raw.bgm2;
mfile[2]= R.raw.bgm3;
mfile[3]= R.raw.bgm4;
mfile[4]= R.raw.bgm5;
Random random = new Random();
int Low = 0;
int High = mfile.length;
int randomInt = random.nextInt(High-Low) + Low;
mediaPlayer = MediaPlayer.create(this, mfile[randomInt]);// raw/s.mp3
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand (Intent intent,int flags, int startId){
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}

Clicking the Home button obviously won't stop a Service running in the background and swiping the app out of Recents won't work either, the OS will restart the Service because of START_STICKY returned from onStartCommand().
You just have to stop the Service when appropriate (in onPause(), for example) by calling stopService().
To stop your Service when your app is getting swiped out of Recents, you could just override onTaskRemoved() and call stopSelf() from there:
#Override
public void onTaskRemoved(Intent rootIntent) {
stopSelf();
}

Related

Making WebView audio play in background

I am making an android app for my website. It has some videos which are somewhat like podcasts. I want the app to be able to play the audio in the background when the user either locks the screen or is using other applications. To achieve this, I have a WebView in place. To provide the above mentioned functionality, I tried to use a PARTIAL_WAKE_LOCK in the activity. This only continues to play the audio when the screen is locked, but not when the home button is pressed (ie. in the background). Is there a workaround for this issue?
If You want your app to keep running the Audio even if it is in Background, You have to run the Mediaplayer in a Separate Service.
This service will keep on Running even the app goes to background or comes back.
You can even write a sticky service to keep running(with foreground as true) if the app gets killed.
You should use android service to play the music independent of your activity.Please look at this example:
Here is my Android Service class:
class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this, R.raw.s);// raw/s.mp3
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
Here is Activity:
public class MusicActivity extends Activity implements OnClickListener {
Button startPlaybackButton, stopPlaybackButton;
Intent playbackServiceIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
playbackServiceIntent = new Intent(this,MusicService.class);
}
public void onClick(View v) {
if (v == startPlaybackButton) {
startService(playbackServiceIntent);
finish();
} else if (v == stopPlaybackButton) {
stopService(playbackServiceIntent);
finish();
}
}
}
Please do not forget to add the service in your manifest file :
<service android:enabled="true" android:name=".services.MusicService" />

How to pause the service when the home button is pressed and resume the service when the program is resume?

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.

Controlling Background Music android

I am using a Service to play background Music. The problem is that the music continues playing when i have finished the activity. when i press home button the music stop i want to make music continue playing while application is use and stop when home button press help me please. can some tell me how to do this
private static final String TAG = null;
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
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) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
You should use a service and play the music.
http://developer.android.com/guide/components/services.html
Service runs in the background so even when you switch activities it still runs and you can play your music there.
You can start a service and then stop it when you need. Also you can bind the service to the activity. Look at the docs in the above link for more info.
Example :
https://thenewcircle.com/s/post/60/servicesdemo_using_android_services
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
// song is res/raw/yourmusicfile.mp3
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
Now just start the service and you can stop the service when you need. You can switch between activities and the service still runs playing the music.
Since the code i huge i uploaded to DropBox. Here's the sample i made
https://www.dropbox.com/s/fjc4krpcwsg7qm6/ServicesDemo.zip

Trying to make a pause/resume music activity using service

I'm trying to create an activity with one button in its layout which will pause or resume the music when it's pressed. the problem is that when it's pressed to resume the music it starts the audio file all over again. Any idea how to make it play from the last point it stopped rather than restarting it?
Main activity
public class MainActivity extends Activity implements OnClickListener {
private Boolean isMusicPlaying;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View musicButton = findViewById(R.id.music_button);
musicButton.setOnClickListener(this);
startService(new Intent(getBaseContext(), MusicService.class));
isMusicPlaying = true;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.music_button)
if (isMusicPlaying) stopService(new Intent(getBaseContext(),
MusicService.class));
else startService(new Intent(getBaseContext(), MusicService.class));
isMusicPlaying = !isMusicPlaying;
}
}
Service class
public class MusicService extends Service {
MediaPlayer player;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.song);
player.setLooping(true); // Set looping
player.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
player.pause();
}
}
It seems like MediaPlayer object in your service is not kept when you stop the service.
You can get the current position of your song using getCurrentPosition() method before you stop your service,
player.pause();
currentPos = player.getCurrentPosition();
and send this value back to activity before it is stopped.
Then, you can use seekTo(int) method to move to specified time position before playing.
player.seekTo(currentPos);
player.start();
For communication between your service and activity, you might register broadcastreceiver and communicate using intent or use a bound service.
UPDATE:
I found following tutorial and you'd better to follow this. It's about using a service with MediaPlayer.
Especially, you are not using prepare method at all when you initialize your MediaPlayer. put these lines:
player.setOnPreparedListener(this);
player.prepareAsync();
and add listener:
public void onPrepared(MediaPlayer player) {
player.start();
}
http://developer.android.com/guide/topics/media/mediaplayer.html#mpandservices
Seeing that the activity is re-started why don't you save the states to Shared Preferences

How to play streamed audio in background on Android?

I have an Android application that plays streamed audio from the Internet using the MediaPlayer class.
How do I let it continue to play the audio on the background when the
user hits the home button to run other applications?
While running other apps, I'd like it to continue to play the audio.
You have to use something called Android Services.
From the docs:
"A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use."
Here's the excellent official guide to using services to get you started:
http://developer.android.com/guide/components/services.html
Here's a good tutorial on building an audio player:
http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/
Here's a video tutorial for building a streaming music player:
http://www.youtube.com/watch?v=LKL-efbiIAM
You'll need to implement a Service in order to play media in the background without it being tied to the Activity that started playback. Have a look at this example.
The key is define Service.START_STICKY to continue playing in background:
public int onStartCommand(Intent intent, int flags, int startId) {
myMediaPlayer.start();
return Service.START_STICKY;
}
Service.START_STICKY : if this service's process is killed while it is
started the system will try to re-create the service.
This is an example of to do this:
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by jorgesys.
*/
/* Add declaration of this service into the AndroidManifest.xml inside application tag*/
public class BackgroundSoundService extends Service {
private static final String TAG = "BackgroundSoundService";
MediaPlayer player;
public IBinder onBind(Intent arg0) {
Log.i(TAG, "onBind()" );
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.jorgesys_song);
player.setLooping(true); // Set looping
player.setVolume(100,100);
Toast.makeText(this, "Service started...", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onCreate() , service started...");
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return Service.START_STICKY;
}
public IBinder onUnBind(Intent arg0) {
Log.i(TAG, "onUnBind()");
return null;
}
public void onStop() {
Log.i(TAG, "onStop()");
}
public void onPause() {
Log.i(TAG, "onPause()");
}
#Override
public void onDestroy() {
player.stop();
player.release();
Toast.makeText(this, "Service stopped...", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onCreate() , service stopped...");
}
#Override
public void onLowMemory() {
Log.i(TAG, "onLowMemory()");
}
}
Start service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);
Stop service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);
Complete code of this example.

Categories

Resources