Java Examples

The following examples show how to use 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:    From linphone-android with GNU General Public License v3.0 6 votes vote down vote up
public static Notification createSimpleNotification(
        Context context, String title, String text, PendingIntent intent) {
    return new Notification.Builder(
                    context, context.getString(R.string.notification_channel_id))
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
Example #2
Source File:    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void listing11_24(Context context, NotificationCompat.Builder builder) {
  Uri emailUri = Uri.parse("[email protected]");

  // Listing 11-24: Adding a Notification action
  Intent deleteAction = new Intent(context, DeleteBroadcastReceiver.class);

  PendingIntent deleteIntent = PendingIntent.getBroadcast(context, 0,
    deleteAction, PendingIntent.FLAG_UPDATE_CURRENT);

    new NotificationCompat.Action.Builder(
Example #3
Source File:    From Shelter with Do What The F*ck You Want To Public License 6 votes vote down vote up
private void actionInstallPackageQ(Uri uri) throws IOException {
    PackageInstaller pi = getPackageManager().getPackageInstaller();
    PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
    int sessionId = pi.createSession(params);

    // Show the progress dialog first
    pi.registerSessionCallback(new InstallationProgressListener(this, pi, sessionId));

    PackageInstaller.Session session = pi.openSession(sessionId);
    doInstallPackageQ(uri, session, () -> {
        // We have finished piping the streams, show the progress as 10%

        // Commit the session
        Intent intent = new Intent(this, DummyActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
Example #4
Source File:    From json2notification with Apache License 2.0 6 votes vote down vote up
public void testSerialize() {
    Intent intent = new Intent(Intent.ACTION_MAIN);

    Notification notification = new NotificationCompat.Builder(context)
        .setContentTitle("Hello World!")
        .setContentText("Hello World!")
        .setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))

    String json = Json2Notification.from(context).with(notification).serialize();
Example #5
Source File:    From 365browser with Apache License 2.0 6 votes vote down vote up
     * Returns the PendingIntent for completing |action| on the notification identified by the data
     * in the other parameters.
     * All parameters set here should also be set in
     * {@link NotificationJobService#getJobExtrasFromIntent(Intent)}.
     * @param context An appropriate context for the intent class and broadcast.
     * @param action The action this pending intent will represent.
     * @param notificationId The id of the notification.
     * @param origin The origin to whom the notification belongs.
     * @param profileId Id of the profile to which the notification belongs.
     * @param incognito Whether the profile was in incognito mode.
     * @param tag The tag of the notification. May be NULL.
     * @param webApkPackage The package of the WebAPK associated with the notification. Empty if
*        the notification is not associated with a WebAPK.
     * @param actionIndex The zero-based index of the action button, or -1 if not applicable.
    private PendingIntent makePendingIntent(Context context, String action, String notificationId,
            String origin, String profileId, boolean incognito, @Nullable String tag,
            String webApkPackage, int actionIndex) {
        Uri intentData = makeIntentData(notificationId, origin, actionIndex);
        Intent intent = new Intent(action, intentData);
        intent.setClass(context, NotificationService.Receiver.class);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_ID, notificationId);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ORIGIN, origin);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_ID, profileId);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_INCOGNITO, incognito);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_TAG, tag);
                NotificationConstants.EXTRA_NOTIFICATION_INFO_WEBAPK_PACKAGE, webApkPackage);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ACTION_INDEX, actionIndex);

        return PendingIntent.getBroadcast(
                context, PENDING_INTENT_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Example #6
Source File:    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private static Object readObj(String type, Parcel in) {
    switch (getBaseType(type)) {
        case FORMAT_SLICE:
            return Slice.CREATOR.createFromParcel(in);
        case FORMAT_TEXT:
            return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
        case FORMAT_IMAGE:
            return Icon.CREATOR.createFromParcel(in);
        case FORMAT_ACTION:
            return new Pair<>(
        case FORMAT_INT:
            return in.readInt();
        case FORMAT_TIMESTAMP:
            return in.readLong();
            return RemoteInput.CREATOR.createFromParcel(in);
        case FORMAT_BUNDLE:
            return Bundle.CREATOR.createFromParcel(in);
    throw new RuntimeException("Unsupported type " + type);
Example #7
Source File:    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public PendingIntent getMarkAsReadIntent(Context context, int notificationId) {
  long[] threadArray = new long[threads.size()];
  int    index       = 0;

  for (long thread : threads) {
    Log.i(TAG, "Added thread: " + thread);
    threadArray[index++] = thread;

  Intent intent = new Intent(MarkReadReceiver.CLEAR_ACTION);
  intent.setClass(context, MarkReadReceiver.class);
  intent.putExtra(MarkReadReceiver.THREAD_IDS_EXTRA, threadArray);
  intent.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, notificationId);

  return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Example #8
Source File:    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
 * Show a notification while this service is running.
private void showNotification() {
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.remote_service_started);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.stat_sample, text,

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, Controller.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
                   text, contentIntent);

    // Send the notification.
    // We use a string id because it is a unique number.  We use it later to cancel.
    mNM.notify(R.string.remote_service_started, notification);
Example #9
Source File:    From android with Apache License 2.0 6 votes vote down vote up
private void addPendingIntents(RemoteViews rv, boolean isPlaying, MediaInfo info) {
    Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
    PendingIntent playbackPendingIntent = PendingIntent
            .getBroadcast(this, 0, playbackIntent, 0);

    Intent stopIntent = new Intent(ACTION_STOP);
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);

    rv.setOnClickPendingIntent(, playbackPendingIntent);
    rv.setOnClickPendingIntent(, stopPendingIntent);

    if (isPlaying) {
        if (info.getStreamType() == MediaInfo.STREAM_TYPE_LIVE) {
            rv.setImageViewResource(, R.drawable.ic_av_stop_sm_dark);
        } else {
            rv.setImageViewResource(, R.drawable.ic_av_pause_sm_dark);

    } else {
        rv.setImageViewResource(, R.drawable.ic_av_play_sm_dark);
Example #10
Source File:    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private void sendNotification(String body, String title) {
    Intent intent = new Intent(this, Home.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Notification.Builder notificationBuilder = (Notification.Builder) new Notification.Builder(this)

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */,;
Example #11
Source File:    From fanfouapp-opensource with Apache License 2.0 6 votes vote down vote up
private static void showMentionMoreNotification(final Context context,
        final int count) {
    if (AppContext.DEBUG) {
                "showMentionMoreNotification count=" + count);
    final String title = "饭否消息";
    final String message = "收到" + count + "条提到你的消息";
    final Intent intent = new Intent(context, HomePage.class);
    intent.setAction("DUMY_ACTION " + System.currentTimeMillis());
    intent.putExtra(Constants.EXTRA_PAGE, 1);
    final PendingIntent contentIntent = PendingIntent.getActivity(context,
            0, intent, 0);
            NotificationReceiver.NOTIFICATION_ID_MENTION, context,
            contentIntent, title, message, R.drawable.ic_notify_mention);
Example #12
Source File:    From android-proguards with Apache License 2.0 6 votes vote down vote up
public static CustomTabsIntent.Builder getCustomTabIntent(@NonNull Context context,
                                                          @NonNull Story story,
                                                          @Nullable CustomTabsSession session) {
    Intent upvoteStory = new Intent(context, UpvoteStoryService.class);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, upvoteStory, 0);
    return new CustomTabsIntent.Builder(session)
            .setToolbarColor(ContextCompat.getColor(context, R.color.designer_news))
Example #13
Source File:    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void listing15_8() {
  if (
      .checkSelfPermission(this, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED ||
        .checkSelfPermission(this, ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED) {

    // Listing 15-8: Requesting location updates using a Pending Intent
    FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    LocationRequest request = new LocationRequest()
                                .setInterval(60000 * 10) // Update every 10 minutes.

    final int locationUpdateRC = 0;
    int flags = PendingIntent.FLAG_UPDATE_CURRENT;

    Intent intent = new Intent(this, MyLocationUpdateReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, locationUpdateRC, intent, flags);

    fusedLocationClient.requestLocationUpdates(request, pendingIntent);
Example #14
Source File:    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private static void disableMotionTrackingDueToErrors(Context context) {
    final long requested = getInternalPrefsLong(REQUESTED);
    final long received = getInternalPrefsLong(RECEIVED);
    Home.toaststaticnext("DISABLED MOTION TRACKING DUE TO FAILURES! See Error Log!");
    final String msg = "Had to disable motion tracking feature as it did not seem to be working and may be incompatible with your phone. Please report this to the developers using the send logs feature: " + requested + " vs " + received + " " + JoH.getDeviceDetails();, msg);
    UserError.Log.ueh(TAG, msg);
    Pref.setBoolean("motion_tracking_enabled", false);
    evaluateRequestReceivedCounters(true, context); // mark for disable
    setInternalPrefsLong(REQUESTED, 0);
    setInternalPrefsLong(RECEIVED, 0);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Intent intent = new Intent(xdrip.getAppContext(), ErrorsActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(xdrip.getAppContext(), 0 /* Request code */, intent,
    builder.setContentText("Shut down motion detection! See Error Logs - Please report to developer" + JoH.dateTimeText(JoH.tsl()));
    builder.setContentTitle("Problem with motion detection!");
Example #15
Source File:    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Notification buildAlertGroupSummaryNotification(Context context,
                                                               Location location,
                                                               Alert alert,
                                                               int notificationId) {
    return new NotificationCompat.Builder(context, GeometricWeather.NOTIFICATION_CHANNEL_ID_ALERT)
                                    ? R.color.lightPrimary_5
                                    : R.color.darkPrimary_5
Example #16
Source File:    From zhangshangwuda with Apache License 2.0 6 votes vote down vote up
public void setNextAlarm(Context context) {
	AlarmManager aManager = (AlarmManager) context
	Calendar tcalendar = Calendar.getInstance();
	tcalendar.add(Calendar.DAY_OF_YEAR, +1);
	tcalendar.set(Calendar.HOUR_OF_DAY, 0);
	tcalendar.set(Calendar.MINUTE, 19);
	tcalendar.set(Calendar.SECOND, 19);
	Intent intent = new Intent(context, LessonsWidgetProvider_4_1.class);
	PendingIntent work = PendingIntent.getBroadcast(context, 0, intent,
	aManager.set(AlarmManager.RTC, tcalendar.getTimeInMillis(), work);
	Log.v("zq.whu.zhangshangwuda.ui.lessons.widget_4_1", "设置定时更新成功");
Example #17
Source File:    From gsn with GNU General Public License v3.0 6 votes vote down vote up
public void sendBasicNotification(String notif) {

		NotificationManager nm = (NotificationManager) StaticData.globalContext.getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = R.drawable.alert_dark_frame;
		CharSequence contentTitle = "TinyGSN notification";
		CharSequence tickerText = notif;
		long when = System.currentTimeMillis();

		NotificationCompat.Builder mBuilder =
				new NotificationCompat.Builder(StaticData.globalContext)

		Intent notificationIntent = new Intent(StaticData.globalContext, ActivityViewData.class);

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(StaticData.globalContext);

		PendingIntent contentIntent = PendingIntent.getActivity(StaticData.globalContext, 0,
				                                                       notificationIntent, 0);
Example #18
Source File:    From Shipr-Community-Android with GNU General Public License v3.0 5 votes vote down vote up
private void Notify() {
    Intent intent = new Intent(context, MainActivity.class);
    final PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) Calendar.getInstance().getTimeInMillis(), intent, 0);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(channel_Id + " channel");

    for (int i = (messages.size() > 5 ? messages.size() - 5 : 0); i < messages.size(); i++) {
        DeveloperMessage message = messages.get(i);
        String line = message.getName() + ":\t" + message.getText();

    int count = messages.size();
    String summary = count + (count > 1 ? " new messages" : " new message");
    //Todo: change the small icon with an xml icon
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel_Id)
            .setSmallIcon(R.mipmap.ic_launcher) //Todo: change the small icon with an xml icon
            .setContentTitle(channel_Id + " channel")

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = new, "Maker Toolbox", NotificationManager.IMPORTANCE_DEFAULT);

Example #19
Source File:    From Android-Scanner-Compat-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
 * When scanning with PendingIntent on Android Oreo or newer, the app may get killed
 * by the system. To stop scanning, the same {@link PendingIntent} must be used that was
 * used to start scanning. Comparing intents is done using {@link Intent#filterEquals(Intent)}.
 * @return The PendingIntent that is to be used to stop scanning. It is equal to one used to
 * start scanning if the callbackIntent is equal to one used to start scanning.
private PendingIntent createStoppingPendingIntent(@NonNull final Context context,
												  @NonNull final PendingIntent callbackIntent) {
	// The PendingIntent ID is derived from the user's callbackIntent.
	final int id = callbackIntent.hashCode();

	// Since Android 8 it has to be an explicit intent
	final Intent intent = new Intent(context, PendingIntentReceiver.class);

	return PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Example #20
Source File:    From PowerSwitch_Android with GNU General Public License v3.0 5 votes vote down vote up
private void enableTagWriteMode() {
    IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
    IntentFilter[] mWriteTagFilters = new IntentFilter[]{intentFilter};
    PendingIntent nfcPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    nfcAdapter.enableForegroundDispatch(this, nfcPendingIntent, mWriteTagFilters, null);
Example #21
Source File:    From Android_framework with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void uncaughtException(Thread thread, Throwable ex) {
    Intent intent = new Intent();
    PendingIntent restartIntent = PendingIntent.getActivity(getInstance(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent);

Example #22
Source File:    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private void initializeServiceIntent() {
    if (serviceIntent == null) {
        synchronized (this) {
            if (serviceIntent == null) {
                serviceIntent = PendingIntent.getService(this, Constants.MISSED_READING_SERVICE_ID, new Intent(this, this.getClass()), 0);
Example #23
Source File:    From goprohero with MIT License 5 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    Intent displayIntent = new Intent(context, MyDisplayActivity.class);
    String text = intent.getStringExtra(CONTENT_KEY);
    Notification notification = new Notification.Builder(context)
            .extend(new Notification.WearableExtender()
                    .setDisplayIntent(PendingIntent.getActivity(context, 0, displayIntent,
    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);

    Toast.makeText(context, context.getString(R.string.notification_posted), Toast.LENGTH_SHORT).show();
Example #24
Source File:    From tickmate with GNU General Public License v3.0 5 votes vote down vote up
    public void onReceive(Context context, Intent intent) {

        Boolean enabled = PreferenceManager.getDefaultSharedPreferences(context)
                                           .getBoolean("notification-enabled", false);

        Log.d(TAG, "Alarm received; enabled=" + enabled.toString());

        if (enabled) {

            //Locale locale = Locale.getDefault();
            //Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, locale)

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(context)
            Intent resultIntent = new Intent(context, Tickmate.class);

            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationManager mNotificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
Example #25
Source File:    From talk-android with MIT License 5 votes vote down vote up
private void schedulePingAlarm() {
    Intent intentAlarm = new Intent();
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, HEARTBEAT_ALARM, intentAlarm,
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        am.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + pingInterval, pendingIntent);
    } else {
        am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + pingInterval, pendingIntent);
Example #26
Source File:    From UniLocalNotification with MIT License 5 votes vote down vote up
 * Cancel registered notification
 * @param requestCode Pending intent request code you want to cancel
public static void cancel(int requestCode) {

    Context context = getContext();

    // get pending intent
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, NotificationReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // cancel it
Example #27
Source File:    From android-Timer with Apache License 2.0 5 votes vote down vote up
private void deleteTimer() {

    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(Constants.ACTION_SHOW_ALARM, null, this,
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,

    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Timer deleted.");
Example #28
Source File:    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void registerAlarmManager( long duration ) {
    AlarmManager alarmManager = (AlarmManager) getSystemService( Context.ALARM_SERVICE );
    Intent intent = new Intent( ACTION_SHOW_ALARM, null, this, TimerService.class );
    PendingIntent pendingIntent = PendingIntent.getService( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT );

    long time = System.currentTimeMillis() + duration;
    alarmManager.setExact( AlarmManager.RTC_WAKEUP, time, pendingIntent );
Example #29
Source File:    From 365browser with Apache License 2.0 5 votes vote down vote up
static void sendChooserIntent(boolean saveLastUsed, Activity activity,
                              Intent sharingIntent,
                              @Nullable TargetChosenCallback callback) {
    synchronized (LOCK) {
        if (sTargetChosenReceiveAction == null) {
            sTargetChosenReceiveAction = activity.getPackageName() + "/"
                    + TargetChosenReceiver.class.getName() + "_ACTION";
        Context context = activity.getApplicationContext();
        if (sLastRegisteredReceiver != null) {
            // Must cancel the callback (to satisfy guarantee that exactly one method of
            // TargetChosenCallback is called).
            // TODO(mgiuca): This should be called immediately upon cancelling the chooser,
            // not just when the next share takes place (
        sLastRegisteredReceiver = new TargetChosenReceiver(saveLastUsed, callback);
                sLastRegisteredReceiver, new IntentFilter(sTargetChosenReceiveAction));

    Intent intent = new Intent(sTargetChosenReceiveAction);
    intent.putExtra(EXTRA_RECEIVER_TOKEN, sLastRegisteredReceiver.hashCode());
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(activity, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT);
    Intent chooserIntent = Intent.createChooser(sharingIntent,
    if (sFakeIntentReceiverForTesting != null) {
    fireIntent(activity, chooserIntent);
Example #30
Source File:    From android-tv-leanback with Apache License 2.0 5 votes vote down vote up
private void scheduleRecommendationUpdate(Context context) {

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent recommendationIntent = new Intent(context, RecommendationsService.class);
        PendingIntent alarmIntent = PendingIntent.getService(context, 0, recommendationIntent, 0);