天天看點

Intent、Bundle

1、Intent封裝

  1. public class IntentHelper { 
  2.     private Intent intent; 
  3.     private static IntentHelper intentHelper; 
  4.     private IntentHelper(){ 
  5.         intent = new Intent(); 
  6.     } 
  7.     public static IntentHelper getInstance(){ 
  8.         if(intentHelper == null){ 
  9.             intentHelper = new IntentHelper(); 
  10.         } 
  11.         return intentHelper; 
  12.     } 
  13.     public Intent getIntent(Context packageContext, Class<?> cls){ 
  14.         intent.setClass(packageContext, cls); 
  15.         return intent; 
  16.     } 
  17.     public Intent getIntentClearPreActivity(Context packageContext, Class<?> cls){ 
  18.         Intent intent = new Intent();  
  19.         intent.setClass(packageContext, cls); 
  20.         intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  21.         return intent; 
  22.     } 
  23.     public Intent getNewIntent(Context packageContext, Class<?> cls){ 
  24.         Intent intentNew = new Intent(); 
  25.         intentNew.setClass(packageContext, cls); 
  26.         return intentNew; 
  27.     } 

2、Activity的兩種啟動模式:

  1. FLAG.ACTIVITY_CLEAR_TOP         
  2. FLAG_ACTIVITY_REORDER_TO_FRONT 

如果已經啟動了四個Activity:A,B,C,D 在D Activity裡,我們要跳轉到B Activity,同時希望C finish掉,可以在startActivity(intent)裡的intent裡添加flags标記

  1. Intent intent = new Intent(this, B.class);    
  2. intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);   
  3. startActivity(intent);  

 這樣啟動B Activity,就會把D,C都finished掉,如果你的B Activity的啟動模式是預設的(multiple),則B Activity會finished掉,再啟動一個新的Activity B。如果不想重新再建立一個新的B Activity,則在上面的代碼裡再加上

  1. intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);  
  1. Intent intent = new Intent(); 
  2. Bundle bundle = new Bundle(); 
  3. bundle.putString("Tag", "mapView");   
  4. intent.setClass(A.this, B.class); 
  5. intent.putExtras(bundle); 
  6. startActivity(intent); 
  1. bundle = this.getIntent().getExtras(); 
  2. bundle.getString("Tag");

繼續閱讀