Single Task Flag in Android Activities.
Android Activities

Single Task Flag in Android Activities.

There are several easy tricky points which do not considered by junior Android developers. In this article i want to speak about Single Task flag during using activities.

In your project there is a Back-Stack that is responsible to keep activities in a stack. Each activity depends on how do they initialized they will be exist in a specific Task. When an activity determined as a Single Task it means this activity and other activities which will be opened on it whole will be kept in one task so Android does not create multiple task for each of them regardless of the other activities that opened on the activity had Single Task flag or they started in standard mode.

<activity android:name="Activity" android:launchMode="singleTask">

By default when you start an activity with no launch mode every time the onCreate() function will fire and you can do some other works when the activity appeared.

As we said before, in Single-Task activities, onCreate() method will fire when an intent create an activity and initialize it for the first time though that function has created and does not execute for several times.

So what should we do if we want pass some data or do few activities in Single Task launch mode?

We have a function in the Activity`s super class name onNewIntent(), this function will fire same as you start a single task activity while that is exist in background. Same as onCreate() method it returns an intent that can include some bundles from previous activity.

protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  setIntent(intent);
  // Do some extras ...  
}

Keep in your mind in a same time just one of these two methods will fire so when the activity start for the first time or that was not existed in background(Memory) onCreate() method will start while onNewIntent() will useful if started activity has existed in the background stack and it just come to the foreground so both of them should have a same behavior to prevent application from crash.

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  // do some extras
}
 
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  setIntent(intent);
  // do some extras
}

Good Luck.



要查看或添加评论,请登录

Mo Ravaei的更多文章

社区洞察

其他会员也浏览了