Stop background Service When application goes to background - android

I have background service in my android app,i start service from MainActivity onResume() method and it is work correctly.But how can i stop service when user press home button.Because currently when user press home button then application move to background and then user open some other app then after some time my service method is called and app force stop.Below is my code for start service -
Intent msgIntent = new Intent(mContext, MyBackgroundService.class);
startService(msgIntent);
Thanks in Advance.
EDITED
In My Service i use below code -
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
callWebservice();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, START_DELAY, DELAY);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
callAsynchronousTask();
return Service.START_NOT_STICKY;
}
#Override
public void onCreate() {
mContext = this;
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
if(timer!=null){
timer.cancel();
}
stopSelf();
}
in my activity i use below code for stop service -
#Override
protected void onStop() {
try{
stopService(new Intent(this, MyBackgroundService.class));
isServiceRunning = false;
}
catch(Exception e){
e.printStackTrace();
}
super.onStop();
}
#Override
protected void onPause() {
try{
stopService(new Intent(this, MyBackgroundService.class));
isServiceRunning = false;
}
catch(Exception e){
e.printStackTrace();
}
super.onPause();
}
but my service is run while i use some other app and it force stop app.From background service i call some webservice and then store response of service in database.

Stop the service in onPause() and onStop()
mContext.stopService(new Intent(mContext,
MyBackgroundService.class))

#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_HOME){
Log.e("home key pressed", "****");
// write your code here to stop the activity
enter code here
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onPause() {
Log.e("home key pressed on pause", "****");
// write your code here to stop your service
super.onPause();
}
the above code will keep check if user have pressed the home button or not.

when we open the other applications then our application(which was in background) gets cleared from the memory However the whole application does not removed but the some unwanted data and activities get finished.
In your case the activity which is to be updated gets cleared from the memory and your running background service when try to update the UI then it gets crashed by throwing NullPointerException.
So please saved the Reference of the activty(whose UI is to be updated) in onCreate() and set the reference to null in finish() method then check this reference in the background service if it is not null then update the UI otherwise no updation.
// Global Class for saving the reference
class GlobalReference{
public static <name_of_your_activity> activityRef;
}
in your activity
onCreate(){
GlobalReference.activityRef = this;
}
finish(){
GlobalReference.activityRef = null;
}
In your background service
if( GlobalReference.activityRef != null){
// update the UI of your activity
}
Hope this code will solve your issue.
Happy Coding...

press Home Button cause OnPause() function. Override onPause() and call stopService:
mContext.stopService(new Intent(mContext,
MyBackgroundService.class))

Related

If app crashes or closed from task manager then that time i want to hit api

I have created a service and called this service class from BaseActivity.
Intent serviceIntent = new Intent(this, UserAvailabilityService.class);
startService(serviceIntent);
public class UserAvailabilityService extends Service {
private static final String TAG = UserAvailabilityService.class.getSimpleName();
boolean isChecked = false;
boolean isUserAvailable = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
isChecked = getAvailableStatusFromFref();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand()");
return START_NOT_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(TAG, "onTaskRemoved()");
if(isChecked) {
//Hit a api
}
else
{
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
#Override
public void onLowMemory() {
super.onLowMemory();
Log.i(TAG, "onLowMemory()");
}
}
If app crashes or closed from task manager then that time i want to hit api.
Right Now, When i am swipping the app from background this onTaskRemoved method is calling. and i am hitting the api.
But when i am closing the same app from task manager (Setting->Apps->App name->Force Stop) then this onTaskRemoved method is not calling.
Any idea,please let me know.
Not possible. You cannot tell from within an app whether the app will be terminated. You could watch for termination from a second app, but at any time the first can be closed without notice. Not to mention the variety of ways that both apps could be shut down (for example, they could just pull the battery). You should never write code that requires you to do something on shutdown, because it will never be reliable.
The best you can do is calling isFinishing() which checks if it is being destroyed from you onPause() method
#Override
protected void onPause(){
super.onPause();
if(isFinishing){
callApi();
}
}

Service Automatic Called on Destroying Activity

I am stuck with the problem of Activity + Service in that I have following number of Activities and Services.
Activities:
LoginActivity => OrderListActivity => AddOrderActivity => ConfirmOrderActivity
Services:
ReceivingOrderService - Receiving New Data From Server
SendingOrderService - Sending new Data to Server
Above both Service Calling from another Separate Service on duration of some interval.
CheckAutoSyncReceivingOrder - To call ReceivingOrderService (Interval 15Mins)
CheckAutoSyncSendingOrder - To call SendingOrderService (Interval 3Mins)
CheckAutoSyncReceivingOrder:
public class CheckAutoSyncReceivingOrder extends Service {
Timer timer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
if(timer != null) {
timer.cancel();
Log.i(TAG, "RECEIVING OLD TIMER CANCELLED>>>");
}
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if(InternetConnection.checkConnection(getApplicationContext())) {
if(getDatabasePath(DatabaseHelper.DATABASE_NAME).exists())
startService(new Intent(CheckAutoSyncReceivingOrder.this, ReceivingOrderService.class));
} else {
Log.d(TAG, "Connection not available");
}
}
}, 0, 60000); // 1000*60*15 = 9,00,000 = 15 minutes
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(timer != null)
timer.cancel();
Log.d(TAG, "Stopping Receiving...");
}
}
CheckAutoSyncSendingOrder:
public class CheckAutoSyncSendingOrder extends Service {
Timer timer;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
if(timer != null) {
timer.cancel();
Log.i(TAG, "OLD TIMER CANCELLED>>>");
}
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Log.i(TAG, ">>>>>>>> SENDING AUTO SYNC SERVICE >>>>>>>>");
if(InternetConnection.checkConnection(getApplicationContext())) {
if(getDatabasePath(DatabaseHelper.DATABASE_NAME).exists())
startService(new Intent(CheckAutoSyncSendingOrder.this, SendingOrderService.class));
} else {
Log.d(TAG, "connection not available");
}
}
}, 0, 120000); // 1000*120*15 = 1,800,000 = 15 minutes
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if(timer != null)
timer.cancel();
Log.d(TAG, "Stopping Sending...");
}
}
ConfirmOrderActivity#Final Task which i have called for Insert Data:
new AsyncTask<Void, Void, Integer>() {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(
ConfirmOrderProductActivity.this);
progressDialog.setMessage("Inserting "
+ (isInquiry ? "Inquiry" : "Order") + "...");
progressDialog.setCancelable(false);
progressDialog
.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
#Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub
int account_id = context.getSharedPreferences(PREF_DATA,
MODE_APPEND).getInt(DATA_ACCOUNT_ID, 0);
/**
* Check Whether isInquiry or not...
*/
product_type = isWeight ? 1 : 0;
if (isInquiry) {
/*
* INSERTING DATA IN INQUIRY TABLE
*/
return m_inquiry_id;
} else {
/*
* INSERTING DATA IN ORDER TABLE
*/
return m_order_id;
}
}
#Override
protected void onPostExecute(Integer m_order_id) {
// TODO Auto-generated method stub
super.onPostExecute(m_order_id);
progressDialog.dismiss();
if (dbHelper.db.isOpen())
dbHelper.close();
String title = "Retry";
String message = "There is some problem, Go Back and Try Again";
AlertDialog.Builder alert = new AlertDialog.Builder(
ConfirmOrderProductActivity.this);
if (m_order_id != -1) {
title = isInquiry ? "New Inquiry" : "New Order";
message = isInquiry ? "Your Inquiry Send Successfully." : "Your Order Saved Successfully.";
alert.setIcon(R.drawable.success).setCancelable(false);
} else {
alert.setIcon(R.drawable.fail).setCancelable(false);
}
alert.setTitle(title).setMessage(message)
.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
startActivity(new Intent(
ConfirmOrderProductActivity.this,
FragmentChangeActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
/* Opening Left to Right Animation */
overridePendingTransition(R.anim.right_out,
R.anim.right_in);
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
}.execute();
Everything is working fine as per flow of inserting records in database.
After Adding Inquiry:
Destroying Activity and Getting following Logcat:
Main Problem:
When I placed order successfully from ConfirmOrderActivity, It is displaying AlertDialog of Success Message which is cancellable false. When I Stop application from this Activity, Its calling both CheckAutoSyncReceivingOrder and CheckAutoSyncSendingOrder automatically.
Edited:
I am calling both Service from LoginActivity only, after that it
will called automatically after given intervals But Problem occurs
when I destroy ConfirmOrderActivity when dialog is shown.
I didn't know why it happens that Why its running automatically when I stop Activity Directly.
I have tried onStartCommand() with START_NON_STICKY in Service but not working. (as START_STICKY is default.)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
Is there any solution?
You need to either run your service in the foreground so when the activity is destroyed so will the service or use a bound service and manage the binding with the activity lifecycle, so it is not continually restarted when the activity is destroyed.
From this android docs tutorial Bound Services
You need to do this for each service.
public class CheckAutoSyncReceivingOrder extends Service {
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
CheckAutoSyncReceivingOrder getService() {
return CheckAutoSyncReceivingOrder.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
From your activity that creates and calls the service, that when it is destroyed you want your service destroyed.
public class BindingActivity extends Activity {
CheckAutoSyncReceivingOr mService;
boolean mBound = false;
#Override
protected void onStart() {
super.onStart();
// Bind to CheckAutoSyncReceivingOr
Intent intent = new Intent(this, CheckAutoSyncReceivingOr.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to CheckAutoSyncReceivingOr, cast the IBinder and get CheckAutoSyncReceivingOr instance
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
And manage the service lifecycle. Restart the same service with your timer, do not create a new service.
public class ExampleService extends Service {
int mStartMode; // indicates how to behave if the service is killed
IBinder mBinder; // interface for clients that bind
boolean mAllowRebind; // indicates whether onRebind should be used
#Override
public void onCreate() {
// The service is being created
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
#Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
#Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
#Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
Note START_NOT_STICKY will only prevent the service from restarting if the device is low on memory.
Be mindful that you where you are starting services, just start it once and allow the service to maintain it's own lifecycle until you destroy it with your activity.
This is in reply to your original unedited question, when the app was mysteriously crashing:
You need to destroy the dialog before the context window the dialog is attached to. That will cause a problem. So this is where program flow and the order of closing and cleaning up resources is important. They, frequently have to be destroyed in the reverse order they were created if they are dependent upon parent windows (which is often in the form of a particular activity).
It's difficult to trace your code, so this is a generic answer.
Make use of onPause and onDestroy in your activities.
In all your activities, manage any resources you have created within that activity and with a null check, close them down. Like you have in your service class. If you want to override the parent onDestroy, place your custom code before super.onDestroy.
protected void onDestroy() {
if(timer != null)
timer.cancel();
Log.d(TAG, "Stopping Sending...");
super.onDestroy();
}
(1)For Your Dialog:
The solution is to call dismiss() on the Dialog you created before exiting the Activity, e.g. in onDestroy(). All Windows & Dialog should be closed before leaving an Activity.
(2)For Your service autostart:
you have to look at the value the service returns from its onStartCommand method. The default value is START_STICKY which will restart the service after it is destroyed. Take a look at the onStartCommand documentation for more details:
If the process that runs your service gets killed, the Android system will restart it automatically it is default behavior.
This behavior is defined by the return value of onStartCommand() in your Service implementation. The constant START_NOT_STICKY tells Android not to restart the service if it s running while the process is "killed".
You need to Override method onStartCommand() in your service class and move all your code from onStart() method to onStartCommand() method.
According to the Android Documentation:
For started services, there are two additional major modes of
operation they can decide to run in, depending on the value they
return from onStartCommand(): START_STICKY is used for services that
are explicitly started and stopped as needed, while START_NOT_STICKY
or START_REDELIVER_INTENT are used for services that should only
remain running while processing any commands sent to them
onStart() method calls each time when service is restarted but onStartCommand() method will not called if you return START_NON_STICKY.
Don't use onStart() anymore, it's deprecated.
I hope it helps you.
Services got killed when application got killed (add logs in service onStartCommand() and onDestroy() function and try clearing app from recent list and you will see onDestroy() is called. Android will re-start service if you have returned START_STICKY intent in onStartCommand()).
There are two approaches to fix your problem.
Either make your two services as foreground service.
Instead of using CheckAutoSyncReceivingOrder and CheckAutoSyncSendingOrder to schedule start of another services, you should use AlarmManager to schedule your task.

I need my service to run only in the background, and close immediately when app comes back to the foreground. How can I do this?

As the title suggests, I need a service that runs exclusively in the background. As you will see below, my service gets the user's location, possibly sends it to the server, and sleeps for 10 minutes at a time.
The problem I'm having is that when I try to stop the service, it doesn't do so immediately, causing the UI to be temporarily (but very noticeably) unresponsive for 30 seconds or so, depending on what the service is doing at that time.
LocationService
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
thread = new Thread(new Runnable() {
public void run() {
Log.d("LocationService", "started");
Hawk.init(getApplicationContext());
listener = new Listener();
locationsReceived = new ArrayList<Location>();
locationManager = (LocationManager) LocationService.this.getSystemService(Context.LOCATION_SERVICE);
mHandler = new Handler(Looper.getMainLooper());
runnable = new Runnable() {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted())
try {
startLocationUpdates();
Thread.sleep(30 * 1000);
stopLocationUpdates();
Thread.sleep(60 * 1000);
if (listener.changed)
sendLocationUpdateWithParams();
else
Log.d("LocationService", "Location not sent to server");
Thread.sleep(10 * 60 * 1000);
} catch (InterruptedException e) {
Log.e("LocationService", "Thread interrupted");
Thread.currentThread().interrupt();
}
}
};
mHandler.post(runnable);
}
});
thread.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
thread.interrupt();
Log.d("LocationService", "destroyed");
}
TabActivity (Primary Activity)
#Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, LocationService.class);
stopService(intent);
startingNewActivity = false; // Used to tell whether or not to start service onPause
Log.i("TabActivity", "onResume");
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this, LocationService.class);
stopService(intent);
}
#Override
protected void onPause() {
super.onPause();
// Start background location service
if (!startingNewActivity) {
Intent intent = new Intent(this, LocationService.class);
startService(intent);
}
Log.i("TabActivity", "onPause");
}
I've done a ton of research on this and I'm pulling my hair out.
Thanks in advance!
You can set/reset a Flag in SharedPreferences whenever onPause() / onDestroy() / onResume() is called.Set the flag to false in onPause() and onDestroy() . Set the flag to true in onResume(). Check this value where you start your Service. If value is set, it means your app is running in foreground and start your Service.Else don't.
You should set one flag in onStartCommand() method of service and check it in your main activity (launcher activity).
If that flag returns true that means your service is already started so you can stop it in the onCreate() and/or onStart() method of your main activity. i.e. your service stops when app comes to foreground.
And when your app goes to background or is closed you should start that service again in onStop() and/or odDestroy() method. i.e. your service starts when app goes to background.

android-how to stop services in android

I want to stop the service when I come to the activity . This is my activity code :
stopService(new Intent(this, Services_chat.class));
on call this on the mainactivity and in the oncreate method . so I certainly called .
this is my service code:
public class Services_chat extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("this","caa");
}
}, 0, 1000);//put here time 1000 milliseconds=1 second
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
As you can seen I log and run this code every second , so after running my app and it calls for stopping service , it doesn't stop and it still runs .
How can I stop this service ?
thanks
write this method in Services_chat class.
#Override
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
If you are binding service via onBind() from MainActivity then call unBindService() method to stop service
If you are starting service via startService() from MainActivity then call stopService() or stopSelf()
Android system will try to stop service as soon as possible upon stop request from application
UPDATE :
Add code to stop timer in onDestroy() like :
#Override
public void onDestroy() {
super.onDestroy();
mTimer.cancel();
}
Make object of Timer instead of using Annonymous class Timer :
in onStartCommand() :
Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.v("this","caa");
}
},0,1000);

Android mediaplayer singleton service won't stop playing

I need to have background music in all my activities. It should stop when the application is not foreground. As I'm developing for 2.3 I can't use the ActivityLifeCycleCallBacks class. I implemented the solution at Checking if an Android application is running in the background and then decided to make the mediaplayer a singleton and use it in a service.
Everything works fine and if I press home, select quit from the menu or I make the application go background any way the sound stops but... after some random time when I'm doing something else or even when the screen is turned off the music will start again out of the blue. Even if I kill the application from task manager the will start again later again.
This is my first singleton and my first time playing with service so I guess I'm missing something really basic. I think I'm closing the service but apparently I'm not.
Here is the code:
PlayAudio.java
import ...
public class PlayAudio extends Service{
private static final Intent Intent = null;
MediaPlayer objPlayer;
private int length = 0;
boolean mIsPlayerRelease = true;
private static PlayAudio uniqueIstance; //the singleton
static PlayAudio mService;
static boolean mBound = false; // boolean to check if the service containing this singleton is binded to some activity
public static boolean activityVisible; // boolean to check if the activity using the player is foreground or not
//My attempt to make a singleton
public static PlayAudio getUniqueIstance(){
if (uniqueIstance == null) {
uniqueIstance = new PlayAudio();
}
return uniqueIstance;
}
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
static public ServiceConnection mConnection = new ServiceConnection() {// helper for the activity
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
public static Intent createIntent (Context context) { //helper for the activity using the player
Intent intent = new Intent(context, PlayAudio.class);
return intent;
}
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
PlayAudio getService() {
// Return this instance so clients can call public methods
return PlayAudio.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void onCreate(){
super.onCreate();
Log.d(LOGCAT, "Service Started!");
objPlayer = MediaPlayer.create(this,R.raw.kickstarterreduced);
objPlayer.setLooping(true);
mIsPlayerRelease = false;
}
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer.start();
Log.d(LOGCAT, "Media Player started!");
if(objPlayer.isLooping() != true){
Log.d(LOGCAT, "Problem in Playing Audio");
}
return 1;
}
public void onStop(){
objPlayer.setLooping(false);
objPlayer.stop();
objPlayer.release();
mIsPlayerRelease = true;
}
public void onPause(){
if(objPlayer.isPlaying())
{
objPlayer.pause();
length=objPlayer.getCurrentPosition(); // save the position in order to be able to resume from here
}
}
public void resumeMusic() // if length is 0 the player just start from zero
{ if (mIsPlayerRelease == true) {
objPlayer = MediaPlayer.create(this,R.raw.kickstarterreduced);
mIsPlayerRelease = false;
}
if(objPlayer.isPlaying()==false )
{
if (length != 0) objPlayer.seekTo(length);
objPlayer.start();
}
}
}
And this are the methods I have implemented in every activity's class
SharedPreferences sharedPrefs;
PlayAudio playerIstanced;
public static boolean activityVisible;
#Override
public void onStart() {
super.onStart();
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
public void onResume() {
super.onResume();
playerIstanced= PlayAudio.getUniqueIstance(); //call singleton
bindService(PlayAudio.createIntent(this), playerIstanced.mConnection, Context.BIND_AUTO_CREATE); // create the service
if (sharedPrefs.getBoolean("sound", true) == true) {// if sound is enabled in option it will start the service
startService(PlayAudio.createIntent(this));
playerIstanced.mService.activityResumed();
if (playerIstanced.mBound == true) {
playerIstanced.mService.resumeMusic();
}
}
}
#Override
public void onPause() {
super.onPause();
playerIstanced.mService.activityPaused();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//If the phone lags when changing activity (between onPause() and the other activity onResume() the music won't stop. If after 500ms onResume() is not called it means the activity went background...Am I messing with service here?
if (playerIstanced.mService.isActivityVisible() != true) {
playerIstanced.mService.onPause();
}
}
}, 500);
}
#Override
public void onStop(){
super.onStop();
// Unbind from the service
if (playerIstanced.mService.mBound) {
playerIstanced.mService.mBound = false;
unbindService(playerIstanced.mService.mConnection);
}
}
}
Stop music automatically when user exit from app
This part has to be in EVERY activity's onPause:
public void onPause(){
super.onPause();
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
StopPlayer();
Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP. MUSIC STOP", Toast.LENGTH_SHORT).show();
}
}
}
This part has to be in EVERY activity's onResume:
Play music automatically when user resume the app
Public void onResume()
{
super.onResume();
StartPlayer();
}
Hope it helps!!
You can check my answer according to this topic may it will sove your issue.
You need to manually stop the service using Context.stopService() or stopSelf(). See the Service Lifecycle section of http://developer.android.com/reference/android/app/Service.html.
Service Lifecycle
There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.
I believe you can simply put playerIstanced.stopSelf() in the onStop() call of each activity.
My understanding is that the service continues to run quietly after your application stops. After a while the system kills the service to free up resources, and then after a while more when resources are available it restarts the service. When the service restarts its onResume() is called and the music begins playing.
it helped me stop the mediaplayer.
Use Handler(getMainLooper()) to start and stop MediaPlayer.
final Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
, 30 * 1000);

Categories

Resources