12月 102019
这几天看安卓系统源码的时候,遇到FLAG_ACTIVITY_FORWARD_RESULT,用于跨Activity传递ActivityResult
记得有一次面试还有面试官问到这个问题,当时还以为是说要用eventbus或者本地广播
我们先用一个图片看看这个标志的作用
下面看看三个Activity的代码
ActivityA的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class AActivity extends AppCompatActivity { public static final int REQCODE_TEST = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); String toastStr = "onActivityResult, " + this.getClass().getName() + ", RequestCode: " + requestCode; if(data != null && data.hasExtra("key")){ toastStr += ",返回key值:" + data.getStringExtra("key"); } Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show(); } public void onButton1Click(View view) { Intent intent = new Intent(this, BActivity.class); startActivityForResult(intent, REQCODE_TEST); } } |
ActivityB的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class BActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_b); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); Toast.makeText(this, "onActivityResult, " + this.getClass().getName() + ", " + requestCode, Toast.LENGTH_SHORT).show(); } public void onButton2Click(View view) { Intent intent = new Intent(this, CActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); // startActivityForResult(intent, 0); //使用FLAG_ACTIVITY_FORWARD_RESULT标志就不能再使用startActivityForResult } } |
ActivityC的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class CActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_c); } @Override public void finish() { Intent resultIntent = new Intent(); resultIntent.putExtra("key", "Value_C"); setResult(AActivity.REQCODE_TEST, resultIntent); super.finish(); } } |
注意事项:
1.如果intent中设置了FLAG_ACTIVITY_FORWARD_RESULT就不能再使用startActivityForResult打开新的Activity了
2.setResult必须在super.finish()之前调用
3.这个标志是否适合于更多层Activity的转发?可以
Sorry, the comment form is closed at this time.