Android:如何不断更新/传递值从一个活动到另一个活动?

时间:2016-02-22 07:07:03

标签: android android-intent android-activity runnable

我正在为一个活动制作一个自定义倒计时器,当我切换活动时,我很难不断更新该值。每次我更改活动时,我只能使用一次该值。

示例:

活动A - > B(屏幕上默认为0,用户将值更新为10)

B - > A - > (屏幕上10,用户更新值为10)

B - > A - > (屏幕上35,用户更新值为9000)等

但是,一旦用户设定了时间,它就应该不断更新并将其计算在内。

我能够通过Runnable更新屏幕后面的值并在控制台上打印出值,但我不知道为什么它不会经常将值传递回上一个活动,A,(所以它是最新的)然后让A在用户返回B时将其传递回B.

我应该注意,当我尝试仅更新run()而不是updateTimerButton()中的额外内容时,屏幕上的任何内容都不会更改,默认值就在那里,但在场景之后值正在更新(控制台) )。

这就是我所拥有的:

public class CustomTimer extends Activity {

    private final Handler handler = new Handler();

    private Intent intent;
    private Button timerButton;
    private EditText hourValue, minuteValue;

    private long startTime = 0L;
    private long timeInMilliseconds = 0L;
    private long timeSwapBuff = 0L;
    private long updatedTime = 0L;

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

        intent = getIntent();
        hourValue = (EditText) findViewById(R.id.hour_value);
        minuteValue = (EditText) findViewById(R.id.minute_value);
        timerButton = (Button) findViewById(R.id.start_timer_button);

        //avoid grabbing values from hour and minute if they were not passed for some reason
        if(intent.getStringExtra("hourValue") != null)
            hourValue.setText(getIntent().getStringExtra("hourValue"));
        if(intent.getStringExtra("minuteValue") != null)
            minuteValue.setText(getIntent().getStringExtra("minuteValue"));

        setUpHourValue();
        setUpMinuteValue();
        setUpTimerButton();
    }

    private void setUpHourValue(){

        hourValue.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                hourValue.setText(v.getText().toString());
                return false;
            }
        });
    }

    private void setUpMinuteValue(){

        minuteValue.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                minuteValue.setText(v.getText().toString());
                return false;
            }
        });
    }

    private void setUpTimerButton(){

        timerButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                String hourTime = hourValue.getText().toString();
                String minuteTime = minuteValue.getText().toString();

                //only start the timer if it is not zero
                if (!hourTime.equals("00") || !minuteTime.equals("00")) {
                    System.out.println("starting runnable");
                    startTime = SystemClock.uptimeMillis();
                    handler.postDelayed(updateTimerThread, 0);
                }
                else{
                    System.out.println("time is default\t" + hourTime + "  : " + minuteTime + "************");
                }

                //send the time values back to main
                //this does not constantly update the values, it only updates it once
                intent.putExtra("hourValue", hourTime);
                intent.putExtra("minuteValue", minuteTime);
                setResult(RESULT_OK, intent);
                finish();//go back to the previous page
            }
        });
    }

    private Intent getOuterClassIntent(){
        return intent;
    }

    private Runnable updateTimerThread = new Runnable() {

        //update the time on the screen and constantly pass the values back to main
        public void run() {

            String hourTime = hourValue.getText().toString();
            String minuteTime = minuteValue.getText().toString();

            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            int hour = mins / 60;
            secs = secs % 60;

            //update the time on screen
            hourValue.setText(Integer.toString(Integer.parseInt(hourTime) - hour));
            minuteValue.setText(Integer.toString(Integer.parseInt(minuteTime) - secs));

            System.out.println("updating time in runnable");
            System.out.println(hourValue.getText().toString()+ " : " + minuteValue.getText().toString());

            //pass the values back to main, but this does NOTHING if I comment out the previous putExtras (above)
            getOuterClassIntent().putExtra("hourValue", hourTime);
            getOuterClassIntent().putExtra("minuteValue", minuteTime);
            setResult(RESULT_OK, getOuterClassIntent());

            handler.postDelayed(this, 0);
        }
    };
}

2 个答案:

答案 0 :(得分:3)

如果您需要在多个活动之间共享数据,则它不应归任何一项活动所有。创建服务,让两个活动在它们启动时绑定到它,并在需要知道值时查询服务(通过Binder)。所有值的更新都应该在服务中进行。

答案 1 :(得分:0)

您可以使用服务来保留倒计时器的值,也可以使用event bus更新activity上的值运行时间。

EventBus.getDefault().register(your activity);

然后在您的活动A或B中的值更改时发布事件

EventBus.getDefault().post(your value to post);

并覆盖方法OnEvent(your data type)以获取更新后的值

请参阅 this