2021年10月28日木曜日

遷移先情報(deep link とか)を持つ Intent の処理タイミング

以下では、SingleActivity で画面遷移は Navigation Compose を使っている前提である。


ポイント1 : Activity 再生成時には処理しないように onCreate() では savedInstanceState をチェックする

Navigation Compose の backstack 情報は再生成に restore される
  1. class MainActivity : ComponentActivity() {  
  2.   
  3.     override fun onCreate(savedInstanceState: Bundle?) {  
  4.         super.onCreate(savedInstanceState)  
  5.         setContent {  
  6.             ...  
  7.         }  
  8.   
  9.         if (savedInstanceState == null) {  
  10.             handleIntent(intent)  
  11.         }  
  12.     }  
  13.   
  14.     override fun onNewIntent(intent: Intent?) {  
  15.         super.onNewIntent(intent)  
  16.         intent?.let { handleIntent(it) }  
  17.     }  
  18.     
  19.     ...  
  20. }  

ポイント2 : Recent Apps から起動されたときは処理しないように FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY をチェックする

  1. class MainActivity : ComponentActivity() {  
  2.   
  3.     ...  
  4.   
  5.     private fun handleIntent(intent: Intent) {  
  6.         if (intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0) {  
  7.             return  
  8.         }  
  9.   
  10.         // intent の内容に応じて NavHostController.navigate() する  
  11.     }    
  12. }  
Task が生きているときに Recent Apps からアプリを開いても FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY はつかない

Root の Activity が finish されたり、プロセスが kill されているときに Recent Apps からアプリを開くと FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY がつく