0

我按照以下方式在我的活动中启动服务。服务启动后,我关闭了活动。如果我再次启动 Activity,我想从服务接收一些信息。我怎样才能做到这一点?

// 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);
  }
4

2 回答 2

2

The simplest solution nowadays, IMHO, is to use a third-party event bus, like Square's Otto (using a @Producer to allow the activity to get the last-sent event of a given type) or greenrobot's EventBus (using a sticky event to allow the activity to get the last-sent event of a given type).

于 2013-10-18T14:42:28.130 回答
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!
}

然后服务将提供结果

@Produce public AnswerAvailableEvent produceAnswer() {
    // Assuming 'lastAnswer' exists.
    return new AnswerAvailableEvent(this.lastAnswer);
}
于 2013-10-18T14:46:22.837 回答