List of usage examples for android.app PendingIntent getService
public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent, @Flags int flags)
From source file:com.smithdtyler.prettygoodmusicplayer.MusicPlaybackService.java
private void updateNotification() { boolean audiobookMode = sharedPref.getBoolean("pref_audiobook_mode", false); // https://stackoverflow.com/questions/5528288/how-do-i-update-the-notification-text-for-a-foreground-service-in-android Intent resultIntent = new Intent(this, NowPlaying.class); // Use the FLAG_ACTIVITY_CLEAR_TOP to prevent launching a second // NowPlaying if one already exists. resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); resultIntent.putExtra("From_Notification", true); resultIntent.putExtra(AlbumList.ALBUM_NAME, album); resultIntent.putExtra(ArtistList.ARTIST_NAME, artist); resultIntent.putExtra(ArtistList.ARTIST_ABS_PATH_NAME, artistAbsPath); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); Builder builder = new NotificationCompat.Builder(this.getApplicationContext()); int icon = R.drawable.ic_pgmp_launcher; String contentText = getResources().getString(R.string.ticker_text); if (songFile != null) { SharedPreferences prefs = getSharedPreferences("PrettyGoodMusicPlayer", MODE_PRIVATE); prefs.edit();/*from w w w . j ava 2 s .c om*/ File bestGuessMusicDir = Utils.getBestGuessMusicDirectory(); String musicRoot = prefs.getString("ARTIST_DIRECTORY", bestGuessMusicDir.getAbsolutePath()); contentText = Utils.getArtistName(songFile, musicRoot) + ": " + Utils.getPrettySongName(songFile); if (mp != null) { if (mp.isPlaying()) { icon = R.drawable.ic_pgmp_launcher; } } } Intent previousIntent = new Intent("Previous", null, this, MusicPlaybackService.class); previousIntent.putExtra("Message", MSG_PREVIOUS); PendingIntent previousPendingIntent = PendingIntent.getService(this, 0, previousIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent jumpBackIntent = new Intent("JumpBack", null, this, MusicPlaybackService.class); jumpBackIntent.putExtra("Message", MSG_JUMPBACK); PendingIntent jumpBackPendingIntent = PendingIntent.getService(this, 0, jumpBackIntent, PendingIntent.FLAG_UPDATE_CURRENT); Intent nextIntent = new Intent("Next", null, this, MusicPlaybackService.class); nextIntent.putExtra("Message", MSG_NEXT); PendingIntent nextPendingIntent = PendingIntent.getService(this, 0, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent playPausePendingIntent; Intent playPauseIntent = new Intent("PlayPause", null, this, MusicPlaybackService.class); playPauseIntent.putExtra("Message", MSG_PLAYPAUSE); playPausePendingIntent = PendingIntent.getService(this, 0, playPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT); int playPauseIcon; if (mp != null && mp.isPlaying()) { playPauseIcon = R.drawable.ic_action_pause; } else { playPauseIcon = R.drawable.ic_action_play; } Notification notification; if (audiobookMode) { notification = builder.setContentText(contentText).setSmallIcon(icon) .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent) .setContentTitle(getResources().getString(R.string.notification_title)) .addAction(R.drawable.ic_action_rewind20, "", jumpBackPendingIntent) .addAction(playPauseIcon, "", playPausePendingIntent) .addAction(R.drawable.ic_action_next, "", nextPendingIntent).build(); } else { notification = builder.setContentText(contentText).setSmallIcon(icon) .setWhen(System.currentTimeMillis()).setContentIntent(pendingIntent) .setContentTitle(getResources().getString(R.string.notification_title)) .addAction(R.drawable.ic_action_previous, "", previousPendingIntent) .addAction(playPauseIcon, "", playPausePendingIntent) .addAction(R.drawable.ic_action_next, "", nextPendingIntent).build(); } NotificationManager mNotificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE); mNotificationManager.notify(uniqueid, notification); }
From source file:com.android.mail.utils.NotificationActionUtils.java
/** * Creates a {@link PendingIntent} to be used for creating and canceling the undo timeout * alarm.//from ww w. j av a 2 s.c o m */ private static PendingIntent createUndoTimeoutPendingIntent(final Context context, final NotificationAction notificationAction) { final Intent intent = new Intent(NotificationActionIntentService.ACTION_UNDO_TIMEOUT); intent.setPackage(context.getPackageName()); intent.setData(notificationAction.mConversation.uri); putNotificationActionExtra(intent, notificationAction); final int requestCode = notificationAction.getAccount().hashCode() ^ notificationAction.getFolder().hashCode(); final PendingIntent pendingIntent = PendingIntent.getService(context, requestCode, intent, 0); return pendingIntent; }
From source file:com.mine.psf.PsfPlaybackService.java
private void notifyPlaying() { Intent notificationIntent = new Intent(this, PsfPlaybackActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_psfplaying).setContentTitle(getAlbumName()) .setContentText(getTrackName()); builder.setContentIntent(contentIntent); // Next button, only work after v11 Intent nextTrackIntent = new Intent(this, PsfPlaybackService.class); nextTrackIntent.setAction(ACTION_CMD); nextTrackIntent.putExtra(CMDNAME, CMDNEXT); PendingIntent nextTrackPendingIntent = PendingIntent.getService(this, 0, nextTrackIntent, PendingIntent.FLAG_CANCEL_CURRENT); // Prev button // Intent pauseTrackIntent = new Intent(this, PsfPlaybackService.class); // pauseTrackIntent.setAction(ACTION_CMD); // pauseTrackIntent.putExtra(CMDNAME, CMDPAUSE); // PendingIntent pauseTrackPendingIntent = // PendingIntent.getService(this, 1, pauseTrackIntent, PendingIntent.FLAG_CANCEL_CURRENT); // Prev button Intent prevTrackIntent = new Intent(this, PsfPlaybackService.class); prevTrackIntent.setAction(ACTION_CMD); prevTrackIntent.putExtra(CMDNAME, CMDPREV); PendingIntent prevTrackPendingIntent = PendingIntent.getService(this, 2, prevTrackIntent, PendingIntent.FLAG_CANCEL_CURRENT); builder.addAction(android.R.drawable.ic_media_previous, "Prev", prevTrackPendingIntent); // builder.addAction(android.R.drawable.ic_media_pause, "", pauseTrackPendingIntent); builder.addAction(android.R.drawable.ic_media_next, "Next", nextTrackPendingIntent); startForeground(PLAYBACKSERVICE_STATUS, builder.build()); }
From source file:com.t2.compassionMeditation.MeditationActivity.java
/** Called when the activity is first created. */ @Override// w ww .j ava2 s . c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()"); mInstance = this; mRateOfChange = new RateOfChange(mRateOfChangeSize); mIntroFade = 255; // We don't want the screen to timeout in this activity getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView setContentView(R.layout.buddah_activity_layout); sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); currentMindsetData = new MindsetData(this); mSaveRawWave = SharedPref.getBoolean(this, BioZenConstants.PREF_SAVE_RAW_WAVE, BioZenConstants.PREF_SAVE_RAW_WAVE_DEFAULT); mShowAGain = SharedPref.getBoolean(this, BioZenConstants.PREF_SHOW_A_GAIN, BioZenConstants.PREF_SHOW_A_GAIN_DEFAULT); mAllowComments = SharedPref.getBoolean(this, BioZenConstants.PREF_COMMENTS, BioZenConstants.PREF_COMMENTS_DEFAULT); mShowForeground = SharedPref.getBoolean(this, "show_lotus", true); mShowToast = SharedPref.getBoolean(this, "show_toast", true); mAudioTrackResourceName = SharedPref.getString(this, "audio_track", "None"); mBaseImageResourceName = SharedPref.getString(this, "background_images", "Sunset"); mBioHarnessParameters = getResources().getStringArray(R.array.bioharness_parameters_array); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); String s = SharedPref.getString(this, BioZenConstants.PREF_SESSION_LENGTH, "10"); mSecondsRemaining = Integer.parseInt(s) * 60; mSecondsTotal = mSecondsRemaining; s = SharedPref.getString(this, BioZenConstants.PREF_ALPHA_GAIN, "5"); mAlphaGain = Float.parseFloat(s); mMovingAverage = new TMovingAverageFilter(mMovingAverageSize); mMovingAverageROC = new TMovingAverageFilter(mMovingAverageSizeROC); View v1 = findViewById(R.id.buddahView); v1.setOnTouchListener(this); Resources resources = this.getResources(); AssetManager assetManager = resources.getAssets(); // Set up member variables to UI Elements mTextInfoView = (TextView) findViewById(R.id.textViewInfo); mTextBioHarnessView = (TextView) findViewById(R.id.textViewBioHarness); mCountdownTextView = (TextView) findViewById(R.id.countdownTextView); mCountdownImageView = (ImageView) findViewById(R.id.imageViewCountdown); mPauseButton = (ImageButton) findViewById(R.id.buttonPause); mSignalImage = (ImageView) findViewById(R.id.imageView1); mTextViewInstructions = (TextView) findViewById(R.id.textViewInstructions); // Note that the seek bar is a debug thing - used only to set the // alpha of the buddah image manually for visual testing mSeekBar = (SeekBar) findViewById(R.id.seekBar1); mSeekBar.setOnSeekBarChangeListener(this); // Scale such that values to the right of center are scaled 1 - 10 // and values to the left of center are scaled 0 = .99999 if (mAlphaGain > 1.0) { mSeekBar.setProgress(50 + (int) (mAlphaGain * 5)); } else { int i = (int) (mAlphaGain * 50); mSeekBar.setProgress(i); } // mSeekBar.setProgress((int) mAlphaGain * 10); // Controls start as invisible, need to touch screen to activate them mCountdownTextView.setVisibility(View.INVISIBLE); mCountdownImageView.setVisibility(View.INVISIBLE); mTextInfoView.setVisibility(View.INVISIBLE); mTextBioHarnessView.setVisibility(View.INVISIBLE); mPauseButton.setVisibility(View.INVISIBLE); mPauseButton.setVisibility(View.VISIBLE); mSeekBar.setVisibility(View.INVISIBLE); mBackgroundImage = (ImageView) findViewById(R.id.buddahView); mForegroundImage = (ImageView) findViewById(R.id.lotusView); mBaseImage = (ImageView) findViewById(R.id.backgroundView); if (!mShowForeground) { mForegroundImage.setVisibility(View.INVISIBLE); } int resource = 0; if (mBaseImageResourceName.equalsIgnoreCase("Buddah")) { mBackgroundImage.setImageResource(R.drawable.buddha); mForegroundImage.setImageResource(R.drawable.lotus_flower); mBaseImage.setImageResource(R.drawable.none_bg); } else if (mBaseImageResourceName.equalsIgnoreCase("Bob")) { mBackgroundImage.setImageResource(R.drawable.bigbob); mForegroundImage.setImageResource(R.drawable.red_nose); mBaseImage.setImageResource(R.drawable.none_bg); } else if (mBaseImageResourceName.equalsIgnoreCase("Sunset")) { mBackgroundImage.setImageResource(R.drawable.eeg_layer); mForegroundImage.setImageResource(R.drawable.breathing_rate); mBaseImage.setImageResource(R.drawable.meditation_bg); } // Initialize SPINE by passing the fileName with the configuration properties try { mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources); } catch (InstantiationException e) { Log.e(TAG, "Exception creating SPINE manager: " + e.toString()); e.printStackTrace(); } // Since Mindset is a static node we have to manually put it in the active node list // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor Node mindsetNode = null; mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); mManager.getActiveNodes().add(mindsetNode); Node zepherNode = null; zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR)); mManager.getActiveNodes().add(zepherNode); // The arduino node is programmed to look like a static Spine node // Note that currently we don't have to turn it on or off - it's always streaming // Since Spine (in this case) is a static node we have to manually put it in the active node list // Since the final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001 mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE)); mManager.getActiveNodes().add(mSpineNode); // Create a broadcast receiver. Note that this is used ONLY for command messages from the service // All data from the service goes through the mail SPINE mechanism (received(Data data)). // See public void received(Data data) this.mCommandReceiver = new SpineReceiver(this); try { PackageManager packageManager = this.getPackageManager(); PackageInfo info = packageManager.getPackageInfo(this.getPackageName(), 0); mApplicationVersion = info.versionName; Log.i(TAG, "BioZen Application Version: " + mApplicationVersion + ", Activity Version: " + mActivityVersion); } catch (NameNotFoundException e) { Log.e(TAG, e.toString()); } // First create GraphBioParameters for each of the ECG static params (ie mindset) int itemId = 0; eegPos = itemId; // eeg always comes first mBioParameters.clear(); for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true); param.isShimmer = false; mBioParameters.add(param); } // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, HR, Skin Temp, Resp Rate String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names); for (String paramName : paramNamesStringArray) { if (paramName.equalsIgnoreCase("not assigned")) continue; if (paramName.equalsIgnoreCase("EEG")) continue; GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true); if (paramName.equalsIgnoreCase("gsr")) { gsrPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("emg")) { emgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("ecg")) { ecgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("heart rate")) { heartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("resp rate")) { respRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("skin temp")) { skinTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Airflow")) { eHealthAirFlowPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Temp")) { eHealthTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth SpO2")) { eHealthSpO2Pos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Heartrate")) { eHealthHeartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth GSR")) { eHealthGSRPos = itemId; param.isShimmer = false; } itemId++; mBioParameters.add(param); } // The session start time will be used as session id // Note this also sets session start time // **** This session ID will be prepended to all JSON data stored // in the external database until it's changed (by the start // of a new session. Calendar cal = Calendar.getInstance(); SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US); String sessionDate = sdf.format(new Date()); long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0); mUserId = SharedPref.getString(this, "SelectedUser", ""); // Now get the database object associated with this user try { mBioUserDao = getHelper().getBioUserDao(); mBioSessionDao = getHelper().getBioSessionDao(); QueryBuilder<BioUser, Integer> builder = mBioUserDao.queryBuilder(); builder.where().eq(BioUser.NAME_FIELD_NAME, mUserId); builder.limit(1); // builder.orderBy(ClickCount.DATE_FIELD_NAME, false).limit(30); List<BioUser> list = mBioUserDao.query(builder.prepare()); if (list.size() == 1) { mCurrentBioUser = list.get(0); } else if (list.size() == 0) { try { mCurrentBioUser = new BioUser(mUserId, System.currentTimeMillis()); mBioUserDao.create(mCurrentBioUser); } catch (SQLException e1) { Log.e(TAG, "Error creating user " + mUserId, e1); } } else { Log.e(TAG, "General Database error" + mUserId); } } catch (SQLException e) { Log.e(TAG, "Can't find user: " + mUserId, e); } mSignalImage.setImageResource(R.drawable.signal_bars0); // Check to see of there a device configured for EEG, if so then show the skin conductance meter String tmp = SharedPref.getString(this, "EEG", null); if (tmp != null) { mSignalImage.setVisibility(View.VISIBLE); mTextViewInstructions.setVisibility(View.VISIBLE); } else { mSignalImage.setVisibility(View.INVISIBLE); mTextViewInstructions.setVisibility(View.INVISIBLE); } mDataOutHandler = new DataOutHandler(this, mUserId, sessionDate, mAppId, DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId); if (mDatabaseEnabled) { TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String myNumber = telephonyManager.getLine1Number(); String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name", getString(R.string.database_uri)); // remoteDatabaseUri += myNumber; Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove try { mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName, remoteDatabaseUri); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } mDataOutHandler.setRequiresAuthentication(false); } mBioDataProcessor.initialize(mDataOutHandler); mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true); mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false); mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false); mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false); if (mAntHrmEnabled) { mHeartRateSource = HEARTRATE_ANT; } else { mHeartRateSource = HEARTRATE_ZEPHYR; } if (mLoggingEnabled) { mDataOutHandler.enableLogging(this); } if (mLogCatEnabled) { mDataOutHandler.enableLogCat(); } // Log the version try { PackageManager packageManager = getPackageManager(); PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0); mApplicationVersion = info.versionName; String versionString = mAppId + " application version: " + mApplicationVersion; DataOutPacket packet = new DataOutPacket(); packet.add(DataOutHandlerTags.version, versionString); try { mDataOutHandler.handleDataOut(packet); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } } catch (NameNotFoundException e) { Log.e(TAG, e.toString()); } if (mInternalSensorMonitoring) { // IntentSender Launches our service scheduled with with the alarm manager mBigBrotherService = PendingIntent.getService(MeditationActivity.this, 0, new Intent(MeditationActivity.this, BigBrotherService.class), 0); long firstTime = SystemClock.elapsedRealtime(); // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000, mBigBrotherService); // Tell the user about what we did. Toast.makeText(MeditationActivity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show(); } }
From source file:com.massivcode.androidmusicplayer.services.MusicService.java
private void showNotificationUnderLollipop() { Notification.Builder builder = new Notification.Builder(this); RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification); // ? ? ? /*from w w w. jav a 2 s.co m*/ // ========================================================================================= Intent musicPreviousIntent = new Intent(getApplicationContext(), MusicService.class); musicPreviousIntent.setAction(ACTION_PLAY_PREVIOUS); musicPreviousIntent.putExtra("position", getPositionAtPreviousOrNext(ACTION_PLAY_PREVIOUS)); PendingIntent musicPreviousPendingIntent = PendingIntent.getService(getApplicationContext(), 0, musicPreviousIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.noti_previous_ib, musicPreviousPendingIntent); // ========================================================================================= // ? ? ? // ========================================================================================= Intent musicStopIntent = new Intent(getApplicationContext(), MusicService.class); musicStopIntent.setAction(ACTION_PAUSE); PendingIntent musicStopPendingIntent = PendingIntent.getService(getApplicationContext(), 1, musicStopIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.noti_play_ib, musicStopPendingIntent); // ========================================================================================= // ? ? ? // ========================================================================================= Intent musicNextIntent = new Intent(getApplicationContext(), MusicService.class); musicNextIntent.setAction(ACTION_PLAY_NEXT); musicNextIntent.putExtra("position", getPositionAtPreviousOrNext(ACTION_PLAY_NEXT)); PendingIntent musicNextPendingIntent = PendingIntent.getService(getApplicationContext(), 2, musicNextIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.noti_next_ib, musicNextPendingIntent); // ========================================================================================= // ? ? // ========================================================================================= Intent closeIntent = new Intent(getApplicationContext(), MusicService.class); closeIntent.setAction(ACTION_FINISH); PendingIntent closePendingIntent = PendingIntent.getService(getApplicationContext(), 3, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.noti_close_ib, closePendingIntent); // ========================================================================================= // Notification ? PendingIntent // ========================================================================================= Intent activityStartIntent = new Intent(MainActivity.ACTION_NAME); activityStartIntent.putExtra("restore", getCurrentInfo()); PendingIntent activityStartPendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, activityStartIntent, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(activityStartPendingIntent); // ========================================================================================= Bitmap bitmap = null; if (mCurrentMusicInfo != null) { if (mCurrentMusicInfo.getUri() != null) { bitmap = MusicInfoLoadUtil.getBitmap(getApplicationContext(), mCurrentMusicInfo.getUri(), 4); } } if (bitmap == null) { bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_no_image); } remoteViews.setImageViewBitmap(R.id.noti_album_art_iv, bitmap); if (mCurrentMusicInfo != null) { remoteViews.setTextViewText(R.id.noti_artist_tv, mCurrentMusicInfo.getArtist()); remoteViews.setTextViewText(R.id.noti_title_tv, mCurrentMusicInfo.getTitle()); } builder.setContent(remoteViews); builder.setLargeIcon(bitmap); builder.setSmallIcon(R.mipmap.ic_no_image); if (mMediaPlayer.isPlaying()) { remoteViews.setImageViewResource(R.id.noti_play_ib, android.R.drawable.ic_media_pause); } else { remoteViews.setImageViewResource(R.id.noti_play_ib, android.R.drawable.ic_media_play); } builder.setAutoCancel(false); Notification notification = builder.build(); startForeground(1, notification); }
From source file:com.android.mail.utils.NotificationUtils.java
/** * Validate the notifications notification. */// www . j a v a 2 s.c om private static void validateNotifications(Context context, final Folder folder, final Account account, boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key, final ContactFetcher contactFetcher) { NotificationManagerCompat nm = NotificationManagerCompat.from(context); final NotificationMap notificationMap = getNotificationMap(context); if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) { LogUtils.i(LOG_TAG, "Validating Notification: %s mapSize: %d " + "folder: %s getAttention: %b ignoreUnobtrusive: %b", createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention, ignoreUnobtrusiveSetting); } else { LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b ignoreUnobtrusive: %b", notificationMap.size(), getAttention, ignoreUnobtrusiveSetting); } // The number of unread messages for this account and label. final Integer unread = notificationMap.getUnread(key); final int unreadCount = unread != null ? unread.intValue() : 0; final Integer unseen = notificationMap.getUnseen(key); int unseenCount = unseen != null ? unseen.intValue() : 0; Cursor cursor = null; try { final Uri.Builder uriBuilder = folder.conversationListUri.buildUpon(); uriBuilder.appendQueryParameter(UIProvider.SEEN_QUERY_PARAMETER, Boolean.FALSE.toString()); // Do not allow this quick check to disrupt any active network-enabled conversation // cursor. uriBuilder.appendQueryParameter(UIProvider.ConversationListQueryParameters.USE_NETWORK, Boolean.FALSE.toString()); cursor = context.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION, null, null, null); if (cursor == null) { // This folder doesn't exist. LogUtils.i(LOG_TAG, "The cursor is null, so the specified folder probably does not exist"); clearFolderNotification(context, account, folder, false); return; } final int cursorUnseenCount = cursor.getCount(); // Make sure the unseen count matches the number of items in the cursor. But, we don't // want to overwrite a 0 unseen count that was specified in the intent if (unseenCount != 0 && unseenCount != cursorUnseenCount) { LogUtils.i(LOG_TAG, "Unseen count doesn't match cursor count. unseen: %d cursor count: %d", unseenCount, cursorUnseenCount); unseenCount = cursorUnseenCount; } // For the purpose of the notifications, the unseen count should be capped at the num of // unread conversations. if (unseenCount > unreadCount) { unseenCount = unreadCount; } final int notificationId = getNotificationId(account.getAccountManagerAccount(), folder); NotificationKey notificationKey = new NotificationKey(account, folder); if (unseenCount == 0) { LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s", LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), LogUtils.sanitizeName(LOG_TAG, folder.persistentId)); nm.cancel(notificationId); cancelConversationNotifications(notificationKey, nm); return; } // We now have all we need to create the notification and the pending intent PendingIntent clickIntent = null; NotificationCompat.Builder notification = new NotificationCompat.Builder(context); NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender(); Map<Integer, NotificationBuilders> msgNotifications = new ArrayMap<Integer, NotificationBuilders>(); if (com.android.mail.utils.Utils.isRunningLOrLater()) { notification.setColor(context.getResources().getColor(R.color.notification_icon_color)); } if (unseenCount > 1) { notification.setSmallIcon(R.drawable.ic_notification_multiple_mail_24dp); } else { notification.setSmallIcon(R.drawable.ic_notification_mail_24dp); } notification.setTicker(account.getDisplayName()); notification.setVisibility(NotificationCompat.VISIBILITY_PRIVATE); notification.setCategory(NotificationCompat.CATEGORY_EMAIL); final long when; final long oldWhen = NotificationActionUtils.sNotificationTimestamps.get(notificationId); if (oldWhen != 0) { when = oldWhen; } else { when = System.currentTimeMillis(); } notification.setWhen(when); // The timestamp is now stored in the notification, so we can remove it from here NotificationActionUtils.sNotificationTimestamps.delete(notificationId); // Dispatch a CLEAR_NEW_MAIL_NOTIFICATIONS intent if the user taps the "X" next to a // notification. Also this intent gets fired when the user taps on a notification as // the AutoCancel flag has been set final Intent cancelNotificationIntent = new Intent( MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS); cancelNotificationIntent.setPackage(context.getPackageName()); cancelNotificationIntent.setData(Utils.appendVersionQueryParameter(context, folder.folderUri.fullUri)); cancelNotificationIntent.putExtra(Utils.EXTRA_ACCOUNT, account); cancelNotificationIntent.putExtra(Utils.EXTRA_FOLDER, folder); notification.setDeleteIntent( PendingIntent.getService(context, notificationId, cancelNotificationIntent, 0)); // Ensure that the notification is cleared when the user selects it notification.setAutoCancel(true); boolean eventInfoConfigured = false; final boolean isInbox = folder.folderUri.equals(account.settings.defaultInbox); final FolderPreferences folderPreferences = new FolderPreferences(context, account.getAccountId(), folder, isInbox); if (isInbox) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.getAccountId()); moveNotificationSetting(accountPreferences, folderPreferences); } if (!folderPreferences.areNotificationsEnabled()) { LogUtils.i(LOG_TAG, "Notifications are disabled for this folder; not notifying"); // Don't notify return; } if (unreadCount > 0) { // How can I order this properly? if (cursor.moveToNext()) { final Intent notificationIntent; // Launch directly to the conversation, if there is only 1 unseen conversation final boolean launchConversationMode = (unseenCount == 1); if (launchConversationMode) { notificationIntent = createViewConversationIntent(context, account, folder, cursor); } else { notificationIntent = createViewConversationIntent(context, account, folder, null); } Analytics.getInstance().sendEvent("notification_create", launchConversationMode ? "conversation" : "conversation_list", folder.getTypeDescription(), unseenCount); if (notificationIntent == null) { LogUtils.e(LOG_TAG, "Null intent when building notification"); return; } clickIntent = createClickPendingIntent(context, notificationIntent); configureLatestEventInfoFromConversation(context, account, folderPreferences, notification, wearableExtender, msgNotifications, notificationId, cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when, contactFetcher); eventInfoConfigured = true; } } final boolean vibrate = folderPreferences.isNotificationVibrateEnabled(); final String ringtoneUri = folderPreferences.getNotificationRingtoneUri(); final boolean notifyOnce = !folderPreferences.isEveryMessageNotificationEnabled(); if (!ignoreUnobtrusiveSetting && notifyOnce) { // If the user has "unobtrusive notifications" enabled, only alert the first time // new mail is received in this account. This is the default behavior. See // bugs 2412348 and 2413490. LogUtils.d(LOG_TAG, "Setting Alert Once"); notification.setOnlyAlertOnce(true); } LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), Boolean.toString(folderPreferences.isNotificationVibrateEnabled())); int defaults = 0; // Check if any current conversation notifications exist previously. Only notify if // one of them is new. boolean hasNewConversationNotification; Set<Integer> prevConversationNotifications = sConversationNotificationMap.get(notificationKey); if (prevConversationNotifications != null) { hasNewConversationNotification = false; for (Integer currentNotificationId : msgNotifications.keySet()) { if (!prevConversationNotifications.contains(currentNotificationId)) { hasNewConversationNotification = true; break; } } } else { hasNewConversationNotification = true; } LogUtils.d(LOG_TAG, "getAttention=%s,oldWhen=%s,hasNewConversationNotification=%s", getAttention, oldWhen, hasNewConversationNotification); /* * We do not want to notify if this is coming back from an Undo notification, hence the * oldWhen check. */ if (getAttention && oldWhen == 0 && hasNewConversationNotification) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.getAccountId()); if (accountPreferences.areNotificationsEnabled()) { if (vibrate) { defaults |= Notification.DEFAULT_VIBRATE; } notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri)); LogUtils.i(LOG_TAG, "New email in %s vibrateWhen: %s, playing notification: %s", LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), vibrate, ringtoneUri); } } // TODO(skennedy) Why do we do any of the above if we're just going to bail here? if (eventInfoConfigured) { defaults |= Notification.DEFAULT_LIGHTS; notification.setDefaults(defaults); if (oldWhen != 0) { // We do not want to display the ticker again if we are re-displaying this // notification (like from an Undo notification) notification.setTicker(null); } notification.extend(wearableExtender); // create the *public* form of the *private* notification we have been assembling final Notification publicNotification = createPublicNotification(context, account, folder, when, unseenCount, unreadCount, clickIntent); notification.setPublicVersion(publicNotification); nm.notify(notificationId, notification.build()); if (prevConversationNotifications != null) { Set<Integer> currentNotificationIds = msgNotifications.keySet(); for (Integer prevConversationNotificationId : prevConversationNotifications) { if (!currentNotificationIds.contains(prevConversationNotificationId)) { nm.cancel(prevConversationNotificationId); LogUtils.d(LOG_TAG, "canceling conversation notification %s", prevConversationNotificationId); } } } for (Map.Entry<Integer, NotificationBuilders> entry : msgNotifications.entrySet()) { NotificationBuilders builders = entry.getValue(); builders.notifBuilder.extend(builders.wearableNotifBuilder); nm.notify(entry.getKey(), builders.notifBuilder.build()); LogUtils.d(LOG_TAG, "notifying conversation notification %s", entry.getKey()); } Set<Integer> conversationNotificationIds = new HashSet<Integer>(); conversationNotificationIds.addAll(msgNotifications.keySet()); sConversationNotificationMap.put(notificationKey, conversationNotificationIds); } else { LogUtils.i(LOG_TAG, "event info not configured - not notifying"); } } finally { if (cursor != null) { cursor.close(); } } }
From source file:com.android.deskclock.data.TimerModel.java
/** * Updates the heads-up notification controlling expired timers. This heads-up notification is * displayed whether the application is open or not. *///from ww w . j a va 2 s.co m private void updateHeadsUpNotification() { // Nothing can be done with the heads-up notification without a valid service reference. if (mService == null) { return; } final List<Timer> expired = getExpiredTimers(); // If no expired timers exist, stop the service (which cancels the foreground notification). if (expired.isEmpty()) { mService.stopSelf(); mService = null; return; } // Generate some descriptive text, a title, and an action name based on the timer count. final int timerId; final String contentText; final String contentTitle; final String resetActionTitle; if (expired.size() > 1) { timerId = -1; contentText = mContext.getString(R.string.timer_multi_times_up, expired.size()); contentTitle = mContext.getString(R.string.timer_notification_label); resetActionTitle = mContext.getString(R.string.timer_stop_all); } else { final Timer timer = expired.get(0); timerId = timer.getId(); resetActionTitle = mContext.getString(R.string.timer_stop); contentText = mContext.getString(R.string.timer_times_up); final String label = timer.getLabel(); if (TextUtils.isEmpty(label)) { contentTitle = mContext.getString(R.string.timer_notification_label); } else { contentTitle = label; } } // Content intent shows the timer full screen when clicked. final Intent content = new Intent(mContext, ExpiredTimersActivity.class); final PendingIntent pendingContent = PendingIntent.getActivity(mContext, 0, content, PendingIntent.FLAG_UPDATE_CURRENT); // Full screen intent has flags so it is different than the content intent. final Intent fullScreen = new Intent(mContext, ExpiredTimersActivity.class) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); final PendingIntent pendingFullScreen = PendingIntent.getActivity(mContext, 0, fullScreen, PendingIntent.FLAG_UPDATE_CURRENT); // First action intent is either reset single timer or reset all timers. final Intent reset = TimerService.createResetExpiredTimersIntent(mContext); final PendingIntent pendingReset = PendingIntent.getService(mContext, 0, reset, PendingIntent.FLAG_UPDATE_CURRENT); final NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext).setWhen(0) .setOngoing(true).setLocalOnly(true).setAutoCancel(false).setContentText(contentText) .setContentTitle(contentTitle).setContentIntent(pendingContent) .setSmallIcon(R.drawable.stat_notify_timer).setFullScreenIntent(pendingFullScreen, true) .setPriority(NotificationCompat.PRIORITY_MAX).setDefaults(NotificationCompat.DEFAULT_LIGHTS) .addAction(R.drawable.ic_stop_24dp, resetActionTitle, pendingReset); // Add a second action if only a single timer is expired. if (expired.size() == 1) { // Second action intent adds a minute to a single timer. final Intent addMinute = TimerService.createAddMinuteTimerIntent(mContext, timerId); final PendingIntent pendingAddMinute = PendingIntent.getService(mContext, 0, addMinute, PendingIntent.FLAG_UPDATE_CURRENT); final String addMinuteTitle = mContext.getString(R.string.timer_plus_1_min); builder.addAction(R.drawable.ic_add_24dp, addMinuteTitle, pendingAddMinute); } // Update the notification. final Notification notification = builder.build(); final int notificationId = mNotificationModel.getExpiredTimerNotificationId(); mService.startForeground(notificationId, notification); }
From source file:com.example.android.wearable.wear.wearnotifications.MainActivity.java
private void generateMessagingStyleNotification() { Log.d(TAG, "generateMessagingStyleNotification()"); // Main steps for building a MESSAGING_STYLE notification: // 0. Get your data // 1. Build the MESSAGING_STYLE // 2. Add support for Wear 1.+ // 3. Set up main Intent for notification // 4. Set up RemoteInput (users can input directly from notification) // 5. Build and issue the notification // 0. Get your data (everything unique per Notification) MockDatabase.MessagingStyleCommsAppData messagingStyleCommsAppData = MockDatabase.getMessagingStyleData(); // 1. Build the Notification.Style (MESSAGING_STYLE) String contentTitle = messagingStyleCommsAppData.getContentTitle(); MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle( messagingStyleCommsAppData.getReplayName()) // You could set a different title to appear when the messaging style // is supported on device (24+) if you wish. In our case, we use the same // title. .setConversationTitle(contentTitle); // Adds all Messages // Note: Messages include the text, timestamp, and sender for (MessagingStyle.Message message : messagingStyleCommsAppData.getMessages()) { messagingStyle.addMessage(message); }/*from w ww. j a v a2s . com*/ // 2. Add support for Wear 1.+ // Since Wear 1.0 doesn't support the MESSAGING_STYLE, we use the BIG_TEXT_STYLE, so all the // text is visible. // This is basically a toString() of all the Messages above. String fullMessageForWearVersion1 = messagingStyleCommsAppData.getFullConversation(); Notification chatHistoryForWearV1 = new NotificationCompat.Builder(getApplicationContext()) .setStyle(new BigTextStyle().bigText(fullMessageForWearVersion1)).setContentTitle(contentTitle) .setSmallIcon(R.drawable.ic_launcher).setContentText(fullMessageForWearVersion1).build(); // Adds page with all text to support Wear 1.+. NotificationCompat.WearableExtender wearableExtenderForWearVersion1 = new NotificationCompat.WearableExtender() .addPage(chatHistoryForWearV1); // 3. Set up main Intent for notification Intent notifyIntent = new Intent(this, MessagingMainActivity.class); // When creating your Intent, you need to take into account the back state, i.e., what // happens after your Activity launches and the user presses the back button. // There are two options: // 1. Regular activity - You're starting an Activity that's part of the application's // normal workflow. // 2. Special activity - The user only sees this Activity if it's started from a // notification. In a sense, the Activity extends the notification by providing // information that would be hard to display in the notification itself. // Even though this sample's MainActivity doesn't link to the Activity this Notification // launches directly, i.e., it isn't part of the normal workflow, a chat app generally // always links to individual conversations as part of the app flow, so we will follow // option 1. // For an example of option 2, check out the BIG_TEXT_STYLE example. // For more information, check out our dev article: // https://developer.android.com/training/notify-user/navigation.html TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack stackBuilder.addParentStack(MessagingMainActivity.class); // Adds the Intent to the top of the stack stackBuilder.addNextIntent(notifyIntent); // Gets a PendingIntent containing the entire back stack PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); // 4. Set up RemoteInput, so users can input (keyboard and voice) from notification // Note: For API <24 (M and below) we need to use an Activity, so the lock-screen present // the auth challenge. For API 24+ (N and above), we use a Service (could be a // BroadcastReceiver), so the user can input from Notification or lock-screen (they have // choice to allow) without leaving the notification. // Create the RemoteInput specifying this key String replyLabel = getString(R.string.reply_label); RemoteInput remoteInput = new RemoteInput.Builder(MessagingIntentService.EXTRA_REPLY).setLabel(replyLabel) .build(); // Pending intent = // API <24 (M and below): activity so the lock-screen presents the auth challenge // API 24+ (N and above): this should be a Service or BroadcastReceiver PendingIntent replyActionPendingIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Intent intent = new Intent(this, MessagingIntentService.class); intent.setAction(MessagingIntentService.ACTION_REPLY); 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) // Allows system to generate replies by context of conversation .setAllowGeneratedReplies(true).build(); // 5. Build and issue the notification // Because we want this to be a new notification (not updating current notification), we // create a new Builder. Later, we update this same notification, so we need to save this // Builder globally (as outlined earlier). NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder( getApplicationContext()); GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder); // Builds and issues notification notificationCompatBuilder // MESSAGING_STYLE sets title and content for API 24+ (N and above) devices .setStyle(messagingStyle) // Title for API <24 (M and below) devices .setContentTitle(contentTitle) // Content for API <24 (M and below) devices .setContentText(messagingStyleCommsAppData.getContentText()).setSmallIcon(R.drawable.ic_launcher) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_person_black_48dp)) .setContentIntent(mainPendingIntent) // Set primary color (important for Wear 2.0 Notifications) .setColor(getResources().getColor(R.color.colorPrimary)) // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+) // devices and all Android Wear devices. If you have more than one notification and // you prefer a different summary notification, set a group key and create a // summary notification via // .setGroupSummary(true) // .setGroup(GROUP_KEY_YOUR_NAME_HERE) // Number of new notifications for API <24 (M and below) devices .setSubText(Integer.toString(messagingStyleCommsAppData.getNumberOfNewMessages())) .addAction(replyAction).setCategory(Notification.CATEGORY_MESSAGE) .setPriority(Notification.PRIORITY_HIGH) // Hides content on the lock-screen .setVisibility(Notification.VISIBILITY_PRIVATE) // Adds multiple pages for easy consumption on a wear device. .extend(wearableExtenderForWearVersion1); // 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 : messagingStyleCommsAppData.getParticipants()) { notificationCompatBuilder.addPerson(name); } Notification notification = notificationCompatBuilder.build(); mNotificationManagerCompat.notify(NOTIFICATION_ID, notification); }
From source file:com.geotrackin.gpslogger.GpsLoggingService.java
private void StopAlarm() { tracer.debug("GpsLoggingService.StopAlarm"); Intent i = new Intent(this, GpsLoggingService.class); i.putExtra("getnextpoint", true); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); nextPointAlarmManager.cancel(pi);/*from w w w. jav a 2s . co m*/ }
From source file:com.geotrackin.gpslogger.GpsLoggingService.java
private void SetAlarmForNextPoint() { tracer.debug("GpsLoggingService.SetAlarmForNextPoint"); Intent i = new Intent(this, GpsLoggingService.class); i.putExtra("getnextpoint", true); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); nextPointAlarmManager.cancel(pi);/*www . ja v a 2 s . co m*/ nextPointAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + AppSettings.getMinimumSeconds() * 1000, pi); }