Example usage for android.app Notification FLAG_FOREGROUND_SERVICE

List of usage examples for android.app Notification FLAG_FOREGROUND_SERVICE

Introduction

In this page you can find the example usage for android.app Notification FLAG_FOREGROUND_SERVICE.

Prototype

int FLAG_FOREGROUND_SERVICE

To view the source code for android.app Notification FLAG_FOREGROUND_SERVICE.

Click Source Link

Document

Bit to be bitwise-ored into the #flags field that should be set if this notification represents a currently running service.

Usage

From source file:dk.dr.radio.afspilning.AfspillerIkonOgNotifikation.java

@SuppressLint("NewApi")
  public static Notification lavNotification(Context ctx) {
      String kanalNavn = "";
      try {//  w w  w. j  a  va  2s  . com
          kanalNavn = DRData.instans.afspiller.getLydkilde().getKanal().navn;
      } catch (Exception e) {
          Log.rapporterFejl(e);
      } // TODO fjern try-catch efter nogle mneder i drift. 9. okt 2014

      NotificationCompat.Builder b = new NotificationCompat.Builder(ctx).setSmallIcon(R.drawable.dr_notifikation)
              .setContentTitle(ctx.getString(R.string.dr_radio)).setContentText(kanalNavn).setOngoing(true)
              .setAutoCancel(false).setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setPriority(1001) // holder den verst
              .setContentIntent(PendingIntent.getActivity(ctx, 0, new Intent(ctx, Hovedaktivitet.class), 0));
      // PendingIntent er til at pege p aktiviteten der skal startes hvis
      // brugeren vlger notifikationen

      b.setContent(
              AfspillerIkonOgNotifikation.lavRemoteViews(AfspillerIkonOgNotifikation.TYPE_notifikation_lille));
      Notification notification = b.build();

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
          // A notification's big view appears only when the notification is expanded,
          // which happens when the notification is at the top of the notification drawer,
          // or when the user expands the notification with a gesture.
          // Expanded notifications are available starting with Android 4.1.
          notification.bigContentView = AfspillerIkonOgNotifikation
                  .lavRemoteViews(AfspillerIkonOgNotifikation.TYPE_notifikation_stor);
      }

      notification.flags |= (Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT
              | Notification.PRIORITY_HIGH | Notification.FLAG_FOREGROUND_SERVICE);
      return notification;
  }

From source file:edu.polyu.screamalert.SoundProcessing.java

@SuppressWarnings("unchecked")
public static void initialize(Context context) {
    thisContext = context;//from  ww  w  . ja v a2  s .co  m
    x = new float[samplePerFrm];
    subx = new float[frameShift]; // Samples in a sub-frame
    mfcc = new MFCC(samplePerFrm, Config.RECORDER_SAMPLERATE, numMfcc);
    ccBuf = new CircularFifoBuffer(K); // Buffer storing K mfcc vectors
    dccBuf = new CircularFifoBuffer(K); // Buffer storing K delta-mfcc vectors
    pDet = new YinPitchDetector(Config.RECORDER_SAMPLERATE, samplePerFrm);
    piBuf = new CircularFifoBuffer(K);
    pkBuf = new CircularFifoBuffer(K);
    mu_z = new double[] { VoiceQuality.JITTER_MEAN, VoiceQuality.SHIMMER_MEAN }; // Jitter and shimmer mean
    sigma_z = new double[] { VoiceQuality.JITTER_STD, VoiceQuality.SHIMMER_STD }; // Jitter and shimmer stddev
    aList = new ArrayList<double[]>();
    enBuf = new CircularFifoBuffer(enBufSize); // Circular buffer storing energy profile of the latest K frames
    frmBuf = new CircularFifoBuffer(K); // Buffer storing K latest frames of audio signals */

    for (int k = 0; k < K; k++) {
        ccBuf.add(new double[numMfcc + 1]); // Initialize MFCC FIFO buffers
        dccBuf.add(new double[numMfcc + 1]); // Initialize delta MFCC FIFO buffers
        piBuf.add(-1.0D); // Initialize pitch FIFO buffer for computing jitter and shimmer
        pkBuf.add(0.0D); // Initialize peak amplitude FIFO buffer for computing shimmer
        frmBuf.add(new double[samplePerFrm]); // Initialize frame buffer
    }
    for (int k = 0; k < enBufSize; k++) {
        enBuf.add(new double[1]); // Initialize energy buffer
    }
    mainIntent = new Intent(thisContext, SoundProcessingSetting.class);
    mainIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    pIntent = PendingIntent.getActivity(thisContext, 0, mainIntent, 0); // Go back to MainActivity when user press the notification
    noti = new NotificationCompat.Builder(thisContext)
            .setContentTitle(
                    thisContext.getString(R.string.app_name) + " " + thisContext.getString(R.string.running))
            .setContentText(thisContext.getString(R.string.configure)).setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent).build();
    noti.flags = Notification.FLAG_FOREGROUND_SERVICE;
    if (SoundProcessingActivity.thisActivity == null)
        calibrateDialog = new ProgressDialog(Exchanger.thisContext);
    else
        calibrateDialog = new ProgressDialog(SoundProcessingActivity.thisActivity);
}

From source file:com.marianhello.bgloc.LocationService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    log.info("Received start startId: {} intent: {}", startId, intent);

    if (provider != null) {
        provider.onDestroy();/*  w ww.ja  va  2 s  .co  m*/
    }

    if (intent == null) {
        //service has been probably restarted so we need to load config from db
        ConfigurationDAO dao = DAOFactory.createConfigurationDAO(this);
        try {
            config = dao.retrieveConfiguration();
        } catch (JSONException e) {
            log.error("Config exception: {}", e.getMessage());
            config = new Config(); //using default config
        }
    } else {
        if (intent.hasExtra("config")) {
            config = intent.getParcelableExtra("config");
        } else {
            config = new Config(); //using default config
        }
    }

    log.debug("Will start service with: {}", config.toString());

    LocationProviderFactory spf = new LocationProviderFactory(this);
    provider = spf.getInstance(config.getLocationProvider());

    if (config.getStartForeground()) {
        // Build a Notification required for running service in foreground.
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(config.getNotificationTitle());
        builder.setContentText(config.getNotificationText());
        if (config.getSmallNotificationIcon() != null) {
            builder.setSmallIcon(getDrawableResource(config.getSmallNotificationIcon()));
        } else {
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
        }
        if (config.getLargeNotificationIcon() != null) {
            builder.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(),
                    getDrawableResource(config.getLargeNotificationIcon())));
        }
        if (config.getNotificationIconColor() != null) {
            builder.setColor(this.parseNotificationIconColor(config.getNotificationIconColor()));
        }

        // Add an onclick handler to the notification
        Context context = getApplicationContext();
        String packageName = context.getPackageName();
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 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;
        startForeground(startId, notification);
    }

    provider.startRecording();

    //We want this service to continue running until it is explicitly stopped
    return START_STICKY;
}

From source file:com.pandoroid.PandoraRadioService.java

public void setNotification() {
    if (!m_paused) {
        try {//  w  w  w .j ava  2 s . c  om
            Song tmp_song;
            tmp_song = m_song_playback.getSong();
            Notification notification = new Notification(R.drawable.icon, "Pandoroid Radio",
                    System.currentTimeMillis());
            Intent notificationIntent = new Intent(this, PandoroidPlayer.class);
            PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_SONG_PLAYING,
                    notificationIntent, 0);
            notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE;
            notification.setLatestEventInfo(getApplicationContext(), tmp_song.getTitle(),
                    tmp_song.getArtist() + " on " + tmp_song.getAlbum(), contentIntent);
            startForeground(NOTIFICATION_SONG_PLAYING, notification);
        } catch (Exception e) {
        }
    }
}

From source file:com.perm.DoomPlay.PlayingService.java

private Notification createNotification() {

    Intent intentActivity;/*from  w  w w .j  a  v  a 2  s  .co  m*/

    if (SettingActivity.getPreferences(SettingActivity.keyOnClickNotif)) {
        intentActivity = new Intent(FullPlaybackActivity.actionReturnFull);
        intentActivity.setClass(this, FullPlaybackActivity.class);
        intentActivity.putExtra(FileSystemActivity.keyMusic, audios);
    } else {
        intentActivity = FullPlaybackActivity.getReturnSmallIntent(this, audios);
    }
    intentActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    Notification notification = new Notification();
    notification.contentView = getNotifViews(R.layout.notif);
    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
    notification.contentIntent = PendingIntent.getActivity(this, 0, intentActivity,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.icon = isPlaying ? R.drawable.status_icon_pause : R.drawable.status_icon_play;

    return notification;
}

From source file:com.parrot.cyclops.CameraView.java

private void startCyclopsServiceForeground() {
    logdebug("startCyclopsServiceForeground");
    SystemProperties.setTvBusyByCyclops(true);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext)
            .setSmallIcon(R.drawable.ic_launcher).setContentTitle(mContext.getString(R.string.notif_title))
            .setContentText(mContext.getString(R.string.notif_text));
    PendingIntent pendingIntent;//from   w ww  .ja v  a 2s.  co  m
    Intent intent = new Intent(mContext, CyclopsActivity.class);
    pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    builder.setContentIntent(pendingIntent);
    builder.setPriority(NotificationCompat.PRIORITY_MAX);
    Notification notif = builder.build();
    notif.flags = Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
    mCyclopsService.startForeground(Cyclops.CYCLOPS_FOREGROUND_NOTIFICATION, notif);
}

From source file:com.marianhello.cordova.bgloc.LocationUpdateService.java

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Received start id " + startId + ": " + intent);
        if (intent != null) {
            try {
                params = new JSONObject(intent.getStringExtra("params"));
                headers = new JSONObject(intent.getStringExtra("headers"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();/*  w w w .j a v a2  s.c  om*/
            }
            url = intent.getStringExtra("url");
            stationaryRadius = Float.parseFloat(intent.getStringExtra("stationaryRadius"));
            distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter"));
            scaledDistanceFilter = distanceFilter;
            desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy"));
            locationTimeout = Integer.parseInt(intent.getStringExtra("locationTimeout"));
            isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging"));
            notificationTitle = intent.getStringExtra("notificationTitle");
            notificationText = intent.getStringExtra("notificationText");

            // Build a Notification required for running service in foreground.
            Intent main = new Intent(this, BackgroundGpsPlugin.class);
            main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            Notification.Builder builder = new Notification.Builder(this);
            builder.setContentTitle(notificationTitle);
            builder.setContentText(notificationText);
            builder.setSmallIcon(android.R.drawable.ic_menu_mylocation);
            builder.setContentIntent(pendingIntent);
            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, "- headers: " + headers.toString());
        Log.i(TAG, "- stationaryRadius: " + stationaryRadius);
        Log.i(TAG, "- distanceFilter: " + distanceFilter);
        Log.i(TAG, "- desiredAccuracy: " + desiredAccuracy);
        Log.i(TAG, "- locationTimeout: " + locationTimeout);
        Log.i(TAG, "- isDebugging: " + isDebugging);
        Log.i(TAG, "- notificationTitle: " + notificationTitle);
        Log.i(TAG, "- notificationText: " + notificationText);

        this.setPace(false);

        //We want this service to continue running until it is explicitly stopped
        return START_REDELIVER_INTENT;
    }

From source file:net.dian1.player.service.PlayerService.java

private void displayNotifcation(PlaylistEntry playlistEntry) {
    Album album = playlistEntry.getAlbum();

    String artist = (album == null ? playlistEntry.getMusic().getArtist() : album.getArtistName());

    artist = (TextUtils.isEmpty(artist) || artist.equals("<unknown>")) ? "" : " - " + artist;

    String notificationMessage = playlistEntry.getMusic().getName() + artist;

    Intent intent = new Intent(getApplicationContext(), PlayerActivity.class);

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    Resources res = getResources();
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentIntent(contentIntent).setSmallIcon(R.drawable.noti_small)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.noti_small))
            .setTicker(notificationMessage).setWhen(System.currentTimeMillis()).setAutoCancel(true)
            .setContentTitle(getString(R.string.app_name)).setContentText(notificationMessage)
    /*.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))*/;
    Notification notification = builder.build();
    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;

    mNotificationManager.notify(PLAYING_NOTIFY_ID, notification);

    addTaskStack(this, MainActivity.class);
}

From source file:com.halseyburgund.rwframework.core.RWService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // intent will be null on restart!
    if (intent != null) {
        getSettingsFromIntent(intent);//from  w  w  w .j a  v a  2  s.c o m
    }

    // create a pending intent to start the specified activity from the notification
    Intent ovIntent = new Intent(this, mNotificationActivity);
    mNotificationPendingIntent = PendingIntent.getActivity(this, 0, ovIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

    // create a notification and move service to foreground
    mRwNotification = new Notification(mNotificationIconId, "Roundware Service Started",
            System.currentTimeMillis());
    mRwNotification.number = 1;
    mRwNotification.flags = mRwNotification.flags | Notification.FLAG_FOREGROUND_SERVICE
            | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
    setNotificationText("");

    startForeground(NOTIFICATION_ID, mRwNotification);

    // try to go on-line, this will attempt to get the configuration and tags
    manageSessionState(SessionState.ON_LINE);

    return Service.START_STICKY;
}

From source file:com.orangelabs.rcs.ri.ConnectionManager.java

private void addImsConnectionNotification(boolean connected, RcsServiceRegistration.ReasonCode reason) {
    /* Create notification */
    Intent intent = new Intent(mContext, SettingsDisplay.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
    int iconId;/* www . ja  v  a  2s  .c o  m*/
    String label;
    if (connected) {
        iconId = R.drawable.ri_notif_on_icon;
        label = mContext.getString(R.string.ims_connected);
    } else {
        iconId = R.drawable.ri_notif_off_icon;
        if (RcsServiceRegistration.ReasonCode.BATTERY_LOW == reason) {
            label = mContext.getString(R.string.ims_battery_disconnected);
        } else {
            label = mContext.getString(R.string.ims_disconnected);
        }
    }
    String title = mContext.getString(R.string.notification_title_rcs_service);
    /* Create notification */
    Notification notif = buildImsConnectionNotification(contentIntent, title, label, iconId);
    notif.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_FOREGROUND_SERVICE;
    /* Send notification */
    NotificationManager notificationManager = (NotificationManager) mContext
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(SERVICE_NOTIFICATION, notif);
}