怎么能用当前状态转到以前的活动

时间:2017-02-05 08:21:21

标签: android android-intent android-activity

有两个Activity,在我的Activity1中有按钮转到Activity2

 Intent mIntent=new Intent(MainActivity.this, MainA2ctivity.class);
 startActivity(mIntent);

在我的Activity2中有播放器具有播放恢复按钮和搜索栏,当播放歌曲变成这样:

enter image description here

这是我在Activity2中的回复代码:

@Override
public void onBackPressed()
{

    Intent mIntent=new Intent(Main2Activity.this, MainActivity.class);
    mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    mIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(mIntent);

}  
在Activity1中的

有另一个按钮,我想点击进入活动2时使用当前播放暂停按钮和搜索栏,这是我的代码:

 Intent mIntent=new Intent(MainActivity.this, Main2Activity.class);
 startActivity(mIntent);

但问题是当进入acitvity2歌曲正在播放但是搜索栏和播放暂停按钮仍然像第一次: enter image description here

2 个答案:

答案 0 :(得分:1)

您必须来自 MainActivity 的状态数据来回发送 Main2Activity

MainActivity 代码

final int REQUEST_PLAYPROG = 22; // custom int code

Intent mIntent = new Intent(MainActivity.this, Main2Activity.class);
mIntent.putExtra("playState", isPlaying);
mIntent.putExtra("progress", seekbarProgress);
startActivityForResult(mIntent, REQUEST_PLAYPROG);

Main2Activity 中,您将检索此类数据

Bundle bundle = getIntent().getExtras();
if(bundle!=null) {
    boolean isPlaying = bundle.getBoolean("playState");
    int seekbarProgress = bundle.getInt("progress");
}

完成从A到B的转移,现在你必须将数据从B发送回A onBackPressed

这是 Main2Activity 代码

@Override
public void onBackPressed() {
    Intent mIntent = getIntent();
    mIntent.putExtra("playState", isPlaying);
    mIntent.putExtra("progress", seekbarProgress);
    setResult(RESULT_OK, mIntent);
    finish();
}

最后通过onActivityResult在 MainActivity 中检索数据

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==REQUEST_PLAYPROG && resultCode==RESULT_OK) {
        boolean isPlaying = data.getExtras().getBoolean("playState"), 
        int seekbarProgress = data.getExtras().getInt("progress"), 
    }
}

答案 1 :(得分:0)

您可以使用onSaveInstanceState来保存活动状态,使用onRestoreInstanceState来恢复状态,这是一个例子:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    // Save UI state changes to the savedInstanceState.
    // This bundle will be passed to onCreate if the process is
    // killed and restarted.
    savedInstanceState.putInt("play", true);
    savedInstanceState.putString("playtime", "1:20");
    // etc.
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    // Restore UI state from the savedInstanceState.
    // This bundle has also been passed to onCreate.
    play = savedInstanceState.getBoolean("play");
    playtime = savedInstanceState.getString("playtime");
}

如果活动被杀,请记住这不会起作用。