添加到包而不提取它

时间:2017-08-02 09:11:45

标签: android bundle

我有两节课。 A类和类 B 。在A类中,我将一些字符串放入一个bundle对象中,然后将其发送到 class B

我的问题在这里: 我可以直接将一些stringint放入此捆绑包而不在B类中提取它并向其添加额外信息,然后创建一个新的捆绑包。

******* ******* EDIT 其他情况:

我已经从意向服务发送了一个捆绑到活动然后在活动中我想为这个捆绑添加一些额外的东西,最后我将这个捆绑包发送到后台线程以保存在sharePreference上。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

是的,你可以这样做。因此,在您的B类中,当您想要打开C类时,您可以从先前的意图中获取该包,然后继续添加到同一个包中并打开C

Intent newIntent = new Intent(ActivityB.this, ActivityC.class);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    bundle.putString("newKey","newValue");
    newIntent.putExtras(bundle);
}
startActivity(newIntent);

<强>更新

因为您希望在BG线程中传递此Bundle并假设您正在使用AsyncTask,您可以执行以下操作 -

声明您的异步任务,如下所示 -

 class MyBGClass extends AsyncTask<Bundle,Void,Void>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }



        @Override
        protected Void doInBackground(Bundle... params) {
            return null;
        }
    }

然后调用它就可以了 -

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    bundle.putString("newKey","newValue");
}
new MyBGClass().execute(bundle);

更新2: 从resultReceiver传递数据 -

receiver.send(RESULT_CODE, bundle);

然后在您的活动中,您将此结果接收者传递给您的服务工具

 @Override
protected void onReceiveResult(int resultCode, Bundle resultData) {

    //resultData is your bundle. to add to it -
    if (resultData != null) {
        resultData.putString("newKey","newValue");
    }
}

然后拨打你的BG线程。

更改WorkerThread类的构造函数,如下所示,并在创建类的对象时将bundle传递给您的线程 -

private class WorkerThread extends HandlerThread {
    private static final int SAVE = 1;
    PreferenceModel instancePreferenceModel;
    Bundle bundle;
    private Handler mHandler;
    public WorkerThread(Bundle bundle) {
        super("WorkerThread", Process.THREAD_PRIORITY_BACKGROUND);
        App app = (App) getApplication();
        this.bundle = bundle;
        instancePreferenceModel = app.getInstancePreferenceModel();
    }

    @Override
    protected void onLooperPrepared() {
        super.onLooperPrepared();

        mHandler = new Handler(getLooper()) {

            @Override // receive message from uiThread as Bundle object.
            public void handleMessage(Message msg) {

                switch (msg.what) {

                    case SAVE:
                        Log.i(TAG, "handleMessage: saved completed");
                        Bundle data = (Bundle) msg.obj;
                        Log.i(TAG, "getData: " + data.getString(LoginIntentService.EXTRA_FIRST_NAME));
                        instancePreferenceModel.saveUserInfo(data);
                        break;
                }

            }

        };

    }

    // this method is access to main ui thread.by this method UiThread can send a Message
    // Background Thread
    public void write(Bundle b) {
        Message msg = new Message();
        msg.obj = b;
        Message obtain = Message.obtain(mHandler, SAVE, msg.obj);
        mHandler.sendMessage(obtain);
    }

}