2013-10-18 45 views
0

我按照以下方式在我的活動中啓動服務。服務開始後,我關閉了活動。如果我再次啓動活動,我想從服務中收到一些信息。我怎樣才能做到這一點?從服務到活動的溝通

// Activity 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    // here I want to receive data from Service 
} 

Intent i=new Intent(this, AppService.class); 

i.putExtra(AppService.TIME, spinner_time.getSelectedItemPosition()); 

startService(i); 


// Service 

public class AppService extends Service { 

    public static final String TIME="TIME"; 

    int time_loud; 

    Notification note; 
    Intent i; 

    private boolean flag_silencemode = false; 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 


    time_loud = intent.getIntExtra(TIME, 0); 

    play(time_loud); 

    return(START_NOT_STICKY); 
    } 

回答

2

時下最簡單的解決方案,恕我直言,是使用第三方事件總線,像Square's Otto(使用@Producer,使活動得到給定類型的最後發送的事件)或greenrobot's EventBus(使用一個粘性事件以允許活動獲得給定類型的最後發送的事件)。

+0

而不是使用第三方解決方案,爲什麼不簡單地使用** LocalBroadcasts **? – waqaslam

+0

@Waqas:對於事件*傳遞*,'LocalBroadcastManager'很好。但是,對於*拉*事件,在「LocalBroadcastManager」中對於Otto的「@ Producer」或「EventBus」粘性事件沒有等價物。 – CommonsWare

+0

但是'context.sendStickyBroadcast'呢? – waqaslam

2

我建議使用Square的Otto庫。

Otto是一種事件總線,旨在將您的 應用程序的不同部分分離,同時仍允許它們有效地進行通信。

最簡單的方法是,你創建一個總線:

Bus bus = new Bus(); 

,那麼只需在發佈事件:

bus.post(new AnswerAvailableEvent(42)); 

到您的Service訂閱

@Subscribe public void answerAvailable(AnswerAvailableEvent event) { 
    // TODO: React to the event somehow! 
} 

然後服務會提供de結果

@Produce public AnswerAvailableEvent produceAnswer() { 
    // Assuming 'lastAnswer' exists. 
    return new AnswerAvailableEvent(this.lastAnswer); 
}