3

I want to create application that can play a streaming music . When I press home my app can running in background but when I open another application that use more memory my app will stop and killed by android system . Anyone have another idea to run my music player app in background?

thank you

Music
  • 33
  • 1
  • 4

2 Answers2

6

You have to implement a foreground service:

https://developer.android.com/guide/components/services.html#Foreground

A foreground service is a service that's considered to be something the user is actively aware of and thus 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, which means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

Example:

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
mgutt
  • 5,867
  • 2
  • 50
  • 77
devconsole
  • 7,875
  • 1
  • 34
  • 42
  • 1
    If this is really needed, why aren't messengers like WhatsApp being killed? – mgutt May 20 '16 at 08:13
  • @mgutt, this duplicate SO question has more comprehensive answers: [How can we prevent a Service from being killed by OS?](https://stackoverflow.com/questions/9696861) – devconsole May 24 '16 at 11:26
3

Look the activity lifecycle :)

http://developer.android.com/guide/topics/fundamentals/activities.html

I think you must do a service.

ykatchou
  • 3,667
  • 1
  • 22
  • 27
  • a foreground service is actually what they want, the same way the native player works where you have an ongoing notification see @devconsole's answer – Rob Aug 10 '11 at 09:03