我需要知道如何在另一个活动发送值时暂停一个活动。在我的代码中,主要活动调用第二个活动,第二个活动发送结果,因此理想情况下,主要活动应该等到它从第二个活动收到结果。
public class MainActivity extends AppCompatActivity {
public final static String key = "abc";
public final static String key1 = "abcd";
String abc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this, "sbabs", Toast.LENGTH_SHORT).show();
send();
}
});
}
public void send() {
// Toast.makeText(MainActivity.this, "jsjaskb", Toast.LENGTH_SHORT).show();
// String str="this is";
String[] str = {"Blue", "Green", "Purple", "Red"};
Intent intent = new Intent(this, Second.class);
intent.putExtra(key, str);
startActivityForResult(intent, 1);
Toast.makeText(MainActivity.this, ""+abc, Toast.LENGTH_SHORT).show();
// Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
abc = extras.getString(key1);
// txtinput1.setText(str);
// Toast.makeText(this, ""+str, Toast.LENGTH_SHORT).show();
}
}
}
public class Second extends AppCompatActivity {
public final static String key="abc";
public final static String key1="abcd";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent=getIntent();
String[] msg=intent.getStringArrayExtra(key);
Toast.makeText(this, "" + msg[0], Toast.LENGTH_SHORT).show();
Button b1 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(MainActivity.this, "sbabs", Toast.LENGTH_SHORT).show();
String str = "hello";
Intent intent1 = new Intent();
intent1.putExtra(key1, str);
setResult(RESULT_OK, intent1);
finish();
}
});
}
}
现在的问题是主要活动打印 str=null 在第二个活动可以分配值 str="hello"