Example usage for android.support.v4.app TaskStackBuilder startActivities

List of usage examples for android.support.v4.app TaskStackBuilder startActivities

Introduction

In this page you can find the example usage for android.support.v4.app TaskStackBuilder startActivities.

Prototype

public void startActivities() 

Source Link

Document

Start the task stack constructed by this builder.

Usage

From source file:org.sufficientlysecure.keychain.ui.CreateKeyActivity.java

public void finishWithFirstTimeHandling(@Nullable Intent intentToLaunch) {
    if (mFirstTime) {
        Preferences prefs = Preferences.getPreferences(this);
        prefs.setFirstTime(false);// w  ww . j  a va2s  . c  om

        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
        Intent mainActivityIntent = new Intent(this, MainActivity.class);
        taskStackBuilder.addNextIntent(mainActivityIntent);
        if (intentToLaunch != null) {
            taskStackBuilder.addNextIntent(intentToLaunch);
        }
        taskStackBuilder.startActivities();
    } else if (intentToLaunch != null) {
        startActivity(intentToLaunch);
    }

    super.finish();
}

From source file:com.flowzr.activity.AboutActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home: {
        TaskStackBuilder tsb = TaskStackBuilder.create(this);
        final int intentCount = tsb.getIntentCount();
        if (intentCount > 0) {
            Intent upIntent = tsb.getIntents()[intentCount - 1];
            if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                // This activity is not part of the application's task, so create a new task with a synthesized back stack.
                tsb.startActivities();
                finish();//w  w w  . j a  va2s.  c  om
            } else {
                // This activity is part of the application's task, so simply navigate up to the hierarchical parent activity.
                NavUtils.navigateUpTo(this, upIntent);
            }
        } else {
            onBackPressed();
        }
        return true;
    }

    }
    return super.onOptionsItemSelected(item);
}

From source file:net.naonedbus.appwidget.HoraireWidgetProvider.java

/**
 * Grer le signal de rafraichissement.//from  ww  w .  j  a v a2 s  . co m
 */
@Override
public void onReceive(final Context context, final Intent intent) {
    final String action = intent.getAction();
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

    if (DBG)
        Log.i(LOG_TAG, Integer.toHexString(hashCode()) + " - " + "onReceive " + action);

    final boolean updateWidget = ACTION_APPWIDGET_UPDATE.equals(action)
            || Intent.ACTION_USER_PRESENT.equals(action);

    if (updateWidget) {

        final int idExtra = intent.getIntExtra("id", -1);
        int[] ids;

        if (DBG)
            Log.i(LOG_TAG, Integer.toHexString(hashCode()) + " - "
                    + "Rception de l'ordre de rafraichissement des widgets.");

        if (idExtra == -1) {
            ids = appWidgetManager.getAppWidgetIds(new ComponentName(context, this.getClass()));
        } else {
            ids = new int[] { idExtra };
        }

        onUpdate(context, appWidgetManager, ids);

    } else if (HoraireWidgetProvider.ACTION_APPWIDGET_ON_CLICK.equals(action)) {

        final Arret arret = intent.getParcelableExtra("favori");
        if (arret != null) {
            final ParamIntent startIntent = new ParamIntent(context, HorairesActivity.class);
            startIntent.putExtra(HorairesActivity.PARAM_ARRET, arret);
            startIntent.putExtra(HorairesActivity.PARAM_FROM_WIDGET, true);
            startIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            final TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(MainActivity.class);
            stackBuilder.addNextIntentWithParentStack(startIntent);

            stackBuilder.startActivities();
        }
    }

    super.onReceive(context, intent);
}

From source file:com.flowzr.activity.DateFilterActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_done:
        Intent data = new Intent();
        PeriodType period = periods[spinnerPeriodType.getSelectedItemPosition()];
        data.putExtra(EXTRA_FILTER_PERIOD_TYPE, period.name());
        data.putExtra(EXTRA_FILTER_PERIOD_FROM, cFrom.getTimeInMillis());
        data.putExtra(EXTRA_FILTER_PERIOD_TO, cTo.getTimeInMillis());
        setResult(RESULT_OK, data);/*from  www  .j  a  v  a2 s.  com*/
        finish();
        return true;
    case R.id.action_cancel:
        setResult(RESULT_CANCELED);
        finish();
        return true;
    case android.R.id.home: {
        TaskStackBuilder tsb = TaskStackBuilder.create(this);
        final int intentCount = tsb.getIntentCount();
        if (intentCount > 0) {
            Intent upIntent = tsb.getIntents()[intentCount - 1];
            if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                // This activity is not part of the application's task, so create a new task with a synthesized back stack.
                tsb.startActivities();
                finish();
            } else {
                // This activity is part of the application's task, so simply navigate up to the hierarchical parent activity.
                NavUtils.navigateUpTo(this, upIntent);
            }
        } else {
            onBackPressed();
        }
        return true;
    }
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.flowzr.activity.BackupListActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_settings:
        startActivity(new Intent(getApplicationContext(), BackupPreferencesActivity.class));
        return true;
    case android.R.id.home: {
        TaskStackBuilder tsb = TaskStackBuilder.create(this);
        final int intentCount = tsb.getIntentCount();
        if (intentCount > 0) {
            Intent upIntent = tsb.getIntents()[intentCount - 1];
            if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                // This activity is not part of the application's task, so create a new task with a synthesized back stack.
                tsb.startActivities();
                finish();//w w w  . j av  a  2 s . c o m
            } else {
                // This activity is part of the application's task, so simply navigate up to the hierarchical parent activity.
                NavUtils.navigateUpTo(this, upIntent);
            }
        } else {
            onBackPressed();
        }
        return true;
    }

    }
    return super.onOptionsItemSelected(item);
}

From source file:androidx.navigation.NavController.java

/**
 * Attempts to navigate up in the navigation hierarchy. Suitable for when the
 * user presses the "Up" button marked with a left (or start)-facing arrow in the upper left
 * (or starting) corner of the app UI.//w  w w  .j a v  a  2  s .  c  o m
 *
 * <p>The intended behavior of Up differs from {@link #popBackStack() Back} when the user
 * did not reach the current destination from the application's own task. e.g. if the user
 * is viewing a document or link in the current app in an activity hosted on another app's
 * task where the user clicked the link. In this case the current activity (determined by the
 * context used to create this NavController) will be {@link Activity#finish() finished} and
 * the user will be taken to an appropriate destination in this app on its own task.</p>
 *
 * @return true if navigation was successful, false otherwise
 */
public boolean navigateUp() {
    if (mBackStack.size() == 1) {
        // If there's only one entry, then we've deep linked into a specific destination
        // on another task so we need to find the parent and start our task from there
        NavDestination currentDestination = getCurrentDestination();
        int destId = currentDestination.getId();
        NavGraph parent = currentDestination.getParent();
        while (parent != null) {
            if (parent.getStartDestination() != destId) {
                TaskStackBuilder parentIntents = new NavDeepLinkBuilder(NavController.this)
                        .setDestination(parent.getId()).createTaskStackBuilder();
                parentIntents.startActivities();
                if (mActivity != null) {
                    mActivity.finish();
                }
                return true;
            }
            destId = parent.getId();
            parent = parent.getParent();
        }
        // We're already at the startDestination of the graph so there's no 'Up' to go to
        return false;
    } else {
        return popBackStack();
    }
}

From source file:com.flowzr.activity.RecurActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_done:
        RecurInterval interval = getRecurInterval(sInterval.getSelectedItem());
        RecurPeriod period = periods[sPeriod.getSelectedItemPosition()];
        Recur r = RecurUtils.createRecur(interval);
        r.startDate = startDate.getTimeInMillis();
        r.period = period;//from w w w  .jav a  2  s.  c o  m
        if (updateInterval(r) && updatePeriod(r)) {
            Intent data = new Intent();
            data.putExtra(EXTRA_RECUR, r.toString());
            setResult(RESULT_OK, data);
            finish();
        }
        return true;
    case R.id.action_cancel:
        setResult(RESULT_CANCELED, null);
        finish();
        return true;
    case android.R.id.home: {
        TaskStackBuilder tsb = TaskStackBuilder.create(this);
        final int intentCount = tsb.getIntentCount();
        if (intentCount > 0) {
            Intent upIntent = tsb.getIntents()[intentCount - 1];
            if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                // This activity is not part of the application's task, so create a new task with a synthesized back stack.
                tsb.startActivities();
                finish();
            } else {
                // This activity is part of the application's task, so simply navigate up to the hierarchical parent activity.
                NavUtils.navigateUpTo(this, upIntent);
            }
        } else {
            onBackPressed();
        }
        return true;
    }
    }
    return super.onOptionsItemSelected(item);
}

From source file:androidx.navigation.NavController.java

/**
 * Checks the given Intent for a Navigation deep link and navigates to the deep link if present.
 * This is called automatically for you the first time you set the graph if you've passed in an
 * {@link Activity} as the context when constructing this NavController, but should be manually
 * called if your Activity receives new Intents in {@link Activity#onNewIntent(Intent)}.
 * <p>//from w ww .  j av a  2 s.c  o m
 * The types of Intents that are supported include:
 * <ul>
 *     <ol>Intents created by {@link NavDeepLinkBuilder} or
 *     {@link #createDeepLink()}. This assumes that the current graph shares
 *     the same hierarchy to get to the deep linked destination as when the deep link was
 *     constructed.</ol>
 *     <ol>Intents that include a {@link Intent#getData() data Uri}. This Uri will be checked
 *     against the Uri patterns added via {@link NavDestination#addDeepLink(String)}.</ol>
 * </ul>
 * <p>The {@link #getGraph() navigation graph} should be set before calling this method.</p>
 * @param intent The Intent that may contain a valid deep link
 * @return True if the navigation controller found a valid deep link and navigated to it.
 * @see NavDestination#addDeepLink(String)
 */
public boolean onHandleDeepLink(@Nullable Intent intent) {
    if (intent == null) {
        return false;
    }
    Bundle extras = intent.getExtras();
    int[] deepLink = extras != null ? extras.getIntArray(KEY_DEEP_LINK_IDS) : null;
    Bundle bundle = new Bundle();
    Bundle deepLinkExtras = extras != null ? extras.getBundle(KEY_DEEP_LINK_EXTRAS) : null;
    if (deepLinkExtras != null) {
        bundle.putAll(deepLinkExtras);
    }
    if ((deepLink == null || deepLink.length == 0) && intent.getData() != null) {
        Pair<NavDestination, Bundle> matchingDeepLink = mGraph.matchDeepLink(intent.getData());
        if (matchingDeepLink != null) {
            deepLink = matchingDeepLink.first.buildDeepLinkIds();
            bundle.putAll(matchingDeepLink.second);
        }
    }
    if (deepLink == null || deepLink.length == 0) {
        return false;
    }
    bundle.putParcelable(KEY_DEEP_LINK_INTENT, intent);
    int flags = intent.getFlags();
    if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 && (flags & Intent.FLAG_ACTIVITY_CLEAR_TASK) == 0) {
        // Someone called us with NEW_TASK, but we don't know what state our whole
        // task stack is in, so we need to manually restart the whole stack to
        // ensure we're in a predictably good state.
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(mContext)
                .addNextIntentWithParentStack(intent);
        taskStackBuilder.startActivities();
        if (mActivity != null) {
            mActivity.finish();
        }
        return true;
    }
    if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        // Start with a cleared task starting at our root when we're on our own task
        if (!mBackStack.isEmpty()) {
            navigate(mGraph.getStartDestination(), bundle, new NavOptions.Builder()
                    .setPopUpTo(mGraph.getId(), true).setEnterAnim(0).setExitAnim(0).build());
        }
        int index = 0;
        while (index < deepLink.length) {
            int destinationId = deepLink[index++];
            NavDestination node = findDestination(destinationId);
            if (node == null) {
                throw new IllegalStateException("unknown destination during deep link: "
                        + NavDestination.getDisplayName(mContext, destinationId));
            }
            node.navigate(bundle, new NavOptions.Builder().setEnterAnim(0).setExitAnim(0).build());
        }
        return true;
    }
    // Assume we're on another apps' task and only start the final destination
    NavGraph graph = mGraph;
    for (int i = 0; i < deepLink.length; i++) {
        int destinationId = deepLink[i];
        NavDestination node = i == 0 ? mGraph : graph.findNode(destinationId);
        if (node == null) {
            throw new IllegalStateException("unknown destination during deep link: "
                    + NavDestination.getDisplayName(mContext, destinationId));
        }
        if (i != deepLink.length - 1) {
            // We're not at the final NavDestination yet, so keep going through the chain
            graph = (NavGraph) node;
        } else {
            // Navigate to the last NavDestination, clearing any existing destinations
            node.navigate(bundle, new NavOptions.Builder().setPopUpTo(mGraph.getId(), true).setEnterAnim(0)
                    .setExitAnim(0).build());
        }
    }
    return true;
}

From source file:com.google.samples.apps.iosched.ui.BaseActivity.java

/**
 * Enables back navigation for activities that are launched from the NavBar. See
 * {@code AndroidManifest.xml} to find out the parent activity names for each activity.
 * @param intent//from ww w  . j  a  v a2 s  .c o  m
 */
private void createBackStack(Intent intent) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        TaskStackBuilder builder = TaskStackBuilder.create(this);
        builder.addNextIntentWithParentStack(intent);
        builder.startActivities();
    } else {
        startActivity(intent);
        finish();
    }
}

From source file:com.smithdtyler.prettygoodmusicplayer.NowPlaying.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent originIntent = getIntent();/* w  w w .  j  av a  2 s.co  m*/
    if (originIntent.getBooleanExtra("From_Notification", false)) {

        String artistName = originIntent.getStringExtra(ArtistList.ARTIST_NAME);
        String artistAbsPath = originIntent.getStringExtra(ArtistList.ARTIST_ABS_PATH_NAME);
        if (artistName != null && artistAbsPath != null) {
            Log.i(TAG, "Now Playing was launched from a notification, setting up its back stack");
            // Reference: https://developer.android.com/reference/android/app/TaskStackBuilder.html
            TaskStackBuilder tsb = TaskStackBuilder.create(this);
            Intent intent = new Intent(this, ArtistList.class);
            tsb.addNextIntent(intent);

            intent = new Intent(this, AlbumList.class);
            intent.putExtra(ArtistList.ARTIST_NAME, artistName);
            intent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath);
            tsb.addNextIntent(intent);

            String albumName = originIntent.getStringExtra(AlbumList.ALBUM_NAME);
            if (albumName != null) {
                intent = new Intent(this, SongList.class);
                intent.putExtra(AlbumList.ALBUM_NAME, albumName);
                intent.putExtra(ArtistList.ARTIST_NAME, artistName);
                intent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath);
                tsb.addNextIntent(intent);
            }
            intent = new Intent(this, NowPlaying.class);
            tsb.addNextIntent(intent);
            tsb.startActivities();
        }

    }

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String theme = sharedPref.getString("pref_theme", getString(R.string.light));
    String size = sharedPref.getString("pref_text_size", getString(R.string.medium));
    Log.i(TAG, "got configured theme " + theme);
    Log.i(TAG, "got configured size " + size);

    // These settings were fixed in english for a while, so check for old style settings as well as language specific ones.
    if (theme.equalsIgnoreCase(getString(R.string.dark)) || theme.equalsIgnoreCase("dark")) {
        Log.i(TAG, "setting theme to " + theme);
        if (size.equalsIgnoreCase(getString(R.string.small)) || size.equalsIgnoreCase("small")) {
            setTheme(R.style.PGMPDarkSmall);
        } else if (size.equalsIgnoreCase(getString(R.string.medium)) || size.equalsIgnoreCase("medium")) {
            setTheme(R.style.PGMPDarkMedium);
        } else {
            setTheme(R.style.PGMPDarkLarge);
        }
    } else if (theme.equalsIgnoreCase(getString(R.string.light)) || theme.equalsIgnoreCase("light")) {
        Log.i(TAG, "setting theme to " + theme);
        if (size.equalsIgnoreCase(getString(R.string.small)) || size.equalsIgnoreCase("small")) {
            setTheme(R.style.PGMPLightSmall);
        } else if (size.equalsIgnoreCase(getString(R.string.medium)) || size.equalsIgnoreCase("medium")) {
            setTheme(R.style.PGMPLightMedium);
        } else {
            setTheme(R.style.PGMPLightLarge);
        }
    }

    boolean fullScreen = sharedPref.getBoolean("pref_full_screen_now_playing", false);
    currentFullScreen = fullScreen;
    if (fullScreen) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    } else {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    setContentView(R.layout.activity_now_playing);

    if (savedInstanceState == null) {
        doBindService(true);
        startPlayingRequired = true;
    } else {
        doBindService(false);
        startPlayingRequired = false;
    }

    // Get the message from the intent
    Intent intent = getIntent();
    if (intent.getBooleanExtra(KICKOFF_SONG, false)) {
        desiredArtistName = intent.getStringExtra(ArtistList.ARTIST_NAME);
        desiredAlbumName = intent.getStringExtra(AlbumList.ALBUM_NAME);
        desiredArtistAbsPath = intent.getStringExtra(ArtistList.ARTIST_ABS_PATH_NAME);
        desiredSongAbsFileNames = intent.getStringArrayExtra(SongList.SONG_ABS_FILE_NAME_LIST);
        desiredAbsSongFileNamesPosition = intent.getIntExtra(SongList.SONG_ABS_FILE_NAME_LIST_POSITION, 0);
        desiredSongProgress = intent.getIntExtra(MusicPlaybackService.TRACK_POSITION, 0);

        Log.d(TAG,
                "Got song names " + desiredSongAbsFileNames + " position " + desiredAbsSongFileNamesPosition);

        TextView et = (TextView) findViewById(R.id.artistName);
        et.setText(desiredArtistName);

        et = (TextView) findViewById(R.id.albumName);
        et.setText(desiredAlbumName);
    }

    // The song name field will be set when we get our first update update from the service.

    final ImageButton pause = (ImageButton) findViewById(R.id.playPause);
    pause.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            playPause();
        }

    });

    ImageButton previous = (ImageButton) findViewById(R.id.previous);
    previous.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            previous();
        }

    });

    previous.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            jumpBack();
            return true;
        }
    });

    ImageButton next = (ImageButton) findViewById(R.id.next);
    next.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            next();
        }
    });

    final ImageButton shuffle = (ImageButton) findViewById(R.id.shuffle);
    shuffle.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleShuffle();
        }
    });

    final ImageButton jumpback = (ImageButton) findViewById(R.id.jumpback);
    jumpback.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            jumpBack();
        }
    });

    SeekBar seekBar = (SeekBar) findViewById(R.id.songProgressBar);
    seekBar.setEnabled(true);
    seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        private int requestedProgress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                Log.v(TAG, "drag location updated..." + progress);
                this.requestedProgress = progress;
                updateSongProgressLabel(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            NowPlaying.this.userDraggingProgress = true;

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            Message msg = Message.obtain(null, MusicPlaybackService.MSG_SEEK_TO);
            msg.getData().putInt(MusicPlaybackService.TRACK_POSITION, requestedProgress);
            try {
                Log.i(TAG, "Sending a request to seek!");
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            NowPlaying.this.userDraggingProgress = false;
        }

    });

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.smithdtyler.ACTION_EXIT");
    exitReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "Received exit request, shutting down...");
            Intent msgIntent = new Intent(getBaseContext(), MusicPlaybackService.class);
            msgIntent.putExtra("Message", MusicPlaybackService.MSG_STOP_SERVICE);
            startService(msgIntent);
            finish();
        }

    };
    registerReceiver(exitReceiver, intentFilter);
}