前言
在做手機音樂播放器的時候,讓我非常苦惱的一件事就是手機有清理內(nèi)存的軟件,比如百度,360等等,一點擊清理音樂就停止播放了,去后臺查看發(fā)現(xiàn)Service已經(jīng)被停止并重新啟動了,這顯然不是我想要的,我希望音樂能夠在后臺播放,并且自己能控制什么時候退出,不想讓系統(tǒng)給我清理了,就像酷狗一直在通知欄顯示那樣,于是我就知道了在前臺運行的服務(wù)。
實現(xiàn)
我們先看一下結(jié)果圖:
這是運行在通知欄的界面,這樣就是讓服務(wù)在前臺運行,再清理的時候就不會導(dǎo)致服務(wù)被關(guān)閉了。
好了,我們直接上代碼,因為要開啟服務(wù),所以我們必須先要有一個Service的子類,然后在onCreate里面實現(xiàn)它。
MyService.java
public class MyService extends Service { public static final String TAG = "MyService"; @Override public void onCreate() { super.onCreate(); Notification notification = new Notification(R.drawable.ic_launcher, "有通知到來", System.currentTimeMillis()); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(this, "幻聽", "許嵩", pendingIntent); startForeground(1, notification); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } }