published: July 22nd, 2010
Go home feature with FLAG_ACTIVITY_CLEAR_TOP
Here’s a little snippet I wrote up the other day to support a Go Home feature for the app I’ve been helping with. It sets the FLAG_ACTIVITY_CLEAR_TOP flag on the Intent along with the HomeActivity. This flag, according to the Android docs, launches a new instance of the activity if it isn’t currently running, and closes all the activities on top of it. So if there are any activities on top of HomeActivity they are cleared and HomeActivity is displayed to the user. I also added a check to determine if the supplied Context is already the HomeActivity, and if so, ignore the call.
public static void goHome( Context ctx )
{
if ( ! ( ctx instanceof HomeActivity ) )
{
Intent intent = new Intent( ctx, HomeActivity.class );
intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP );
ctx.startActivity( intent );
}
}

