将数据从广播接收器发送到正在运行的服务

时间:2019-07-10 04:28:49

标签: java android broadcastreceiver android-service

我需要一项服务,以便在从设备接收数据的同时向云发送消息,因此我具有以下代码:

public class MessageService extends Service {
  private int mAlert = 0;
  private PanicReceiver mPanicReceiver;

  @Override
  public void onCreate() {
    super.onCreate();
    mPanicReceiver = new PanicReceiver();

    IntentFilter panicFilter = new IntentFilter();
    panicFilter.addAction(Constants.PANIC_ON_RECEIVER_ACTION);
    panicFilter.addAction(Constants.PANIC_OFF_RECEIVER_ACTION);

    registerReceiver(mPanicReceiver, panicFilter);

  }

  @Override
  public void onDestroy() {
    unregisterReceiver(mPanicReceiver);
    super.onDestroy();
  }

  private class PanicReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      switch (intent.getAction()) {
        case Constants.PANIC_ON_RECEIVER_ACTION:
          mAlert = 2;
          break;
        case Constants.PANIC_OFF_RECEIVER_ACTION:
          mAlert = 0;
          break;
      }
    }
  }
}

我想将广播接收器分隔为单独的文件。你该怎么做?

2 个答案:

答案 0 :(得分:0)

只需将mAlert从MessageService移到PanicReceiver,然后您就可以使用IDE来帮助您重构类,并在类名上方按F6或右键单击:

Right click

Refactor popup

答案 1 :(得分:0)

MessageService.class

public class MessageService extends Service {

  private PanicReceiver mPanicReceiver;

  @Override
  public void onCreate() {
  super.onCreate();
  mPanicReceiver = new PanicReceiver();

  IntentFilter panicFilter = new IntentFilter();
  panicFilter.addAction(Constants.PANIC_ON_RECEIVER_ACTION);
  panicFilter.addAction(Constants.PANIC_OFF_RECEIVER_ACTION);

  registerReceiver(mPanicReceiver, panicFilter);

  }

  @Override
  public void onDestroy() {
    unregisterReceiver(mPanicReceiver);
    super.onDestroy();
  }

  private int getAlert() {
    return mPanicReceiver.getAlert();
  }
}

PanicReceiver.java

private class PanicReceiver extends BroadcastReceiver {

  private int mAlert = 0;

  @Override
  public void onReceive(Context context, Intent intent) {
    switch (intent.getAction()) {
      case Constants.PANIC_ON_RECEIVER_ACTION:
        this.setAlert(2);
        break;
      case Constants.PANIC_OFF_RECEIVER_ACTION:
        this.setAlert(0);
        break;
    }
  }

  public int getAlert() {
    return mAlert;
  }

  public void setAlert(int mAlert) {
    this.mAlert = mAlert;
  }
}