从服务到活动的ResultReceiver

时间:2016-06-08 18:28:15

标签: android android-intent service

我有一个在后台运行的服务,该服务从一个活动开始,并在没有活动的情况下完成工作。使用ResultReceiver,我可以与活动进行通信,但只要活动处于活动状态。一旦破坏并重新开始,就没有回复活动。我错了什么?

        // Activity
            public void onReceiveResult(int resultCode, Bundle resultData) {
            String test = resultData.getString("Event");
        }
        public MyResultReceiver mReceiver;

        @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      mReceiver = new MyResultReceiver(new Handler());
      mReceiver.setReceiver(this);


        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);
          resultReceiver = intent.getParcelableExtra(RESULT_RECEIVER);
          resultData = new Bundle();

          resultData.putString("Event", "ysfgsdfgsdfg");
          resultReceiver.send(55, resultData);

            play(time_loud); 

            return(START_NOT_STICKY);
          }


    @SuppressLint("ParcelCreator")
    public class MyResultReceiver extends ResultReceiver {

        private Receiver mReceiver;

        public MyResultReceiver(Handler handler) {
            super(handler);
        }

        public void setReceiver(Receiver receiver) {
            mReceiver = receiver;
        }

        public interface Receiver {
            void onReceiveResult(int resultCode, Bundle resultData);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            if (mReceiver != null) {
                mReceiver.onReceiveResult(resultCode, resultData);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

为简单起见,请使用本地广播管理器,并在您的活动onResume上注册和取消注册,onPause生命周期