2011-08-12 36 views
3

我已經構建了一個使用startForeground()來維持活動的服務,但我需要使用綁定將其連接到我的活動。使前臺服務與綁定保持一致

事實證明,即使服務在前臺運行,當所有活動都從其中解除時,它仍然會被終止。即使沒有任何活動被綁定,我怎樣才能保持服務的活力?

回答

5

我對這件作品有點驚訝,但實際上您可以撥打startService()從您開始的服務。如果沒有實現onStartCommand(),這仍然有效;只要確保你打電話stopSelf()清理在其他點。

一個例子服務:

public class ForegroundService extends Service { 

    public static final int START = 1; 
    public static final int STOP = 2; 

    final Messenger messenger = new Messenger(new IncomingHandler()); 

    @Override 
    public IBinder onBind(Intent intent){ 
     return messenger.getBinder(); 
    } 

    private Notification makeNotification(){ 
     // build your foreground notification here 
    } 

    class IncomingHandler extends Handler { 

     @Override 
     public void handleMessage(Message msg){ 
      switch(msg.what){ 
      case START: 
       startService(new Intent(this, ForegroundService.class)); 
       startForeground(MY_NOTIFICATION, makeNotification()); 
       break; 

      case STOP: 
       stopForeground(true); 
       stopSelf(); 
       break;  

      default: 
       super.handleMessage(msg);  
      } 
     } 
    } 
} 
+0

只是要清楚:這的確解決了,你先綁定到該服務,然後在服務中你決定讓前臺的場景? –