欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android實(shí)現(xiàn)Service在前臺運(yùn)行服務(wù)

 更新時(shí)間:2017年11月29日 17:16:35   作者:潘建成  
這篇文章主要為大家詳細(xì)介紹了Android中實(shí)現(xiàn)Service在前臺運(yùn)行服務(wù),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

前言

在做手機(jī)音樂播放器的時(shí)候,讓我非??鄲赖囊患戮褪鞘謾C(jī)有清理內(nèi)存的軟件,比如百度,360等等,一點(diǎn)擊清理音樂就停止播放了,去后臺查看發(fā)現(xiàn)Service已經(jīng)被停止并重新啟動(dòng)了,這顯然不是我想要的,我希望音樂能夠在后臺播放,并且自己能控制什么時(shí)候退出,不想讓系統(tǒng)給我清理了,就像酷狗一直在通知欄顯示那樣,于是我就知道了在前臺運(yùn)行的服務(wù)。

實(shí)現(xiàn)

我們先看一下結(jié)果圖:

這是運(yùn)行在通知欄的界面,這樣就是讓服務(wù)在前臺運(yùn)行,再清理的時(shí)候就不會導(dǎo)致服務(wù)被關(guān)閉了。

好了,我們直接上代碼,因?yàn)橐_啟服務(wù),所以我們必須先要有一個(gè)Service的子類,然后在onCreate里面實(shí)現(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;
 }

}

可以看到,在onCreate方法里面我們得到Notification的一個(gè)對象,然后調(diào)用startForeground(1, notification);方法來實(shí)現(xiàn)在前臺運(yùn)行。如果想要退出只需要退出服務(wù)即可。

小結(jié)

在前臺運(yùn)行服務(wù)是十分有用的,特別是在做播放器開發(fā)的時(shí)候,如果只是簡單的清理一下音樂就退出播放了,這是很不能容忍的。

像酷狗一樣,在通知欄有自己Notification的自定義界面,下一篇文章我說明如何自定義Notification的界面。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論