List of usage examples for android.app PendingIntent getActivity
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, @Flags int flags)
From source file:com.hhunj.hhudata.ForegroundService.java
protected void showNotification(CharSequence from, CharSequence message) { // look up the notification manager service NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // The PendingIntent to launch our activity if the user selects this // notification //,// ww w. ja va 2 s . co m PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, IncomingMessageView.class), 0); // The ticker text, this uses a formatted string so our message could be // localized String tickerText = getString(R.string.imcoming_message_ticker_text, message); // construct the Notification object. Notification notif = new Notification(R.drawable.stat_sample, tickerText, System.currentTimeMillis()); // Set the info for the views that show in the notification panel. notif.setLatestEventInfo(this, from, message, contentIntent); // // Date dt = new Date(); if (IsDuringWorkHours(dt)) { notif.defaults |= (Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE); } else { notif.defaults |= (Notification.DEFAULT_VIBRATE); } // after a 100ms delay, vibrate for 250ms, pause for 100 ms and // then vibrate for 500ms.// notif.vibrate = new long[] { 100, 250, 100, 500 }; nm.notify(R.string.imcoming_message_ticker_text, notif); }
From source file:com.bonsai.btcreceive.WalletService.java
private void showStatusNotification() { // In this sample, we'll use the same text for the ticker and // the expanded notification CharSequence started_txt = getText(R.string.wallet_service_started); CharSequence info_txt = getText(R.string.wallet_service_info); Notification note = new Notification(R.drawable.ic_stat_notify, started_txt, System.currentTimeMillis()); Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0); // Set the info for the views that show in the notification panel. note.setLatestEventInfo(this, getText(R.string.wallet_service_label), info_txt, contentIntent); note.flags |= Notification.FLAG_NO_CLEAR; startForeground(NOTIFICATION, note); }
From source file:edu.mit.mobile.android.locast.sync.MediaSync.java
/** * Checks the local file system and checks to see if the given media resource has been * downloaded successfully already. If not, it will download it from the server and store it in * the filesystem. This uses the last-modified header and file length to determine if a media * resource is up to date./*from ww w. j a v a2 s . c om*/ * * This method blocks for the course of the download, but shows a progress notification. * * @param pubUri * the http:// uri of the public resource * @param saveFile * the file that the resource will be saved to * @param castMediaUri * the content:// uri of the cast * @return true if anything has changed. False if this function has determined it doesn't need * to do anything. * @throws SyncException */ public boolean downloadMediaFile(String pubUri, File saveFile, Uri castMediaUri) throws SyncException { final NetworkClient nc = NetworkClient.getInstance(this, Authenticator.getFirstAccount(this)); try { boolean dirty = true; // String contentType = null; if (saveFile.exists()) { final HttpResponse headRes = nc.head(pubUri); final long serverLength = Long.valueOf(headRes.getFirstHeader("Content-Length").getValue()); // XXX should really be checking the e-tag too, but this will be // fine for our application. final Header remoteLastModifiedHeader = headRes.getFirstHeader("last-modified"); long remoteLastModified = 0; if (remoteLastModifiedHeader != null) { remoteLastModified = DateUtils.parseDate(remoteLastModifiedHeader.getValue()).getTime(); } final HttpEntity entity = headRes.getEntity(); if (entity != null) { entity.consumeContent(); } if (saveFile.length() == serverLength && saveFile.lastModified() >= remoteLastModified) { if (DEBUG) { Log.i(TAG, "Local copy of cast " + saveFile + " seems to be the same as the one on the server. Not re-downloading."); } dirty = false; } // fall through and re-download, as we have a different size // file locally. } if (dirty) { final Uri castUri = CastMedia.getCast(castMediaUri); String castTitle = Cast.getTitle(this, castUri); if (castTitle == null) { castTitle = "untitled"; } final HttpResponse res = nc.get(pubUri); final HttpEntity ent = res.getEntity(); final ProgressNotification notification = new ProgressNotification(this, getString(R.string.sync_downloading_cast, castTitle), ProgressNotification.TYPE_DOWNLOAD, PendingIntent.getActivity(this, 0, new Intent(Intent.ACTION_VIEW, castUri).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 0), false); final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); final NotificationProgressListener npl = new NotificationProgressListener(nm, notification, ent.getContentLength(), 0); final InputStreamWatcher is = new InputStreamWatcher(ent.getContent(), npl); try { if (DEBUG) { Log.d(TAG, "Downloading " + pubUri + " and saving it in " + saveFile.getAbsolutePath()); } final FileOutputStream fos = new FileOutputStream(saveFile); StreamUtils.inputStreamToOutputStream(is, fos); fos.close(); // set the file's last modified to match the remote. // We can check this later to see if everything is up to // date. final Header lastModified = res.getFirstHeader("last-modified"); if (lastModified != null) { saveFile.setLastModified(DateUtils.parseDate(lastModified.getValue()).getTime()); } // contentType = ent.getContentType().getValue(); } finally { npl.done(); ent.consumeContent(); is.close(); } // XXX avoid this to prevent adding to local collection // final String filePath = saveFile.getAbsolutePath(); // scanMediaItem(castMediaUri, filePath, contentType); return true; } } catch (final Exception e) { final SyncException se = new SyncException("Error downloading content item."); se.initCause(e); throw se; } return false; }
From source file:com.dmbstream.android.util.Util.java
public static void showPlayingNotification(final Context context, final DownloadServiceImpl downloadService, Handler handler, Track song) { // Use the same text for the ticker and the expanded notification String title = song.title;//from ww w . ja v a2 s . c o m String text = song.artist; // Set the icon, scrolling text and timestamp final Notification notification = new Notification(R.drawable.notify_playing, title, System.currentTimeMillis()); notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.partial_notification); // set the text for the notifications contentView.setTextViewText(R.id.notification_title, title); contentView.setTextViewText(R.id.notification_artist, text); Pair<Integer, Integer> colors = getNotificationTextColors(context); if (colors.getFirst() != null) { contentView.setTextColor(R.id.notification_title, colors.getFirst()); } if (colors.getSecond() != null) { contentView.setTextColor(R.id.notification_artist, colors.getSecond()); } notification.contentView = contentView; // Send them to the main menu when if they click the notification // TODO: Send them to the concert, playlist, compilation details or chat page? Intent notificationIntent = new Intent(context, MainMenuActivity.class); notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); // Send the notification and put the service in the foreground. handler.post(new Runnable() { @Override public void run() { startForeground(downloadService, Constants.NOTIFICATION_ID_PLAYING, notification); } }); // Update widget DmbstreamAppWidgetProvider.getInstance().notifyChange(context, downloadService, true); }
From source file:org.gaeproxy.GAEProxyService.java
@Override public void onCreate() { super.onCreate(); mShutdownReceiver = new BroadcastReceiver() { @Override// w w w . j a v a 2 s . c om public void onReceive(Context context, Intent intent) { stopSelf(); } }; IntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN); registerReceiver(mShutdownReceiver, filter); EasyTracker.getTracker().trackEvent("service", "start", getVersionName(), 0L); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); settings = PreferenceManager.getDefaultSharedPreferences(this); Intent intent = new Intent(this, GAEProxyActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); pendIntent = PendingIntent.getActivity(this, 0, intent, 0); notification = new Notification(); try { mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature); mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature); } catch (NoSuchMethodException e) { // Running on an older platform. mStartForeground = mStopForeground = null; } try { mSetForeground = getClass().getMethod("setForeground", mSetForegroundSignature); } catch (NoSuchMethodException e) { throw new IllegalStateException("OS doesn't have Service.startForeground OR Service.setForeground!"); } }
From source file:me.calebjones.blogsite.network.PostDownloader.java
public void download(final List<String> postID) { final DatabaseManager databaseManager = new DatabaseManager(this); try {//from w ww. ja v a 2s . c o m final int num = postID.size() - 1; final CountDownLatch latch = new CountDownLatch(num); final Executor executor = Executors.newFixedThreadPool(15); for (int i = 1; i <= postID.size() - 1; i++) { final int count = i; final int index = Integer.parseInt(postID.get(i)); executor.execute(new Runnable() { @Override public void run() { try { if (index != 404) { String url = String.format(POST_URL, index); Request newReq = new Request.Builder().url(url).build(); Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq) .execute(); if (!newResp.isSuccessful() && !(newResp.code() == 404) && !(newResp.code() == 403)) { Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url); LocalBroadcastManager.getInstance(PostDownloader.this) .sendBroadcast(new Intent(DOWNLOAD_FAIL)); throw new IOException(); } if (newResp.code() == 404) { return; } String resp = newResp.body().string(); JSONObject jObject = new JSONObject(resp); Posts item1 = new Posts(); //If the item is not a post break out of loop and ignore it if (!(jObject.optString("type").equals("post"))) { return; } item1.setTitle(jObject.optString("title")); item1.setContent(jObject.optString("content")); item1.setExcerpt(jObject.optString("excerpt")); item1.setPostID(jObject.optInt("ID")); item1.setURL(jObject.optString("URL")); //Parse the Date! String date = jObject.optString("date"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); Date newDate = format.parse(date); format = new SimpleDateFormat("yyyy-MM-dd"); date = format.format(newDate); item1.setDate(date); //Cuts out all the Child nodes and gets only the tags. JSONObject Tobj = new JSONObject(jObject.optString("tags")); JSONArray Tarray = Tobj.names(); String tagsList = null; if (Tarray != null && (Tarray.length() > 0)) { for (int c = 0; c < Tarray.length(); c++) { if (tagsList != null) { String thisTag = Tarray.getString(c); tagsList = tagsList + ", " + thisTag; } else { String thisTag = Tarray.getString(c); tagsList = thisTag; } } item1.setTags(tagsList); } else { item1.setTags(""); } JSONObject Cobj = new JSONObject(jObject.optString("categories")); JSONArray Carray = Cobj.names(); String catsList = null; if (Carray != null && (Carray.length() > 0)) { for (int c = 0; c < Carray.length(); c++) { if (catsList != null) { String thisCat = Carray.getString(c); catsList = catsList + ", " + thisCat; } else { String thisCat = Carray.getString(c); catsList = thisCat; } } item1.setCategories(catsList); } else { item1.setCategories(""); } Integer ImageLength = jObject.optString("featured_image").length(); if (ImageLength == 0) { item1.setFeaturedImage(null); } else { item1.setFeaturedImage(jObject.optString("featured_image")); } if (item1 != null) { databaseManager.addPost(item1); Log.d("PostDownloader", index + " database..."); double progress = ((double) count / num) * 100; setProgress((int) progress, item1.getTitle(), count); Intent intent = new Intent(DOWNLOAD_PROGRESS); intent.putExtra(PROGRESS, progress); intent.putExtra(NUMBER, num); intent.putExtra(TITLE, item1.getTitle()); LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent); } } } catch (IOException | JSONException | ParseException e) { if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setDownloading(false); e.printStackTrace(); } finally { latch.countDown(); } } }); } try { latch.await(); } catch (InterruptedException e) { if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setDownloading(false); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL)); mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download) .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false); mNotifyManager.notify(NOTIF_ID, mBuilder.build()); throw new IOException(e); } if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setDownloading(false); Log.d("PostDownloader", "Broadcast Sent!"); Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading()); Intent mainActIntent = new Intent(this, MainActivity.class); PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent, PendingIntent.FLAG_UPDATE_CURRENT); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS)); mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done) .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false); mNotifyManager.notify(NOTIF_ID, mBuilder.build()); } catch (IOException e) { if (SharedPrefs.getInstance().isFirstDownload()) { SharedPrefs.getInstance().setFirstDownload(false); } SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis()); SharedPrefs.getInstance().setDownloading(false); e.printStackTrace(); LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL)); mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true) .setOngoing(false); mNotifyManager.notify(NOTIF_ID, mBuilder.build()); } }
From source file:at.ac.uniklu.mobile.sportal.service.MutingService.java
private void notifyUser(int id, boolean ongoing, String tickerText, String contentTitle, String contentText, int icon, Intent intent) { NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new NotificationCompat.Builder(this).setSmallIcon(icon).setTicker(tickerText) .setContentText(contentText).setContentTitle(contentTitle).setContentIntent(contentIntent) .setWhen(System.currentTimeMillis()).setOngoing(ongoing).build(); notificationManager.notify(id, notification); }
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. ja v a2s. 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.daskiworks.ghwatch.backend.UnreadNotificationsService.java
protected void fireAndroidNotification(NotificationStream newStream, NotificationStream oldStream) { if (newStream == null || !PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY, true)) return;/*from www . j a v a 2 s. co m*/ Log.d(TAG, "fireAndroidNotification count before filter " + newStream.size()); newStream = filterForAndroidNotification(newStream); Log.d(TAG, "fireAndroidNotification count after filter " + newStream.size()); if (newStream.isNewNotification(oldStream)) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.github_notification) .setContentTitle(context.getString(R.string.an_title_more)) .setPriority(NotificationCompat.PRIORITY_DEFAULT); mBuilder.setAutoCancel(true); if (newStream.size() > 1) mBuilder.setNumber(newStream.size()); boolean allFromOne = newStream.allNotificationsFromSameRepository(); if (newStream.size() == 1 || allFromOne) { // only one repository Notification n = newStream.get(0); Bitmap b = ImageLoader.getInstance(context).loadImageWithFileLevelCache(n.getRepositoryAvatarUrl()); if (b != null) { mBuilder.setLargeIcon(b); } else { mBuilder.setLargeIcon( BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification)); } mBuilder.setContentText(n.getRepositoryFullName()); } else { mBuilder.setLargeIcon( BitmapFactory.decodeResource(context.getResources(), R.drawable.github_notification)); } Intent resultIntent = null; if (newStream.size() == 1) { mBuilder.setContentTitle(context.getString(R.string.an_title_one)); Notification n = newStream.get(0); mBuilder.setContentText(n.getRepositoryFullName() + ": " + n.getSubjectTitle()); NotificationCompat.BigTextStyle btStyle = new NotificationCompat.BigTextStyle(); btStyle.bigText(n.getSubjectTitle()); btStyle.setSummaryText(n.getRepositoryFullName()); mBuilder.setStyle(btStyle); Intent actionIntent = new Intent(context, MarkNotifiationAsReadReceiver.class); actionIntent.putExtra(MarkNotifiationAsReadReceiver.INTENT_EXTRA_KEY_ID, n.getId()); mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_mark_read), PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT)); resultIntent = new Intent(context, MainActivity.class); } else { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); for (Notification n : newStream) { if (allFromOne) { inboxStyle.addLine(n.getSubjectTitle()); } else { inboxStyle.addLine(n.getRepositoryFullName() + ": " + n.getSubjectTitle()); } } if (allFromOne) inboxStyle.setSummaryText(newStream.get(0).getRepositoryFullName()); else inboxStyle.setSummaryText(" "); mBuilder.setStyle(inboxStyle); Intent actionIntent = new Intent(context, MainActivity.class); actionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); actionIntent.setAction(MainActivity.INTENT_ACTION_DISMISS_ALL); mBuilder.addAction(R.drawable.ic_action_dismis_all, context.getString(R.string.action_all_read), PendingIntent.getActivity(context, 0, actionIntent, 0)); resultIntent = new Intent(context, MainActivity.class); } resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); resultIntent.setAction(MainActivity.INTENT_ACTION_SHOW); PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0); mBuilder.setContentIntent(resultPendingIntent); String nsound = PreferencesUtils.getString(context, PreferencesUtils.PREF_NOTIFY_SOUND, null); Log.d(TAG, "Notification sound from preference: " + nsound); if (nsound != null) { mBuilder.setSound(Uri.parse(nsound)); } if (PreferencesUtils.getBoolean(context, PreferencesUtils.PREF_NOTIFY_VIBRATE, true)) { mBuilder.setVibrate(new long[] { 0, 300, 100, 150, 100, 150 }); } mBuilder.setLights(0xffffffff, 100, 4000); // mId allows you to update the notification later on. Utils.getNotificationManager(context).notify(ANDROID_NOTIFICATION_ID, mBuilder.build()); ActivityTracker.sendEvent(context, ActivityTracker.CAT_NOTIF, "new_notif", "notif count: " + newStream.size(), Long.valueOf(newStream.size())); } else if (newStream.isEmpty()) { // #54 dismiss previous android notification if no any Github notification is available (as it was read on another device) Utils.getNotificationManager(context).cancel(ANDROID_NOTIFICATION_ID); } }
From source file:net.tac42.subtails.util.Util.java
public static void showPlayingNotification(final Context context, final DownloadServiceImpl downloadService, Handler handler, MusicDirectory.Entry song) { // Use the same text for the ticker and the expanded notification String title = song.getTitle(); String text = song.getArtist(); // Set the icon, scrolling text and timestamp final Notification notification = new Notification(R.drawable.stat_notify_playing, title, System.currentTimeMillis()); notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification); // Set the album art. try {/* w w w.j a v a 2s .c om*/ int size = context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight(); Bitmap bitmap = FileUtil.getAlbumArtBitmap(context, song, size); if (bitmap == null) { // set default album art contentView.setImageViewResource(R.id.notification_image, R.drawable.unknown_album); } else { contentView.setImageViewBitmap(R.id.notification_image, bitmap); } } catch (Exception x) { Log.w(TAG, "Failed to get notification cover art", x); contentView.setImageViewResource(R.id.notification_image, R.drawable.unknown_album); } // set the text for the notifications contentView.setTextViewText(R.id.notification_title, title); contentView.setTextViewText(R.id.notification_artist, text); Pair<Integer, Integer> colors = getNotificationTextColors(context); if (colors.getFirst() != null) { contentView.setTextColor(R.id.notification_title, colors.getFirst()); } if (colors.getSecond() != null) { contentView.setTextColor(R.id.notification_artist, colors.getSecond()); } notification.contentView = contentView; Intent notificationIntent = new Intent(context, DownloadActivity.class); notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); // Send the notification and put the service in the foreground. handler.post(new Runnable() { @Override public void run() { startForeground(downloadService, Constants.NOTIFICATION_ID_PLAYING, notification); } }); // Update widget SubtailsAppWidgetProvider.getInstance().notifyChange(context, downloadService, true); }