Java Code Examples for android.app.Notification#FLAG_FOREGROUND_SERVICE

The following examples show how to use android.app.Notification#FLAG_FOREGROUND_SERVICE . 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: NotificationUtils.java    From freemp with Apache License 2.0 6 votes vote down vote up
public static Notification getNotification(Context context, PendingIntent pendingIntent, ClsTrack track, boolean isPlaying) {

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
        notificationBuilder
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.freemp)
                .setContentTitle(track != null ? track.getArtist() : "")
                .setContentText(track != null ? track.getTitle() : "");
        Notification notification = notificationBuilder.build();
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        notification.contentIntent = pendingIntent;
        if (track != null) {
            notification.contentView = getNotificationViews(track, context, isPlaying, R.layout.notification);
        } else {
            //notification.contentView = null;
            //notification.setLatestEventInfo(context, "", "", pendingIntent);
            notification = null;
        }

        return notification;
    }
 
Example 2
Source File: SmbService.java    From DanDanPlayForAndroid with MIT License 6 votes vote down vote up
private Notification buildNotification(){
    Intent intent = new Intent(this, SmbDeviceActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent,0);

    Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("弹弹play")
            .setContentText("已开启SMB服务")
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setWhen(System.currentTimeMillis())
            .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
            .setVibrate(new long[]{0})
            .setSound(null);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setChannelId("com.xyoye.dandanplay.smbservice.playchannel");
    }
    Notification notify = builder.build();
    notify.flags = Notification.FLAG_FOREGROUND_SERVICE ;
    return notify;
}
 
Example 3
Source File: TorrentService.java    From DanDanPlayForAndroid with MIT License 6 votes vote down vote up
/**
 * 创建通知
 */
private Notification buildNotification() {
    Notification.Builder foregroundNotify = new Notification.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("DanDanPlay后台下载")
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setContentIntent(null)
            .setWhen(System.currentTimeMillis())
            .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
            .setVibrate(new long[]{0})
            .setSound(null);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        foregroundNotify.setChannelId("com.xyoye.dandanplay.TorrentService.DownloadChannel");
    }

    String content =
            "速度: " +
            "↓" + CommonUtils.convertFileSize(TorrentEngine.getInstance().getDownloadRate()) + "/s ." +
            "↑" + CommonUtils.convertFileSize(TorrentEngine.getInstance().getUploadRate()) + "/s";
    foregroundNotify.setContentText(content);
    Notification notify = foregroundNotify.build();
    notify.flags = Notification.FLAG_FOREGROUND_SERVICE;
    return notify;
}
 
Example 4
Source File: LocationsServiceBase.java    From edslite with GNU General Public License v2.0 6 votes vote down vote up
private Notification getServiceRunningNotification()
{
       Intent i = new Intent(this, FileManagerActivity.class);
       i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CompatHelper.getServiceRunningNotificationsChannelId(this))
               .setContentTitle(getString(R.string.eds_service_is_running))
               .setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_notification_new : R.drawable.ic_notification)
               .setContentText("")
               .setContentIntent(PendingIntent.getActivity(this, 0, i, 0))
               .setOngoing(true)
			.addAction(
					R.drawable.ic_action_cancel,
					getString(R.string.close_all_containers),
					PendingIntent.getActivity(
							this,
							0,
							new Intent(this, CloseLocationsActivity.class),
							PendingIntent.FLAG_UPDATE_CURRENT
					)
			);
       Notification n = builder.build();
       n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_FOREGROUND_SERVICE;
	return n;
}
 
Example 5
Source File: MountApplication.java    From Mount with GNU General Public License v3.0 5 votes vote down vote up
public List<String> getForegroundServiceList() {
    List<String> list = new ArrayList<>();

    if (mNotificationService != null) {
        StatusBarNotification[] notifications = mNotificationService.getActiveNotifications();
        for (StatusBarNotification notification : notifications) {
            int mask = Notification.FLAG_FOREGROUND_SERVICE;
            if ((notification.getNotification().flags & mask) != 0) {
                list.add(notification.getPackageName());
            }
        }
    }

    return list;
}
 
Example 6
Source File: NotificationSubjectTest.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Test
public void flags() {
  Notification notification = new Notification();
  notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_FOREGROUND_SERVICE;

  assertThat(notification).hasFlags(Notification.FLAG_AUTO_CANCEL);
  assertThat(notification)
      .doesNotHaveFlags(Notification.FLAG_NO_CLEAR | Notification.FLAG_INSISTENT);
}
 
Example 7
Source File: DownloadNotificationService.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Checks to see if the summary notification is alone and, if so, hides it.  If the summary
 * notification thinks it's in the foreground, this will start the service with the goal of
 * shutting it down.  That is because if the service is in the foreground it's not possible to
 * stop it through the notification manager.
 * @param removedNotificationId The id of the notification that was just removed or {@code -1}
 *                              if this does not apply.
 */
@TargetApi(Build.VERSION_CODES.M)
public static void hideDanglingSummaryNotification(Context context, int removedNotificationId) {
    if (!useForegroundService()) return;

    NotificationManager manager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (hasDownloadNotifications(manager, removedNotificationId)) return;

    StatusBarNotification summary = getSummaryNotification(manager);
    if (summary == null) return;

    boolean isForeground =
            (summary.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE) != 0;

    if (BrowserStartupController.get(LibraryProcessType.PROCESS_BROWSER)
                    .isStartupSuccessfullyCompleted()) {
        RecordHistogram.recordBooleanHistogram(
                "MobileDownload.Notification.FixingSummaryLeak", isForeground);
    }

    if (isForeground) {
        // If it is a foreground notification, we are in a bad state.  We don't have any
        // other download notifications, but we can't close the summary.  Try to start
        // up the service and quit through that path?
        startDownloadNotificationService(context, new Intent(ACTION_DOWNLOAD_FAIL_SAFE));
    } else {
        manager.cancel(NotificationConstants.NOTIFICATION_ID_DOWNLOAD_SUMMARY);
    }
}
 
Example 8
Source File: NotificationUtils.java    From IdealMedia with Apache License 2.0 5 votes vote down vote up
public static Notification getNotification(Context context, PendingIntent pendingIntent, Track track, boolean isPlaying) {

        Notification notification = new Notification();
        if (track != null) {
            notification.contentView = getNotificationViews(track, context, isPlaying);
        }
        else {
            notification.setLatestEventInfo(context, "", "", pendingIntent);
        }
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        notification.contentIntent = pendingIntent;
        notification.icon = R.drawable.ic_notification;

        return notification;
    }
 
Example 9
Source File: BaseBuilder.java    From NotifyUtil with Apache License 2.0 5 votes vote down vote up
public void show(){
    build();
    Notification notification = cBuilder.build();
    if(forgroundService){
        notification.flags = Notification.FLAG_FOREGROUND_SERVICE;
    }

  NotifyUtil.notify(id,notification);
}
 
Example 10
Source File: NotificationHelper.java    From background-geolocation-android with Apache License 2.0 5 votes vote down vote up
public Notification getNotification(String title, String text, String largeIcon, String smallIcon, String color) {
    Context appContext = mContext.getApplicationContext();

    // Build a Notification required for running service in foreground.
    NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NotificationHelper.SERVICE_CHANNEL_ID);

    builder.setContentTitle(title);
    builder.setContentText(text);
    if (smallIcon != null && !smallIcon.isEmpty()) {
        builder.setSmallIcon(mResolver.getDrawable(smallIcon));
    } else {
        builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
    }
    if (largeIcon != null && !largeIcon.isEmpty()) {
        builder.setLargeIcon(BitmapFactory.decodeResource(appContext.getResources(), mResolver.getDrawable(largeIcon)));
    }
    if (color != null && !color.isEmpty()) {
        builder.setColor(this.parseNotificationIconColor(color));
    }

    // Add an onclick handler to the notification
    String packageName = appContext.getPackageName();
    Intent launchIntent = appContext.getPackageManager().getLaunchIntentForPackage(packageName);
    if (launchIntent != null) {
        // NOTICE: testing apps might not have registered launch intent
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(appContext, 0, launchIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(contentIntent);
    }

    Notification notification = builder.build();
    notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;

    return notification;
}
 
Example 11
Source File: NotificationUsageStats.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public void countApiUse(NotificationRecord record) {
    final Notification n = record.getNotification();
    if (n.actions != null) {
        numWithActions++;
    }

    if ((n.flags & Notification.FLAG_FOREGROUND_SERVICE) != 0) {
        numForegroundService++;
    }

    if ((n.flags & Notification.FLAG_ONGOING_EVENT) != 0) {
        numOngoing++;
    }

    if ((n.flags & Notification.FLAG_AUTO_CANCEL) != 0) {
        numAutoCancel++;
    }

    if ((n.defaults & Notification.DEFAULT_SOUND) != 0 ||
            (n.defaults & Notification.DEFAULT_VIBRATE) != 0 ||
            n.sound != null || n.vibrate != null) {
        numInterrupt++;
    }

    switch (n.visibility) {
        case Notification.VISIBILITY_PRIVATE:
            numPrivate++;
            break;
        case Notification.VISIBILITY_SECRET:
            numSecret++;
            break;
    }

    if (record.stats.isNoisy) {
        noisyImportance.increment(record.stats.requestedImportance);
    } else {
        quietImportance.increment(record.stats.requestedImportance);
    }
    finalImportance.increment(record.getImportance());

    final Set<String> names = n.extras.keySet();
    if (names.contains(Notification.EXTRA_BIG_TEXT)) {
        numWithBigText++;
    }
    if (names.contains(Notification.EXTRA_PICTURE)) {
        numWithBigPicture++;
    }
    if (names.contains(Notification.EXTRA_LARGE_ICON)) {
        numWithLargeIcon++;
    }
    if (names.contains(Notification.EXTRA_TEXT_LINES)) {
        numWithInbox++;
    }
    if (names.contains(Notification.EXTRA_MEDIA_SESSION)) {
        numWithMediaSession++;
    }
    if (names.contains(Notification.EXTRA_TITLE) &&
            !TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_TITLE))) {
        numWithTitle++;
    }
    if (names.contains(Notification.EXTRA_TEXT) &&
            !TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_TEXT))) {
        numWithText++;
    }
    if (names.contains(Notification.EXTRA_SUB_TEXT) &&
            !TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_SUB_TEXT))) {
        numWithSubText++;
    }
    if (names.contains(Notification.EXTRA_INFO_TEXT) &&
            !TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_INFO_TEXT))) {
        numWithInfoText++;
    }
}
 
Example 12
Source File: NotificationService.java    From an2linuxclient with GNU General Public License v3.0 4 votes vote down vote up
private boolean isForeground(int flags) {
    return (flags & Notification.FLAG_FOREGROUND_SERVICE) != 0;
}
 
Example 13
Source File: NotificationService.java    From an2linuxclient with GNU General Public License v3.0 4 votes vote down vote up
private boolean isForeground(int flags) {
    return (flags & Notification.FLAG_FOREGROUND_SERVICE) != 0;
}
 
Example 14
Source File: BackgroundLocationUpdateService.java    From cordova-background-geolocation-services with Apache License 2.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "Received start id " + startId + ": " + intent);
    if (intent != null) {

        distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter"));
        desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy"));

        interval             = Integer.parseInt(intent.getStringExtra("interval"));
        fastestInterval      = Integer.parseInt(intent.getStringExtra("fastestInterval"));
        aggressiveInterval   = Integer.parseInt(intent.getStringExtra("aggressiveInterval"));
        activitiesInterval   = Integer.parseInt(intent.getStringExtra("activitiesInterval"));

        isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging"));
        notificationTitle = intent.getStringExtra("notificationTitle");
        notificationText = intent.getStringExtra("notificationText");

        useActivityDetection = Boolean.parseBoolean(intent.getStringExtra("useActivityDetection"));


        // Build the notification / pending intent
        Intent main = new Intent(this, BackgroundLocationServicesPlugin.class);
        main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main,  PendingIntent.FLAG_UPDATE_CURRENT);

        Context context = getApplicationContext();

        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationText);
        builder.setSmallIcon(context.getApplicationInfo().icon);

        Bitmap bm = BitmapFactory.decodeResource(context.getResources(),
                                       context.getApplicationInfo().icon);

        float mult = getImageFactor(getResources());
        Bitmap scaledBm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth()*mult), (int)(bm.getHeight()*mult), false);

        if(scaledBm != null) {
          builder.setLargeIcon(scaledBm);
        }

        // Integer resId = getPluginResource("location_icon");
        //
        // //Scale our location_icon.png for different phone resolutions
        // //TODO: Get this icon via a filepath from the user
        // if(resId != 0) {
        //     Bitmap bm = BitmapFactory.decodeResource(getResources(), resId);
        //
        //     float mult = getImageFactor(getResources());
        //     Bitmap scaledBm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth()*mult), (int)(bm.getHeight()*mult), false);
        //
        //     if(scaledBm != null) {
        //         builder.setLargeIcon(scaledBm);
        //     }
        // } else {
        //     Log.w(TAG, "Could NOT find Resource for large icon");
        // }

        //Make clicking the event link back to the main cordova activity
        builder.setContentIntent(pendingIntent);
        setClickEvent(builder);

        Notification notification;
        if (android.os.Build.VERSION.SDK_INT >= 16) {
            notification = buildForegroundNotification(builder);
        } else {
            notification = buildForegroundNotificationCompat(builder);
        }

        notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
        startForeground(startId, notification);
    }

    // Log.i(TAG, "- url: " + url);
    // Log.i(TAG, "- params: "  + params.toString());
    Log.i(TAG, "- interval: "             + interval);
    Log.i(TAG, "- fastestInterval: "      + fastestInterval);

    Log.i(TAG, "- distanceFilter: "     + distanceFilter);
    Log.i(TAG, "- desiredAccuracy: "    + desiredAccuracy);
    Log.i(TAG, "- isDebugging: "        + isDebugging);
    Log.i(TAG, "- notificationTitle: "  + notificationTitle);
    Log.i(TAG, "- notificationText: "   + notificationText);
    Log.i(TAG, "- useActivityDetection: "   + useActivityDetection);
    Log.i(TAG, "- activityDetectionInterval: "   + activitiesInterval);

    //We want this service to continue running until it is explicitly stopped
    return START_REDELIVER_INTENT;
}
 
Example 15
Source File: DownloadNotificationService.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Check all current notifications and hide the summary notification if we have no downloads
 * notifications left.  On Android if the user swipes away the last download notification the
 * summary will be dismissed.  But if the last downloads notification is dismissed via
 * {@link NotificationManager#cancel(int)}, the summary will remain, so we need to check and
 * manually remove it ourselves.
 * @param notificationIdToIgnore Canceling a notification and querying for the current list of
 *                               active notifications isn't synchronous.  Pass a notification id
 *                               here if there is a notification that should be assumed gone.
 *                               Or pass -1 if no notification fits that criteria.
 */
@TargetApi(Build.VERSION_CODES.M)
boolean hideSummaryNotificationIfNecessary(int notificationIdToIgnore) {
    if (!useForegroundService()) return false;
    if (mDownloadsInProgress.size() > 0) return false;

    if (hasDownloadNotificationsInternal(notificationIdToIgnore)) return false;

    StatusBarNotification notification = getSummaryNotification(mNotificationManager);
    if (notification != null) {
        // We have a valid summary notification, but how we dismiss it depends on whether or not
        // it is currently bound to this service via startForeground(...).
        if ((notification.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE)
                != 0) {
            // If we are a foreground service and we are hiding the notification, we have no
            // other downloads notifications showing, so we need to remove the notification and
            // unregister it from this service at the same time.
            stopForegroundInternal(true);
        } else {
            // If we are not a foreground service, remove the notification via the
            // NotificationManager.  The notification is not bound to this service, so any call
            // to stopForeground() won't affect the notification.
            cancelSummaryNotification();
        }
    } else {
        // If we don't have a valid summary, just guarantee that we aren't in the foreground for
        // safety.  Still try to remove the summary notification to make sure it's gone.  This
        // is because querying for it might fail if we have just recently started up and began
        // showing it.  This might leave us in a bad state if the cancel request fails inside
        // the framework.
        // TODO(dtrainor): Add a way to attempt to automatically clean up the notification
        // shortly after this.
        stopForegroundInternal(true);
    }

    // Stop the service which should start the destruction process.  At this point we should be
    // a background service.  We might not be unbound from any clients.  When they unbind we
    // will shut down.  That is okay because they will only unbind from us when they are ok with
    // us going away (e.g. we shouldn't be unbound while in the foreground).
    stopSelf();
    return true;
}
 
Example 16
Source File: NavigationService.java    From graphhopper-navigation-android with MIT License 4 votes vote down vote up
private void startForegroundNotification(NavigationNotification navigationNotification) {
  Notification notification = navigationNotification.getNotification();
  int notificationId = navigationNotification.getNotificationId();
  notification.flags = Notification.FLAG_FOREGROUND_SERVICE;
  startForeground(notificationId, notification);
}
 
Example 17
Source File: TrustService.java    From trust with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "service started");

    sPausedVoluntarilz = false;
    wasVoluntaryStart();

    settings = PreferenceManager.getDefaultSharedPreferences(this);
    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    filter.addAction(Intent.ACTION_POWER_CONNECTED);
    filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    filter.addAction(Intent.ACTION_REBOOT);
    filter.addAction(Intent.ACTION_SHUTDOWN);
    filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
    filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

    mTrustReceivers = new TrustReceivers();
    registerReceiver(mTrustReceivers, filter);

    IntentFilter filterPackage = new IntentFilter();
    filterPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    filterPackage.addAction(Intent.ACTION_PACKAGE_CHANGED);
    filterPackage.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
    filterPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filterPackage.addAction(Intent.ACTION_PACKAGE_REPLACED);
    filterPackage.addAction(Intent.ACTION_PACKAGE_RESTARTED);
    filterPackage.addDataScheme("package");

    registerReceiver(mTrustReceivers, filterPackage);
    sIsRunning = true;

    mNotification = new Notification(R.drawable.ic_launcher, "Trust is good", System.currentTimeMillis());
    Intent i = new Intent(this, TrustActivity.class);

    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    mPendingIntent = PendingIntent.getActivity(this, 0, i, 0);

    mNotification.setLatestEventInfo(this, "Control is better", "Trust running", mPendingIntent);
    mNotification.flags |= Notification.FLAG_NO_CLEAR;
    mNotification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
    mNotification.flags |= Notification.FLAG_ONGOING_EVENT;

    if (settings.getBoolean("general.notification", false))
        startForeground(NOTIFICATION_ID, mNotification);


    mAppWatcher = new AppWatcher(this);
    mAppWatcher.startWatching();
}
 
Example 18
Source File: NotificationComparator.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private boolean isOngoing(NotificationRecord record) {
    final int ongoingFlags = Notification.FLAG_FOREGROUND_SERVICE;
    return (record.getNotification().flags & ongoingFlags) != 0;
}