先看看官方文件的說法:
- standard - The system always creates a new instance of the activity in the target task and routes the intent to it.
- singleTop - If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.
這裡用發送通知做測試兩種的差異,啟動 activity 後立即發送 notification,然後到 notification bar 點選 notification 回到同名的 activity,這時 standard 的 activity 就會另外產生一個新的 instance 在原來的 instance 上,而 singleTop 則會回到原來的 instance,可以從唯一的 key 值做判斷,也可以使用 Back 鍵來測試,standard 的要按兩下才會離開該 activity,事實上是離開兩個 instance,而 singleTop 的只要按一下就離開了。
AndroidManifest.xml
<activity. .. android:launchMode="standard | singleTop">
...
</activity>
SingletonActivitypublic class SingletonActivity extends Activity { private static final String TAG = "SingletonActivity"; private NotificationManager nMgr; private long key; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.nMgr = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); this.key = System.currentTimeMillis(); Log.d(TAG, "onCreate - " + key); // 立即發送通知 String title = "Singleton"; String msg = "Singleton 測試"; Notification n = new Notification(R.drawable.ic_launcher, msg, System.currentTimeMillis()); // 回到同名 activity PendingIntent pi = PendingIntent.getActivity(this, 1, new Intent(this, SingletonActivity.class), 0); n.setLatestEventInfo(this, title, msg, pi); this.nMgr.notify(1, n); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume - " + key); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause - " + key); } @Override protected void onDestroy() { super.onPause(); Log.d(TAG, "onDestroy - " + key); } }standard launchMode - 兩組不同 key 值的 onCreate 與 onDestroy。
singleTop launceMode -僅有一組 key 值的 onCreate 與 onDestroy。
沒有留言:
張貼留言