建立前臺 Service

 Service在後臺運行時,若是系統內存內存不足時,就有可能會回收掉後臺運行的Service,ui

 若是想要Service一直運行,而不會由於內存不足時被回收,就能夠使用前臺Service;this

 前臺Service和普通Service的區別:spa

 

 前臺Service會有個圖標顯示在系統的狀態欄,下拉狀態欄會有更詳細的信息對象

 前臺Service的建立blog

  在onCreate()方法中:內存

  一、建立一個Notification對象。並設置參數;get

  二、調用startForeground(1,notification); //啓動爲前臺Serviceit

 

public void onCreate()
	{				
		super.onCreate();
		
		Intent intent = new Intent(this,MainActivity.class);
		PendingIntent pend = PendingIntent.getActivity(this,0, intent,0);
		 
		//建立Notification
		NotificationCompat.Builder nc = new Builder(this);
			nc.setContentTitle("前臺Service");
			nc.setContentText("有新消息");
			nc.setSmallIcon(R.drawable.ic_launcher);
			nc.setContentIntent(pend);
			Notification notifivatiion = nc.build();
			
			//開啓模式爲     前臺Service
			startForeground(1,notifivatiion);	
	}
相關文章
相關標籤/搜索