Java Code Examples for androidx.core.app.TaskStackBuilder#create()

The following examples show how to use androidx.core.app.TaskStackBuilder#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecondActivity.java    From AndroidAll with Apache License 2.0 6 votes vote down vote up
public void sendNotificationForBack1() {
    Intent resultIntent = new Intent(this, SecondActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // 添加返回栈
    stackBuilder.addParentStack(SecondActivity.class);
    // 添加Intent到栈顶
    stackBuilder.addNextIntent(resultIntent);
    // 创建包含返回栈的pendingIntent
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setContentTitle("from SecondActivity");
    builder.setContentText("test notification press back go main activity");
    builder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(2, builder.build());
}
 
Example 2
Source File: PostItemDetailActivity.java    From mimi-reader with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    // This ID represents the Home or Up button. In the case of this
    // activity, the Up button is shown. Use NavUtils to allow users
    // to navigate up one level in the application structure. For
    // more details, see the Navigation pattern on Android Design:
    //
    // http://developer.android.com/design/patterns/navigation.html#up-vs-back
    //
    final Intent listIntent = new Intent(this, PostItemListActivity.class);
    if (NavUtils.shouldUpRecreateTask(this, listIntent)) {
        final TaskStackBuilder taskStack = TaskStackBuilder.create(this);
        taskStack.addNextIntent(listIntent);
        taskStack.startActivities();
    } else {
        NavUtils.navigateUpTo(this, listIntent);
    }
}
 
Example 3
Source File: OpenAction.java    From opentasks with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Context context, ContentProviderClient contentProviderClient, RowDataSnapshot<TaskContract.Instances> rowSnapshot, Uri taskUri) throws RemoteException, OperationApplicationException
{
    // TODO: check if it's still a good idea to build a custom stack
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(Intent.ACTION_VIEW);
    resultIntent.setData(taskUri);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    context.startActivities(stackBuilder.getIntents());
}
 
Example 4
Source File: AppCompatPreferenceActivity.java    From MHViewer with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called whenever the user chooses to navigate Up within your application's
 * activity hierarchy from the action bar.
 *
 * <p>If a parent was specified in the manifest for this activity or an activity-alias to it,
 * default Up navigation will be handled automatically. See
 * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity
 * along the parent chain requires extra Intent arguments, the Activity subclass
 * should override the method {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}
 * to supply those arguments.</p>
 *
 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and
 * Back Stack</a> from the developer guide and
 * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide
 * for more information about navigating within your app.</p>
 *
 * <p>See the {@link androidx.core.app.TaskStackBuilder} class and the Activity methods
 * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and
 * {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p>
 *
 * @return true if Up navigation completed successfully and this Activity was finished,
 *         false otherwise.
 */
public boolean onSupportNavigateUp() {
    Intent upIntent = getSupportParentActivityIntent();

    if (upIntent != null) {
        if (supportShouldUpRecreateTask(upIntent)) {
            TaskStackBuilder b = TaskStackBuilder.create(this);
            onCreateSupportNavigateUpTaskStack(b);
            onPrepareSupportNavigateUpTaskStack(b);
            b.startActivities();

            try {
                ActivityCompat.finishAffinity(this);
            } catch (IllegalStateException e) {
                // This can only happen on 4.1+, when we don't have a parent or a result set.
                // In that case we should just finish().
                finish();
            }
        } else {
            // This activity is part of the application's task, so simply
            // navigate up to the hierarchical parent activity.
            supportNavigateUpTo(upIntent);
        }
        return true;
    }
    return false;
}
 
Example 5
Source File: StunnelIntentService.java    From SSLSocks with MIT License 5 votes vote down vote up
private void showNotification() {
	NotificationCompat.Builder mBuilder =
			new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
					.setSmallIcon(R.drawable.ic_service_running)
					.setContentTitle(getString(R.string.app_name_full))
					.setContentText(getString(R.string.notification_desc))
					.setCategory(NotificationCompat.CATEGORY_SERVICE)
					.setPriority(NotificationCompat.PRIORITY_DEFAULT)
					.setOngoing(true);
	// Creates an explicit intent for an Activity in your app
	Intent resultIntent = new Intent(this, MainActivity.class);
	// The stack builder object will contain an artificial back stack for the
	// started Activity.
	// This ensures that navigating backward from the Activity leads out of
	// your application to the Home screen.
	TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
	// Adds the back stack for the Intent (but not the Intent itself)
	stackBuilder.addParentStack(MainActivity.class);
	// Adds the Intent that starts the Activity to the top of the stack
	stackBuilder.addNextIntent(resultIntent);
	PendingIntent resultPendingIntent =
			stackBuilder.getPendingIntent(
					0,
					PendingIntent.FLAG_UPDATE_CURRENT
			);
	mBuilder.setContentIntent(resultPendingIntent);

	Intent serviceStopIntent = new Intent(this, ServiceStopReceiver.class);
	serviceStopIntent.setAction(ACTION_STOP);
	PendingIntent serviceStopIntentPending = PendingIntent.getBroadcast(this, 1, serviceStopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
	mBuilder.addAction(R.drawable.ic_stop, "Stop", serviceStopIntentPending);

	// Ensure that the service is a foreground service
	startForeground(NOTIFICATION_ID, mBuilder.build());
}
 
Example 6
Source File: StatusServiceImpl.java    From Status with Apache License 2.0 5 votes vote down vote up
private void startForeground(String packageName, AppData.ActivityData activityData) {
    Intent contentIntent = new Intent(service, MainActivity.class);
    contentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    TaskStackBuilder contentStackBuilder = TaskStackBuilder.create(service);
    contentStackBuilder.addParentStack(MainActivity.class);
    contentStackBuilder.addNextIntent(contentIntent);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(service)
            .setSmallIcon(R.drawable.ic_notification)
            .setColor(ContextCompat.getColor(service, R.color.colorAccent))
            .setContentTitle(service.getString(R.string.app_name))
            .setContentText(activityData.name)
            .setSubText(packageName)
            .setContentIntent(contentStackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

    if (PreferenceData.STATUS_COLOR_AUTO.getValue(service)) {
        Intent colorIntent = new Intent(service, AppSettingActivity.class);
        colorIntent.putExtra(AppSettingActivity.EXTRA_COMPONENT, activityData.packageName + "/" + activityData.name);
        colorIntent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

        builder.addAction(R.drawable.ic_notification_color, service.getString(R.string.action_set_color), PendingIntent.getActivity(service, 1, colorIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    }

    boolean isFullscreen = activityPreference != null && activityPreference.isFullScreen(service);
    Intent visibleIntent = new Intent(service, ActivityFullScreenSettingReceiver.class);
    visibleIntent.putExtra(ActivityFullScreenSettingReceiver.EXTRA_COMPONENT, activityData.packageName + "/" + activityData.name);
    visibleIntent.putExtra(ActivityFullScreenSettingReceiver.EXTRA_FULLSCREEN, isFullscreen);

    builder.addAction(R.drawable.ic_notification_visible, service.getString(isFullscreen ? R.string.action_show_status : R.string.action_hide_status), PendingIntent.getBroadcast(service, 0, visibleIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    Intent settingsIntent = new Intent(service, AppSettingActivity.class);
    settingsIntent.putExtra(AppSettingActivity.EXTRA_COMPONENT, activityData.packageName);
    settingsIntent.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

    builder.addAction(R.drawable.ic_notification_settings, service.getString(R.string.action_app_settings), PendingIntent.getActivity(service, 0, settingsIntent, PendingIntent.FLAG_CANCEL_CURRENT));

    service.startForeground(ID_FOREGROUND, builder.build());
}
 
Example 7
Source File: BaseActivity.java    From privacy-friendly-interval-timer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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
 */
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();
    }
}
 
Example 8
Source File: NotificationObserver.java    From Kore with Apache License 2.0 5 votes vote down vote up
public NotificationObserver(Service service) {
    this.service = service;

    // Create the intent to start the remote when the user taps the notification
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.service);
    stackBuilder.addParentStack(RemoteActivity.class);
    stackBuilder.addNextIntent(new Intent(this.service, RemoteActivity.class));
    remoteStartPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Create the notification channel
    if (Utils.isOreoOrLater()) {
        buildNotificationChannel();
    }
    nothingPlayingNotification = buildNothingPlayingNotification();
}
 
Example 9
Source File: AppCompatPreferenceActivity.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called whenever the user chooses to navigate Up within your application's
 * activity hierarchy from the action bar.
 *
 * <p>If a parent was specified in the manifest for this activity or an activity-alias to it,
 * default Up navigation will be handled automatically. See
 * {@link #getSupportParentActivityIntent()} for how to specify the parent. If any activity
 * along the parent chain requires extra Intent arguments, the Activity subclass
 * should override the method {@link #onPrepareSupportNavigateUpTaskStack(androidx.core.app.TaskStackBuilder)}
 * to supply those arguments.</p>
 *
 * <p>See <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and
 * Back Stack</a> from the developer guide and
 * <a href="{@docRoot}design/patterns/navigation.html">Navigation</a> from the design guide
 * for more information about navigating within your app.</p>
 *
 * <p>See the {@link androidx.core.app.TaskStackBuilder} class and the Activity methods
 * {@link #getSupportParentActivityIntent()}, {@link #supportShouldUpRecreateTask(android.content.Intent)}, and
 * {@link #supportNavigateUpTo(android.content.Intent)} for help implementing custom Up navigation.</p>
 *
 * @return true if Up navigation completed successfully and this Activity was finished,
 *         false otherwise.
 */
public boolean onSupportNavigateUp() {
    Intent upIntent = getSupportParentActivityIntent();

    if (upIntent != null) {
        if (supportShouldUpRecreateTask(upIntent)) {
            TaskStackBuilder b = TaskStackBuilder.create(this);
            onCreateSupportNavigateUpTaskStack(b);
            onPrepareSupportNavigateUpTaskStack(b);
            b.startActivities();

            try {
                ActivityCompat.finishAffinity(this);
            } catch (IllegalStateException e) {
                // This can only happen on 4.1+, when we don't have a parent or a result set.
                // In that case we should just finish().
                finish();
            }
        } else {
            // This activity is part of the application's task, so simply
            // navigate up to the hierarchical parent activity.
            supportNavigateUpTo(upIntent);
        }
        return true;
    }
    return false;
}
 
Example 10
Source File: BigPictureSocialIntentService.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
private NotificationCompat.Builder recreateBuilderWithBigPictureStyle() {

        // Main steps for building a BIG_PICTURE_STYLE notification (for more detailed comments on
        // building this notification, check MainActivity.java):
        //      0. Get your data
        //      1. Build the BIG_PICTURE_STYLE
        //      2. Set up main Intent for notification
        //      3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        //      4. Build and issue the notification

        // 0. Get your data (everything unique per Notification)
        MockDatabase.BigPictureStyleSocialAppData bigPictureStyleSocialAppData =
                MockDatabase.getBigPictureStyleData();

        // 1. Build the BIG_PICTURE_STYLE
        BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                .bigPicture(
                        BitmapFactory.decodeResource(
                                getResources(),
                                bigPictureStyleSocialAppData.getBigImage()))
                .setBigContentTitle(bigPictureStyleSocialAppData.getBigContentTitle())
                .setSummaryText(bigPictureStyleSocialAppData.getSummaryText());

        // 2. Set up main Intent for notification
        Intent mainIntent = new Intent(this, BigPictureSocialMainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(BigPictureSocialMainActivity.class);
        stackBuilder.addNextIntent(mainIntent);

        PendingIntent mainPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        mainIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        // 3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        String replyLabel = getString(R.string.reply_label);
        RemoteInput remoteInput =
                new RemoteInput.Builder(BigPictureSocialIntentService.EXTRA_COMMENT)
                        .setLabel(replyLabel)
                        .setChoices(bigPictureStyleSocialAppData.getPossiblePostResponses())
                        .build();

        PendingIntent replyActionPendingIntent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent(this, BigPictureSocialIntentService.class);
            intent.setAction(BigPictureSocialIntentService.ACTION_COMMENT);
            replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0);

        } else {
            replyActionPendingIntent = mainPendingIntent;
        }

        NotificationCompat.Action replyAction =
                new NotificationCompat.Action.Builder(
                        R.drawable.ic_reply_white_18dp,
                        replyLabel,
                        replyActionPendingIntent)
                        .addRemoteInput(remoteInput)
                        .build();

        // 4. Build and issue the notification
        NotificationCompat.Builder notificationCompatBuilder =
                new NotificationCompat.Builder(getApplicationContext());

        GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

        notificationCompatBuilder
                .setStyle(bigPictureStyle)
                .setContentTitle(bigPictureStyleSocialAppData.getContentTitle())
                .setContentText(bigPictureStyleSocialAppData.getContentText())
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getResources(),
                        R.drawable.ic_person_black_48dp))
                .setContentIntent(mainPendingIntent)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSubText(Integer.toString(1))
                .addAction(replyAction)
                .setCategory(Notification.CATEGORY_SOCIAL)
                .setPriority(Notification.PRIORITY_HIGH)
                .setVisibility(Notification.VISIBILITY_PRIVATE);

        // If the phone is in "Do not disturb mode, the user will still be notified if
        // the sender(s) is starred as a favorite.
        for (String name : bigPictureStyleSocialAppData.getParticipants()) {
            notificationCompatBuilder.addPerson(name);
        }

        return notificationCompatBuilder;
    }
 
Example 11
Source File: StatusServiceImpl.java    From Status with Apache License 2.0 4 votes vote down vote up
public int onStartCommand(Intent intent, int flags, int startId) {
    if (!(boolean) PreferenceData.STATUS_ENABLED.getValue(service)) {
        onDestroy();
        disable(service);
        return Service.START_NOT_STICKY;
    }

    if (intent == null) return Service.START_STICKY;
    String action = intent.getAction();
    if (action == null) return Service.START_STICKY;
    switch (action) {
        case ACTION_CREATE:
            if (statusView == null)
                setUp(false);
            break;
        case ACTION_START:
            setUp(intent.getBooleanExtra(EXTRA_KEEP_OLD, false));
            break;
        case ACTION_STOP:
            onDestroy();
            disable(service);
            break;
        case ACTION_UPDATE:
            if (statusView != null) {
                if (intent.hasExtra(EXTRA_IS_TRANSPARENT) && intent.getBooleanExtra(EXTRA_IS_TRANSPARENT, false))
                    statusView.setTransparent();
                else if (intent.hasExtra(EXTRA_COLOR))
                    statusView.setColor(intent.getIntExtra(EXTRA_COLOR, Color.BLACK));

                statusView.setSystemShowing(intent.getBooleanExtra(EXTRA_IS_SYSTEM_FULLSCREEN, statusView.isSystemShowing()));
                statusView.setFullscreen(intent.getBooleanExtra(EXTRA_IS_FULLSCREEN, isFullscreen()));

                if (intent.hasExtra(EXTRA_PACKAGE) && intent.hasExtra(EXTRA_ACTIVITY)) {
                    AppPreferenceData preference = null;

                    packageName = intent.getStringExtra(EXTRA_PACKAGE);
                    activityData = intent.getParcelableExtra(EXTRA_ACTIVITY);

                    if (activityData != null) {
                        preference = new AppPreferenceData(activityData.packageName + "/" + activityData.name);
                        statusView.setIconColor(preference.getIconColor(service));
                        statusView.setTextColor(preference.getTextColor(service));
                    }

                    if (PreferenceData.STATUS_PERSISTENT_NOTIFICATION.getValue(service)) {
                        packageName = intent.getStringExtra(EXTRA_PACKAGE);
                        activityData = intent.getParcelableExtra(EXTRA_ACTIVITY);
                        activityPreference = preference;

                        startForeground(packageName, activityData);
                    } else service.stopForeground(true);
                }
            }
            return Service.START_STICKY;
    }

    if (PreferenceData.STATUS_PERSISTENT_NOTIFICATION.getValue(service)) {
        if (packageName != null && activityData != null)
            startForeground(packageName, activityData);
        else {
            Intent contentIntent = new Intent(service, MainActivity.class);
            contentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            TaskStackBuilder contentStackBuilder = TaskStackBuilder.create(service);
            contentStackBuilder.addParentStack(MainActivity.class);
            contentStackBuilder.addNextIntent(contentIntent);

            service.startForeground(ID_FOREGROUND, new NotificationCompat.Builder(service)
                    .setSmallIcon(R.drawable.ic_notification)
                    .setColor(ContextCompat.getColor(service, R.color.colorAccent))
                    .setContentTitle(service.getString(R.string.app_name))
                    .setContentIntent(contentStackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT))
                    .build()
            );
        }
    } else service.stopForeground(true);

    return Service.START_STICKY;
}
 
Example 12
Source File: BigPictureSocialIntentService.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
private NotificationCompat.Builder recreateBuilderWithBigPictureStyle() {

        // Main steps for building a BIG_PICTURE_STYLE notification (for more detailed comments on
        // building this notification, check MainActivity.java):
        //      0. Get your data
        //      1. Build the BIG_PICTURE_STYLE
        //      2. Set up main Intent for notification
        //      3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        //      4. Build and issue the notification

        // 0. Get your data (everything unique per Notification)
        MockDatabase.BigPictureStyleSocialAppData bigPictureStyleSocialAppData =
                MockDatabase.getBigPictureStyleData();

        // 1. Build the BIG_PICTURE_STYLE
        BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                .bigPicture(
                        BitmapFactory.decodeResource(
                                getResources(),
                                bigPictureStyleSocialAppData.getBigImage()))
                .setBigContentTitle(bigPictureStyleSocialAppData.getBigContentTitle())
                .setSummaryText(bigPictureStyleSocialAppData.getSummaryText());

        // 2. Set up main Intent for notification
        Intent mainIntent = new Intent(this, BigPictureSocialMainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(BigPictureSocialMainActivity.class);
        stackBuilder.addNextIntent(mainIntent);

        PendingIntent mainPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        mainIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        // 3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        String replyLabel = getString(R.string.reply_label);
        RemoteInput remoteInput =
                new RemoteInput.Builder(BigPictureSocialIntentService.EXTRA_COMMENT)
                        .setLabel(replyLabel)
                        .setChoices(bigPictureStyleSocialAppData.getPossiblePostResponses())
                        .build();

        PendingIntent replyActionPendingIntent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent(this, BigPictureSocialIntentService.class);
            intent.setAction(BigPictureSocialIntentService.ACTION_COMMENT);
            replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0);

        } else {
            replyActionPendingIntent = mainPendingIntent;
        }

        NotificationCompat.Action replyAction =
                new NotificationCompat.Action.Builder(
                        R.drawable.ic_reply_white_18dp,
                        replyLabel,
                        replyActionPendingIntent)
                        .addRemoteInput(remoteInput)
                        .build();

        // 4. Build and issue the notification
        NotificationCompat.Builder notificationCompatBuilder =
                new NotificationCompat.Builder(getApplicationContext());

        GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

        notificationCompatBuilder
                .setStyle(bigPictureStyle)
                .setContentTitle(bigPictureStyleSocialAppData.getContentTitle())
                .setContentText(bigPictureStyleSocialAppData.getContentText())
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getResources(),
                        R.drawable.ic_person_black_48dp))
                .setContentIntent(mainPendingIntent)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSubText(Integer.toString(1))
                .addAction(replyAction)
                .setCategory(Notification.CATEGORY_SOCIAL)
                .setPriority(Notification.PRIORITY_HIGH)
                .setVisibility(Notification.VISIBILITY_PRIVATE);

        // If the phone is in "Do not disturb mode, the user will still be notified if
        // the sender(s) is starred as a favorite.
        for (String name : bigPictureStyleSocialAppData.getParticipants()) {
            notificationCompatBuilder.addPerson(name);
        }

        return notificationCompatBuilder;
    }
 
Example 13
Source File: MageApplication.java    From mage-android with Apache License 2.0 4 votes vote down vote up
public void createNotification() {
	boolean tokenExpired = UserUtility.getInstance(getApplicationContext()).isTokenExpired();

    // Creates an explicit intent for an Activity in your app
	Intent resultIntent = new Intent(this, LoginActivity.class);
	// The stack builder object will contain an artificial back stack for the
	// started Activity.
	// This ensures that navigating backward from the Activity leads out of
	// your application to the Home screen.
	TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
	// Adds the back stack for the Intent (but not the Intent itself)
	stackBuilder.addParentStack(LoginActivity.class);
	// Adds the Intent that starts the Activity to the top of the stack
	stackBuilder.addNextIntent(resultIntent);
	PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

	String noticationMsg = tokenExpired ? "Your token has expired, please tap to login." : "You are currently logged into MAGE.";

	Notification accountNotification = new NotificationCompat.Builder(this, MAGE_NOTIFICATION_CHANNEL_ID)
			.setOngoing(true)
			.setSortKey("1")
			.setContentTitle("MAGE")
			.setContentText(noticationMsg)
			.setGroup(MAGE_NOTIFICATION_GROUP)
			.setContentIntent(resultPendingIntent)
			.setSmallIcon(R.drawable.ic_wand_white_50dp)
			.addAction(R.drawable.ic_power_settings_new_white_24dp, "Logout", getLogoutPendingIntent())
			.build();

	NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle()
			.addLine(noticationMsg)
			.setBigContentTitle("MAGE");

	if (isReportingLocation()) {
		style.addLine("MAGE is currently reporting your location.");
	}

	// This summary notification supports "grouping" on versions older that Android.N
	Notification summaryNotification = new NotificationCompat.Builder(this, MAGE_NOTIFICATION_CHANNEL_ID)
			.setGroupSummary(true)
			.setGroup(MAGE_NOTIFICATION_GROUP)
			.setContentTitle("MAGE")
			.setContentText(noticationMsg)
			.setSmallIcon(R.drawable.ic_wand_white_50dp)
			.setStyle(style)
			.setContentIntent(resultPendingIntent)
			.addAction(R.drawable.ic_power_settings_new_white_24dp, "Logout", getLogoutPendingIntent())
			.build();

	NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
	notificationManager.notify(MAGE_ACCOUNT_NOTIFICATION_ID, accountNotification);
	notificationManager.notify(MAGE_SUMMARY_NOTIFICATION_ID, summaryNotification);
}
 
Example 14
Source File: GeofenceTransitionsJobIntentService.java    From location-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 */
private void sendNotification(String notificationDetails) {
    // Get an instance of the Notification manager
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Android O requires a Notification Channel.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.app_name);
        // Create the channel for the notification
        NotificationChannel mChannel =
                new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);

        // Set the Notification Channel for the Notification Manager.
        mNotificationManager.createNotificationChannel(mChannel);
    }

    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.drawable.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_launcher))
            .setColor(Color.RED)
            .setContentTitle(notificationDetails)
            .setContentText(getString(R.string.geofence_transition_notification_text))
            .setContentIntent(notificationPendingIntent);

    // Set the Channel ID for Android O.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setChannelId(CHANNEL_ID); // Channel ID
    }

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}
 
Example 15
Source File: Utils.java    From location-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Posts a notification in the notification bar when a transition is detected.
 * If the user clicks the notification, control goes to the MainActivity.
 */
static void sendNotification(Context context, String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(context, MainActivity.class);

    notificationIntent.putExtra("from_notification", true);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    // Define the notification settings.
    builder.setSmallIcon(R.mipmap.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                    R.mipmap.ic_launcher))
            .setColor(Color.RED)
            .setContentTitle("Location update")
            .setContentText(notificationDetails)
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    // Android O requires a Notification Channel.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = context.getString(R.string.app_name);
        // Create the channel for the notification
        NotificationChannel mChannel =
                new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT);

        // Set the Notification Channel for the Notification Manager.
        mNotificationManager.createNotificationChannel(mChannel);

        // Channel ID
        builder.setChannelId(CHANNEL_ID);
    }

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}