41

is there a way to set the "task affinity" programmatically? I mean like with some Intent flag or sth? I didn't find anything about this being possible in the Android docs.

Setting the affinity in a static way in the AndroidManifest.xml with android:taskAffinity does not suit my needs.

RamblinRose
  • 4,883
  • 2
  • 21
  • 33
aMiGo
  • 757
  • 7
  • 10
  • Whenever launching an Activity, you can add affinity flags like so. Not sure if this is what you intended. ```Intent intent = new Intent(this, IntroActivity.class); // These flags disable back-pressing back into the previous activity intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); finish();``` – Clark Wilson Aug 07 '16 at 19:53
  • Possible duplicate of [Android: Task affinity & Clear task](https://stackoverflow.com/questions/21528508/android-task-affinity-clear-task) – Ganesh May 04 '18 at 09:00

2 Answers2

5

You cannot.

taskAffinity is contained by ActivityInfo, which is member of Activity.

Source code of Activity

public class Activity extends ContextThemeWrapper
    ...
    ... {
    // set by the thread after the constructor and before 
    // onCreate(Bundle savedInstanceState) is called.

    @UnsupportedAppUsage
    /*package*/ ActivityInfo mActivityInfo;
 }

And ActivityInfo has taskAffinity.

Source code of ActivityInfo

/**
 * Information you can retrieve about a particular application
 * activity or receiver. This corresponds to information collected
 * from the AndroidManifest.xml's <activity> and
 * <receiver> tags.
 */
public class ActivityInfo extends ComponentInfo implements Parcelable {

   /**
    * The affinity this activity has for another task in the system.  The
    * string here is the name of the task, often the package name of the
    * overall package.  If null, the activity has no affinity.  Set from the
    * {@link android.R.attr#taskAffinity} attribute.
    */
    public String taskAffinity;

According to the comment of source code, information of taskAffinity is collected from AndroidManifest.xml. And there is no public method to set mActivityInfo.taskAffinity.

Stanley Ko
  • 3,383
  • 3
  • 34
  • 60
-4

Use this method :

finishAffinity();
Boken
  • 4,825
  • 10
  • 32
  • 42