Android Service中给其他的组件回传数据。

1.简单的方法,使用广播。service中处理完数据后发送广播,在需要接收的地方接收广播。

2.使用回调接口。编写回调的地方是往往是处理数据的地方,在这里写interface等。如下:

public class UpdateLiveDataService extends Service {

    private WriteToDbListener mWriteToDbListener;

    public interface WriteToDbListener {
        void onWriteFinish();
    }

    public void setWriteToDbListener(WriteToDbListener listener) {
        mWriteToDbListener = listener;
    }

    /**
     * 返回一个Binder对象
     */
    @Override
    public IBinder onBind(Intent intent) {
        return new MsgBinder();
    }

    public class MsgBinder extends Binder {
        /**
         * 获取当前Service的实例
         * @return
         */
        public UpdateLiveDataService getService(){
            return UpdateLiveDataService.this;
        }
    }

    ...在相关的地方回调
    LogUtil.i(this,"mWriteToDbListener="+mWriteToDbListener);
    if (mWriteToDbListener != null) {
        mWriteToDbListener.onWriteFinish();
    }

}

 
  

使用回调的地方:

 private void registerWriteToDbListener() {
        //绑定Service,现在的service绑定在5.0之后要用显示的绑定了
        Intent intent = new Intent();
        intent.setAction("lenovo.com.ismartvlive.UPDATE");
        intent.setPackage(getPackageName());
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            mUpdateLiveDataService = ((UpdateLiveDataService.MsgBinder)service).getService();

            mUpdateLiveDataService.setWriteToDbListener(new UpdateLiveDataService.WriteToDbListener() {
                @Override
                public void onWriteFinish() {
                    LogUtil.i(this, "write to Db finish,isFirstTune:"+isFirstTune);
                    if (isFirstTune) {
                        startPlayLastTuneChannel();
                    }
                }
            });

        }
    };


你可能感兴趣的:(android)