As we all know, we usually put the logic of the play into the service, so that we can continue to play music in the background function. The probability of the backend service being reclaimed by the system is relatively low, but this situation does exist.
Front-desk services are services that are considered user-aware and do not allow the system to kill when memory is low. The front desk service must provide a notification to the status bar that he is placed under the "in Progress (ongoing)" heading, which means that until the service is terminated or the notification is removed from the foreground to be dismissed.
For example, a music player service that plays music should be set up to run in the foreground because the user knows exactly what they are doing. Notifications in the status bar may indicate the current song, and the user initiates an activity that interacts with the music player.
To have your service run in the foreground, you need to call the Startforeground () method, which requires two parameters: An integer that uniquely identifies the notification and a notification to the status bar, such as:
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, NOTIFICATION);
To remove a service from the foreground, you need to call the Stopforeground () method, which requires a Boolean parameter indicating whether to delete the status bar notification. This method does not terminate the service. However, if you terminate a running foreground service, the notification will also be deleted.
Note: the Startforeground () and Stopforeground () methods are introduced in Android2.0 (API level 5). In order to run your service in the older platform version, you must use the previous Setforeground () method---about how to provide backward compatibility, see the Startforeground () method documentation.
The sample code is as follows:
Forgroundservice.java
Import Java.io.file;import android.app.notification;import android.app.pendingintent;import android.app.Service; Import Android.content.intent;import android.media.mediaplayer;import android.net.uri;import android.os.Binder; Import Android.os.ibinder;public class Forgroundservice extends Service {private static final int notification_id = 100;PR Ivate static final Uri Mmusicuri = uri.fromfile (New File ("/sdcard/sound_file_1.mp3"));p rivate MediaPlayer Mmediaplayer = Null;public class Forgroundservicebinder extends Binder {public void Playmusic () {stopcurrentmediaplayer (); Mmediaplayer = Mediaplayer.create (Getapplicationcontext (), Mmusicuri); Mmediaplayer.start (); String songname = "Test Music";//Assign the song name to songnamependingintent pi = pendingintent.getactivity (getapplicat Ioncontext (), 0, New Intent (Getapplicationcontext (), Forgroundserviceactivity.class), Pendingintent.flag_update_ Current); Notification Notification = new Notification (); notification.tickertext = "Forground Service";Notification.icon = R.drawable.icon;notification.flags |= notification.flag_ongoing_event; Notification.setlatesteventinfo (Getapplicationcontext (), "Musicplayersample", "Playing:" + songname, pi); Startforeground (notification_id, NOTIFICATION);//start foreground service}public void Stopmusic () {stopcurrentmediaplayer (); Stopforeground (TRUE);//close front service}}private forgroundservicebinder mbinder = new Forgroundservicebinder (); Overridepublic ibinder onbind (Intent arg0) {return mbinder;} @Overridepublic void OnDestroy () {stopcurrentmediaplayer (); Super.ondestroy ();} private void Stopcurrentmediaplayer () {if (Mmediaplayer! = null) {mmediaplayer.stop (); Mmediaplayer.release (); Mmediaplayer = null;}}}
Forgroundserviceactivity.java
Import Forgroundservice.forgroundservicebinder;import Android.app.activity;import android.content.ComponentName; Import Android.content.intent;import Android.content.serviceconnection;import Android.os.bundle;import Android.os.ibinder;import Android.view.view;import Android.view.view.onclicklistener;public Class Forgroundserviceactivity extends Activity {@Overrideprotected void OnDestroy () {unbindservice (mserviceconnection); Super.ondestroy ();} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.layout_forground_service); final Intent serviceintent = new Intent (this, forgroundservice.class);// StartService (serviceintent); Bindservice (Serviceintent, mserviceconnection, bind_auto_create);} Private Serviceconnection mserviceconnection = new Serviceconnection () {@Overridepublic void onserviceconnected ( ComponentName name, IBinder Binder) {final Forgroundservicebinder service = (forgroundservicebinder) binder; Findviewbyid (R.id.starT). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {service.playmusic ();}}); Findviewbyid (r.id.stop). Setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) { Service.stopmusic ();}});} @Overridepublic void onservicedisconnected (componentname name) {}};}
Layout_forground_service.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:layout_width=" match_parent " android:layout_height=" match_parent " android:o rientation= "vertical" > <button android:id= "@+id/start" android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "Play"/> <button android:id= "@+id/ Stop " android:layout_width=" match_parent " android:layout_height=" wrap_content " android:text=" Stop "/></linearlayout>