List of usage examples for android.app Notification DEFAULT_LIGHTS
int DEFAULT_LIGHTS
To view the source code for android.app Notification DEFAULT_LIGHTS.
Click Source Link
From source file:com.bonsai.btcreceive.WalletService.java
private void showEventNotification(int noteId, int icon, String title, String msg) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(icon) .setContentTitle(title).setContentText(msg).setAutoCancel(true).setDefaults( Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE); // Creates an explicit intent for an Activity in your app Intent intent = new Intent(this, MainActivity.class); // The stack builder object will contain an artificial back // stack for the started Activity. This ensures that // navigating backward from the Activity leads out of your // application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(MainActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(intent);/* w ww. ja v a 2s.c o m*/ PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mNM.notify(noteId, mBuilder.build()); }
From source file:im.vector.notifications.NotificationUtils.java
/** * Add the notification sound.//from w ww . j av a2s .com * * @param context the context * @param builder the notification builder * @param isBackground true if the notification is a background one * @param isBing true if the notification should play sound */ @SuppressLint("NewApi") private static void manageNotificationSound(Context context, NotificationCompat.Builder builder, boolean isBackground, boolean isBing) { @ColorInt int highlightColor = ContextCompat.getColor(context, R.color.vector_fuchsia_color); int defaultColor = Color.TRANSPARENT; if (isBackground) { builder.setPriority(NotificationCompat.PRIORITY_DEFAULT); builder.setColor(defaultColor); } else if (isBing) { builder.setPriority(NotificationCompat.PRIORITY_HIGH); builder.setColor(highlightColor); } else { builder.setPriority(NotificationCompat.PRIORITY_DEFAULT); builder.setColor(Color.TRANSPARENT); } if (!isBackground) { builder.setDefaults(Notification.DEFAULT_LIGHTS); if (isBing && (null != PreferencesManager.getNotificationRingTone(context))) { builder.setSound(PreferencesManager.getNotificationRingTone(context)); if (Build.VERSION.SDK_INT >= 26) { builder.setChannelId(NOISY_NOTIFICATION_CHANNEL_ID); } } // turn the screen on for 3 seconds if (Matrix.getInstance(VectorApp.getInstance()).getSharedGCMRegistrationManager().isScreenTurnedOn()) { PowerManager pm = (PowerManager) VectorApp.getInstance().getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock( PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "manageNotificationSound"); wl.acquire(3000); wl.release(); } } }
From source file:com.piusvelte.sonet.core.SonetService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else/* ww w. j av a2 s . co m*/ putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(SonetService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(SonetService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(SonetService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(SonetService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mSonetCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(SonetService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(SonetService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Sonet.default_message_bg_color; int profile_bg_color = Sonet.default_message_bg_color; int friend_bg_color = Sonet.default_friend_bg_color; boolean icon = true; int status_count = Sonet.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(SonetService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Sonet.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(SonetService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Sonet.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(SonetService.this, widget, Sonet.INVALID_ACCOUNT_ID); } initAccountSettings(SonetService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Sonet.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(SonetService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(SonetService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(SonetService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(SonetService.this, 0, (Sonet .getPackageIntent(SonetService.this, SonetNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }
From source file:com.shafiq.myfeedle.core.MyfeedleService.java
private void start(Intent intent) { if (intent != null) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if (ACTION_REFRESH.equals(action)) { if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS)) putValidatedUpdates(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), 1); else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 1); else if (intent.getData() != null) putValidatedUpdates(new int[] { Integer.parseInt(intent.getData().getLastPathSegment()) }, 1); else/*from ww w.j a v a 2 s . c o m*/ putValidatedUpdates(null, 0); } else if (LauncherIntent.Action.ACTION_READY.equals(action)) { if (intent.hasExtra(EXTRA_SCROLLABLE_VERSION) && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { int scrollableVersion = intent.getIntExtra(EXTRA_SCROLLABLE_VERSION, 1); int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // check if the scrollable needs to be built Cursor widget = this.getContentResolver().query(Widgets.getContentUri(MyfeedleService.this), new String[] { Widgets._ID, Widgets.SCROLLABLE }, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }, null); if (widget.moveToFirst()) { if (widget.getInt(widget.getColumnIndex(Widgets.SCROLLABLE)) < scrollableVersion) { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } else putValidatedUpdates(new int[] { appWidgetId }, 1); } else { ContentValues values = new ContentValues(); values.put(Widgets.SCROLLABLE, scrollableVersion); // set the scrollable version this.getContentResolver().update(Widgets.getContentUri(MyfeedleService.this), values, Widgets.WIDGET + "=?", new String[] { Integer.toString(appWidgetId) }); putValidatedUpdates(new int[] { appWidgetId }, 1); } widget.close(); } else if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)) { // requery putValidatedUpdates(new int[] { intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) }, 0); } } else if (SMS_RECEIVED.equals(action)) { // parse the sms, and notify any widgets which have sms enabled Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); AsyncTask<SmsMessage, String, int[]> smsLoader = new AsyncTask<SmsMessage, String, int[]>() { @Override protected int[] doInBackground(SmsMessage... msg) { // check if SMS is enabled anywhere Cursor widgets = getContentResolver().query( Widget_accounts_view.getContentUri(MyfeedleService.this), new String[] { Widget_accounts_view._ID, Widget_accounts_view.WIDGET, Widget_accounts_view.ACCOUNT }, Widget_accounts_view.SERVICE + "=?", new String[] { Integer.toString(SMS) }, null); int[] appWidgetIds = new int[widgets.getCount()]; if (widgets.moveToFirst()) { // insert this message to the statuses db and requery scrollable/rebuild widget // check if this is a contact String phone = msg[0].getOriginatingAddress(); String friend = phone; byte[] profile = null; Uri content_uri = null; // unknown numbers crash here in the emulator Cursor phones = getContentResolver().query( Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.PhoneLookup._ID }, null, null, null); if (phones.moveToFirst()) content_uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, phones.getLong(0)); else { Cursor emails = getContentResolver().query( Uri.withAppendedPath( ContactsContract.CommonDataKinds.Email.CONTENT_FILTER_URI, Uri.encode(phone)), new String[] { ContactsContract.CommonDataKinds.Email._ID }, null, null, null); if (emails.moveToFirst()) content_uri = ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, emails.getLong(0)); emails.close(); } phones.close(); if (content_uri != null) { // load contact Cursor contacts = getContentResolver().query(content_uri, new String[] { ContactsContract.Contacts.DISPLAY_NAME }, null, null, null); if (contacts.moveToFirst()) friend = contacts.getString(0); contacts.close(); profile = getBlob(ContactsContract.Contacts .openContactPhotoInputStream(getContentResolver(), content_uri)); } long accountId = widgets.getLong(2); long id; ContentValues values = new ContentValues(); values.put(Entities.ESID, phone); values.put(Entities.FRIEND, friend); values.put(Entities.PROFILE, profile); values.put(Entities.ACCOUNT, accountId); Cursor entity = getContentResolver().query( Entities.getContentUri(MyfeedleService.this), new String[] { Entities._ID }, Entities.ACCOUNT + "=? and " + Entities.ESID + "=?", new String[] { Long.toString(accountId), mMyfeedleCrypto.Encrypt(phone) }, null); if (entity.moveToFirst()) { id = entity.getLong(0); getContentResolver().update(Entities.getContentUri(MyfeedleService.this), values, Entities._ID + "=?", new String[] { Long.toString(id) }); } else id = Long.parseLong(getContentResolver() .insert(Entities.getContentUri(MyfeedleService.this), values) .getLastPathSegment()); entity.close(); values.clear(); Long created = msg[0].getTimestampMillis(); values.put(Statuses.CREATED, created); values.put(Statuses.ENTITY, id); values.put(Statuses.MESSAGE, msg[0].getMessageBody()); values.put(Statuses.SERVICE, SMS); while (!widgets.isAfterLast()) { int widget = widgets.getInt(1); appWidgetIds[widgets.getPosition()] = widget; // get settings boolean time24hr = true; int status_bg_color = Myfeedle.default_message_bg_color; int profile_bg_color = Myfeedle.default_message_bg_color; int friend_bg_color = Myfeedle.default_friend_bg_color; boolean icon = true; int status_count = Myfeedle.default_statuses_per_account; int notifications = 0; Cursor c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(Myfeedle.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) { c.close(); c = getContentResolver().query( Widgets_settings.getContentUri(MyfeedleService.this), new String[] { Widgets.TIME24HR, Widgets.MESSAGES_BG_COLOR, Widgets.ICON, Widgets.STATUSES_PER_ACCOUNT, Widgets.SOUND, Widgets.VIBRATE, Widgets.LIGHTS, Widgets.PROFILES_BG_COLOR, Widgets.FRIEND_BG_COLOR }, Widgets.WIDGET + "=? and " + Widgets.ACCOUNT + "=?", new String[] { Integer.toString(AppWidgetManager.INVALID_APPWIDGET_ID), Long.toString(Myfeedle.INVALID_ACCOUNT_ID) }, null); if (!c.moveToFirst()) initAccountSettings(MyfeedleService.this, AppWidgetManager.INVALID_APPWIDGET_ID, Myfeedle.INVALID_ACCOUNT_ID); if (widget != AppWidgetManager.INVALID_APPWIDGET_ID) initAccountSettings(MyfeedleService.this, widget, Myfeedle.INVALID_ACCOUNT_ID); } initAccountSettings(MyfeedleService.this, widget, accountId); } if (c.moveToFirst()) { time24hr = c.getInt(0) == 1; status_bg_color = c.getInt(1); icon = c.getInt(2) == 1; status_count = c.getInt(3); if (c.getInt(4) == 1) notifications |= Notification.DEFAULT_SOUND; if (c.getInt(5) == 1) notifications |= Notification.DEFAULT_VIBRATE; if (c.getInt(6) == 1) notifications |= Notification.DEFAULT_LIGHTS; profile_bg_color = c.getInt(7); friend_bg_color = c.getInt(8); } c.close(); values.put(Statuses.CREATEDTEXT, Myfeedle.getCreatedText(created, time24hr)); // update the bg and icon // create the status_bg values.put(Statuses.STATUS_BG, createBackground(status_bg_color)); // friend_bg values.put(Statuses.FRIEND_BG, createBackground(friend_bg_color)); // profile_bg values.put(Statuses.PROFILE_BG, createBackground(profile_bg_color)); values.put(Statuses.ICON, icon ? getBlob(getResources(), map_icons[SMS]) : null); // insert the message values.put(Statuses.WIDGET, widget); values.put(Statuses.ACCOUNT, accountId); getContentResolver().insert(Statuses.getContentUri(MyfeedleService.this), values); // check the status count, removing old sms Cursor statuses = getContentResolver().query( Statuses.getContentUri(MyfeedleService.this), new String[] { Statuses._ID }, Statuses.WIDGET + "=? and " + Statuses.ACCOUNT + "=?", new String[] { Integer.toString(widget), Long.toString(accountId) }, Statuses.CREATED + " desc"); if (statuses.moveToFirst()) { while (!statuses.isAfterLast()) { if (statuses.getPosition() >= status_count) { getContentResolver().delete( Statuses.getContentUri(MyfeedleService.this), Statuses._ID + "=?", new String[] { Long.toString(statuses .getLong(statuses.getColumnIndex(Statuses._ID))) }); } statuses.moveToNext(); } } statuses.close(); if (notifications != 0) publishProgress(Integer.toString(notifications), friend + " sent a message"); widgets.moveToNext(); } } widgets.close(); return appWidgetIds; } @Override protected void onProgressUpdate(String... updates) { int notifications = Integer.parseInt(updates[0]); if (notifications != 0) { Notification notification = new Notification(R.drawable.notification, updates[1], System.currentTimeMillis()); notification.setLatestEventInfo(getBaseContext(), "New messages", updates[1], PendingIntent.getActivity(MyfeedleService.this, 0, (Myfeedle.getPackageIntent(MyfeedleService.this, MyfeedleNotifications.class)), 0)); notification.defaults |= notifications; ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)) .notify(NOTIFY_ID, notification); } } @Override protected void onPostExecute(int[] appWidgetIds) { // remove self from thread list if (!mSMSLoaders.isEmpty()) mSMSLoaders.remove(this); putValidatedUpdates(appWidgetIds, 0); } }; mSMSLoaders.add(smsLoader); smsLoader.execute(msg); } } else if (ACTION_PAGE_DOWN.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_DOWN, 0)); else if (ACTION_PAGE_UP.equals(action)) (new PagingTask()).execute(Integer.parseInt(intent.getData().getLastPathSegment()), intent.getIntExtra(ACTION_PAGE_UP, 0)); else { // this might be a widget update from the widget refresh button int appWidgetId; try { appWidgetId = Integer.parseInt(action); putValidatedUpdates(new int[] { appWidgetId }, 1); } catch (NumberFormatException e) { Log.d(TAG, "unknown action:" + action); } } } }
From source file:com.bonsai.wallet32.WalletService.java
private void showEventNotification(int noteId, int icon, String title, String msg) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(icon) .setContentTitle(title).setContentText(msg).setAutoCancel(true).setDefaults( Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE); // Creates an explicit intent for an Activity in your app Intent intent = new Intent(this, ViewTransactionsActivity.class); // The stack builder object will contain an artificial back // stack for the started Activity. This ensures that // navigating backward from the Activity leads out of your // application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(ViewTransactionsActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(intent);//from www . java2 s .co m PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mNM.notify(noteId, mBuilder.build()); }
From source file:br.com.arlsoft.pushclient.PushClientModule.java
public static void sendNotification(Bundle extras) { if (extras == null || extras.isEmpty()) return;/* w w w .j a v a2 s . co m*/ TiApplication appContext = TiApplication.getInstance(); int appIconId = appContext.getResources().getIdentifier("appicon", "drawable", appContext.getPackageName()); String appName = appContext.getAppInfo().getName(); Bundle extrasRoot = extras; int badgeCount = -1; int notificationId = 0; String notificationTitle = null; String notificationText = null; String notificationTicker = null; Uri notificationSound = null; int notificationDefaults = 0; // TEXT if (extras.containsKey("text")) { notificationText = extras.getString("text"); } else if (extras.containsKey("alert")) { notificationText = extras.getString("alert"); } else if (extras.containsKey("message")) { notificationText = extras.getString("message"); } else if (extras.containsKey("data")) { try { JSONObject reader = new JSONObject(extras.getString("data")); Bundle newExtras = new Bundle(); for (int i = 0; i < reader.names().length(); i++) { String key = reader.names().getString(i); newExtras.putString(key, reader.getString(key)); } if (newExtras.containsKey("text")) { notificationText = newExtras.getString("text"); extras = newExtras; } else if (newExtras.containsKey("alert")) { notificationText = newExtras.getString("alert"); extras = newExtras; } else if (newExtras.containsKey("message")) { notificationText = newExtras.getString("message"); extras = newExtras; } } catch (JSONException e) { String text = extras.getString("data"); if (text != null) { notificationText = text; } } } else if (extras.containsKey("msg")) { try { JSONObject reader = new JSONObject(extras.getString("msg")); Bundle newExtras = new Bundle(); for (int i = 0; i < reader.names().length(); i++) { String key = reader.names().getString(i); newExtras.putString(key, reader.getString(key)); } if (newExtras.containsKey("text")) { notificationText = newExtras.getString("text"); extras = newExtras; } else if (newExtras.containsKey("alert")) { notificationText = newExtras.getString("alert"); extras = newExtras; } else if (newExtras.containsKey("message")) { notificationText = newExtras.getString("message"); extras = newExtras; } } catch (JSONException e) { String text = extras.getString("msg"); if (text != null) { notificationText = text; } } } else if (extras.containsKey("default")) { try { JSONObject reader = new JSONObject(extras.getString("default")); Bundle newExtras = new Bundle(); for (int i = 0; i < reader.names().length(); i++) { String key = reader.names().getString(i); newExtras.putString(key, reader.getString(key)); } if (newExtras.containsKey("text")) { notificationText = newExtras.getString("text"); extras = newExtras; } else if (newExtras.containsKey("alert")) { notificationText = newExtras.getString("alert"); extras = newExtras; } else if (newExtras.containsKey("message")) { notificationText = newExtras.getString("message"); extras = newExtras; } } catch (JSONException e) { String text = extras.getString("default"); if (text != null) { notificationText = text; } } } else if (extras.containsKey("payload")) { try { JSONObject reader = new JSONObject(extras.getString("payload")); Bundle newExtras = new Bundle(); for (int i = 0; i < reader.names().length(); i++) { String key = reader.names().getString(i); newExtras.putString(key, reader.getString(key)); } if (newExtras.containsKey("text")) { notificationText = newExtras.getString("text"); extras = newExtras; } else if (newExtras.containsKey("alert")) { notificationText = newExtras.getString("alert"); extras = newExtras; } else if (newExtras.containsKey("message")) { notificationText = newExtras.getString("message"); extras = newExtras; } } catch (JSONException e) { String text = extras.getString("payload"); if (text != null) { notificationText = text; } } } // TITLE if (extras.containsKey("title")) { notificationTitle = extras.getString("title"); } else { notificationTitle = appName; } // TICKER if (extras.containsKey("ticker")) { notificationTicker = extras.getString("ticker"); } else { notificationTicker = notificationText; } // SOUND if (extras.containsKey("sound")) { if (extras.getString("sound").equalsIgnoreCase("default")) { notificationDefaults |= Notification.DEFAULT_SOUND; } else { File file = null; // getResourcesDirectory file = new File("app://" + extras.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // getResourcesDirectory + sound folder file = new File("app://sound/" + extras.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // getExternalStorageDirectory file = new File("appdata://" + extras.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // getExternalStorageDirectory + sound folder file = new File("appdata://sound/" + extras.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // res folder int soundId = appContext.getResources().getIdentifier(extras.getString("sound"), "raw", appContext.getPackageName()); if (soundId != 0) { notificationSound = Uri.parse("android.resource://" + appContext.getPackageName() + "/raw/" + soundId); } else { // res folder without file extension String soundFile = extras.getString("sound").split("\\.")[0]; soundId = appContext.getResources().getIdentifier(soundFile, "raw", appContext.getPackageName()); if (soundId != 0) { notificationSound = Uri.parse("android.resource://" + appContext.getPackageName() + "/raw/" + soundId); } } } } } } } } else if (extrasRoot.containsKey("sound")) { if (extrasRoot.getString("sound").equalsIgnoreCase("default")) { notificationDefaults |= Notification.DEFAULT_SOUND; } else { File file = null; // getResourcesDirectory file = new File("app://" + extrasRoot.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // getResourcesDirectory + sound folder file = new File("app://sound/" + extrasRoot.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // getExternalStorageDirectory file = new File("appdata://" + extrasRoot.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // getExternalStorageDirectory + sound folder file = new File("appdata://sound/" + extrasRoot.getString("sound")); if (file != null && file.exists()) { notificationSound = Uri.fromFile(file); } else { // res folder int soundId = appContext.getResources().getIdentifier(extrasRoot.getString("sound"), "raw", appContext.getPackageName()); if (soundId != 0) { notificationSound = Uri.parse("android.resource://" + appContext.getPackageName() + "/raw/" + soundId); } else { // res folder without file extension String soundFile = extrasRoot.getString("sound").split("\\.")[0]; soundId = appContext.getResources().getIdentifier(soundFile, "raw", appContext.getPackageName()); if (soundId != 0) { notificationSound = Uri.parse("android.resource://" + appContext.getPackageName() + "/raw/" + soundId); } } } } } } } } // VIBRATE if (extras.containsKey("vibrate") && extras.getString("vibrate").equalsIgnoreCase("true")) { notificationDefaults |= Notification.DEFAULT_VIBRATE; } // LIGHTS if (extras.containsKey("lights") && extras.getString("lights").equalsIgnoreCase("true")) { notificationDefaults |= Notification.DEFAULT_LIGHTS; } // NOTIFICATION ID if (extras.containsKey("notificationId")) { try { notificationId = Integer.parseInt(extras.getString("notificationId")); } catch (NumberFormatException nfe) { } } if (notificationId == 0) { notificationId = appContext.getAppProperties().getInt(PROPERTY_NOTIFICATION_ID, 0); notificationId++; appContext.getAppProperties().setInt(PROPERTY_NOTIFICATION_ID, notificationId); } // BADGE if (extras.containsKey("badge")) { try { badgeCount = Integer.parseInt(extras.getString("badge")); } catch (NumberFormatException nfe) { } } // LARGE ICON Bitmap largeIcon = null; if (extras.containsKey("largeIcon")) { largeIcon = getBitmap(extras.getString("largeIcon")); } else if (extras.containsKey("licon")) { largeIcon = getBitmap(extras.getString("licon")); } else if (extrasRoot.containsKey("largeIcon")) { largeIcon = getBitmap(extrasRoot.getString("largeIcon")); } else if (extrasRoot.containsKey("licon")) { largeIcon = getBitmap(extrasRoot.getString("licon")); } // SMALL ICON if (extras.containsKey("smallIcon")) { appIconId = appContext.getResources().getIdentifier(extras.getString("smallIcon"), "drawable", appContext.getPackageName()); if (appIconId == 0) { Log.i(TAG, "Unable to find resource identifier to custom smallIcon : " + extras.getString("smallIcon")); } } else if (extras.containsKey("sicon")) { appIconId = appContext.getResources().getIdentifier(extras.getString("sicon"), "drawable", appContext.getPackageName()); if (appIconId == 0) { Log.i(TAG, "Unable to find resource identifier to custom sicon : " + extras.getString("sicon")); } } else if (extrasRoot.containsKey("smallIcon")) { appIconId = appContext.getResources().getIdentifier(extrasRoot.getString("smallIcon"), "drawable", appContext.getPackageName()); if (appIconId == 0) { Log.i(TAG, "Unable to find resource identifier to custom smallIcon : " + extrasRoot.getString("smallIcon")); } } else if (extrasRoot.containsKey("sicon")) { appIconId = appContext.getResources().getIdentifier(extrasRoot.getString("sicon"), "drawable", appContext.getPackageName()); if (appIconId == 0) { Log.i(TAG, "Unable to find resource identifier to custom smallIcon : " + extrasRoot.getString("sicon")); } } if (notificationText != null) { // Intent launch = getLauncherIntent(extras); Intent launch = new Intent(appContext, PendingNotificationActivity.class); launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); if (extrasRoot != null && !extrasRoot.isEmpty()) { launch.putExtra(PROPERTY_EXTRAS, extrasRoot); } launch.setAction("dummy_unique_action_identifyer:" + notificationId); PendingIntent contentIntent = PendingIntent.getActivity(appContext, 0, launch, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(appContext); mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationText)); mBuilder.setContentText(notificationText); if (notificationTitle != null) { mBuilder.setContentTitle(notificationTitle); } if (notificationTicker != null) { mBuilder.setTicker(notificationTicker); } if (notificationDefaults != 0) { mBuilder.setDefaults(notificationDefaults); } if (notificationSound != null) { mBuilder.setSound(notificationSound); } if (badgeCount >= 0) { mBuilder.setNumber(badgeCount); } if (largeIcon != null) { mBuilder.setLargeIcon(largeIcon); } if (appIconId == 0) { appIconId = appContext.getResources().getIdentifier("appicon", "drawable", appContext.getPackageName()); } mBuilder.setSmallIcon(appIconId); mBuilder.setContentIntent(contentIntent); mBuilder.setAutoCancel(true); mBuilder.setWhen(System.currentTimeMillis()); // ledARGB, ledOnMS, ledOffMS boolean customLight = false; int argb = 0xFFFFFFFF; int onMs = 1000; int offMs = 2000; if (extras.containsKey("ledARGB")) { try { argb = TiColorHelper.parseColor(extras.getString("ledARGB")); customLight = true; } catch (Exception ex) { try { argb = Integer.parseInt(extras.getString("ledARGB")); customLight = true; } catch (NumberFormatException nfe) { } } } else if (extras.containsKey("ledc")) { try { argb = TiColorHelper.parseColor(extras.getString("ledc")); customLight = true; } catch (Exception ex) { try { argb = Integer.parseInt(extras.getString("ledc")); customLight = true; } catch (NumberFormatException nfe) { } } } else if (extrasRoot.containsKey("ledARGB")) { try { argb = TiColorHelper.parseColor(extrasRoot.getString("ledARGB")); customLight = true; } catch (Exception ex) { try { argb = Integer.parseInt(extrasRoot.getString("ledARGB")); customLight = true; } catch (NumberFormatException nfe) { } } } else if (extrasRoot.containsKey("ledc")) { try { argb = TiColorHelper.parseColor(extrasRoot.getString("ledc")); customLight = true; } catch (Exception ex) { try { argb = Integer.parseInt(extrasRoot.getString("ledc")); customLight = true; } catch (NumberFormatException nfe) { } } } if (extras.containsKey("ledOnMS")) { try { onMs = Integer.parseInt(extras.getString("ledOnMS")); customLight = true; } catch (NumberFormatException nfe) { } } if (extras.containsKey("ledOffMS")) { try { offMs = Integer.parseInt(extras.getString("ledOffMS")); customLight = true; } catch (NumberFormatException nfe) { } } if (customLight) { mBuilder.setLights(argb, onMs, offMs); } //Visibility if (extras.containsKey("visibility")) { try { mBuilder.setVisibility(Integer.parseInt(extras.getString("visibility"))); } catch (NumberFormatException nfe) { } } else if (extras.containsKey("vis")) { try { mBuilder.setVisibility(Integer.parseInt(extras.getString("vis"))); } catch (NumberFormatException nfe) { } } else if (extrasRoot.containsKey("visibility")) { try { mBuilder.setVisibility(Integer.parseInt(extrasRoot.getString("visibility"))); } catch (NumberFormatException nfe) { } } else if (extrasRoot.containsKey("vis")) { try { mBuilder.setVisibility(Integer.parseInt(extrasRoot.getString("vis"))); } catch (NumberFormatException nfe) { } } //Icon background color int accent_argb = 0xFFFFFFFF; if (extras.containsKey("accentARGB")) { try { accent_argb = TiColorHelper.parseColor(extras.getString("accentARGB")); mBuilder.setColor(accent_argb); } catch (Exception ex) { try { accent_argb = Integer.parseInt(extras.getString("accentARGB")); mBuilder.setColor(accent_argb); } catch (NumberFormatException nfe) { } } } else if (extras.containsKey("bgac")) { try { accent_argb = TiColorHelper.parseColor(extras.getString("bgac")); mBuilder.setColor(accent_argb); } catch (Exception ex) { try { accent_argb = Integer.parseInt(extras.getString("bgac")); mBuilder.setColor(accent_argb); } catch (NumberFormatException nfe) { } } } else if (extrasRoot.containsKey("accentARGB")) { try { accent_argb = TiColorHelper.parseColor(extrasRoot.getString("accentARGB")); mBuilder.setColor(accent_argb); } catch (Exception ex) { try { accent_argb = Integer.parseInt(extrasRoot.getString("accentARGB")); mBuilder.setColor(accent_argb); } catch (NumberFormatException nfe) { } } } else if (extrasRoot.containsKey("bgac")) { try { accent_argb = TiColorHelper.parseColor(extrasRoot.getString("bgac")); mBuilder.setColor(accent_argb); } catch (Exception ex) { try { accent_argb = Integer.parseInt(extrasRoot.getString("bgac")); mBuilder.setColor(accent_argb); } catch (NumberFormatException nfe) { } } } NotificationManager nm = (NotificationManager) appContext .getSystemService(Context.NOTIFICATION_SERVICE); nm.notify(notificationId, mBuilder.build()); } }
From source file:com.android.messaging.datamodel.BugleNotifications.java
private static void updateBuilderAudioVibrate(final NotificationState state, final NotificationCompat.Builder notifBuilder, final boolean silent, final Uri ringtoneUri, final String conversationId) { int defaults = Notification.DEFAULT_LIGHTS; if (!silent) { final BuglePrefs prefs = Factory.get().getApplicationPrefs(); final long latestNotificationTimestamp = prefs .getLong(BuglePrefsKeys.LATEST_NOTIFICATION_MESSAGE_TIMESTAMP, Long.MIN_VALUE); final long latestReceivedTimestamp = state.getLatestReceivedTimestamp(); prefs.putLong(BuglePrefsKeys.LATEST_NOTIFICATION_MESSAGE_TIMESTAMP, Math.max(latestNotificationTimestamp, latestReceivedTimestamp)); if (latestReceivedTimestamp > latestNotificationTimestamp) { synchronized (mLock) { // Find out the last time we dinged for this conversation Long lastTime = sLastMessageDingTime.get(conversationId); if (sTimeBetweenDingsMs == 0) { sTimeBetweenDingsMs = BugleGservices.get().getInt( BugleGservicesKeys.NOTIFICATION_TIME_BETWEEN_RINGS_SECONDS, BugleGservicesKeys.NOTIFICATION_TIME_BETWEEN_RINGS_SECONDS_DEFAULT) * 1000; }//from w w w .j ava 2 s . c o m if (lastTime == null || SystemClock.elapsedRealtime() - lastTime > sTimeBetweenDingsMs) { sLastMessageDingTime.put(conversationId, SystemClock.elapsedRealtime()); notifBuilder.setSound(ringtoneUri); if (shouldVibrate(state)) { defaults |= Notification.DEFAULT_VIBRATE; } } } } } notifBuilder.setDefaults(defaults); }
From source file:com.chen.mail.utils.NotificationUtils.java
/** * Validate the notifications notification. *///from w w w .ja va 2 s .co m private static void validateNotifications(Context context, final Folder folder, final Account account, boolean getAttention, boolean ignoreUnobtrusiveSetting, NotificationKey key) { NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 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", createNotificationString(notificationMap), notificationMap.size(), folder.name, getAttention); } else { LogUtils.i(LOG_TAG, "Validating Notification, mapSize: %d " + "getAttention: %b", notificationMap.size(), getAttention); } // 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); if (unseenCount == 0) { LogUtils.i(LOG_TAG, "validateNotifications - cancelling account %s / folder %s", LogUtils.sanitizeName(LOG_TAG, account.name), LogUtils.sanitizeName(LOG_TAG, folder.persistentId)); nm.cancel(notificationId); return; } // We now have all we need to create the notification and the pending intent PendingIntent clickIntent; NotificationCompat.Builder notification = new NotificationCompat.Builder(context); notification.setSmallIcon(R.drawable.stat_notify_email); notification.setTicker(account.name); 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.getEmailAddress(), folder, isInbox); if (isInbox) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.getEmailAddress()); 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; } // Amend the click intent with a hint that its source was a notification, // but remove the hint before it's used to generate notification action // intents. This prevents the following sequence: // 1. generate single notification // 2. user clicks reply, then completes Compose activity // 3. main activity launches, gets FROM_NOTIFICATION hint in intent notificationIntent.putExtra(Utils.EXTRA_FROM_NOTIFICATION, true); clickIntent = PendingIntent.getActivity(context, -1, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); notificationIntent.removeExtra(Utils.EXTRA_FROM_NOTIFICATION); configureLatestEventInfoFromConversation(context, account, folderPreferences, notification, cursor, clickIntent, notificationIntent, unreadCount, unseenCount, folder, when); 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. notification.setOnlyAlertOnce(true); } LogUtils.i(LOG_TAG, "Account: %s vibrate: %s", LogUtils.sanitizeName(LOG_TAG, account.name), Boolean.toString(folderPreferences.isNotificationVibrateEnabled())); int defaults = 0; /* * We do not want to notify if this is coming back from an Undo notification, hence the * oldWhen check. */ if (getAttention && oldWhen == 0) { final AccountPreferences accountPreferences = new AccountPreferences(context, account.name); 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.name), 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); } nm.notify(notificationId, notification.build()); } else { LogUtils.i(LOG_TAG, "event info not configured - not notifying"); } } finally { if (cursor != null) { cursor.close(); } } }
From source file:com.tct.email.NotificationController.java
/** * Show (or update) a send failed notification. If tapped, the user is taken to the OUTBOX view * where he can view the list of failed mails. if tap retry,mail will retry to send. *///from w ww. j a v a2s . c o m public void showMailSendFaildNotification(long accountId, int number) { Account account = Account.restoreAccountWithId(mContext, accountId); if (account == null) { LogUtils.e(LOG_TAG, "Null account during notification SEND_FAILED "); return; } NotificationCompat.Builder notification = new NotificationCompat.Builder(mContext); ContentResolver conentResolver = mContext.getContentResolver(); Folder UIFolder = queryUIFolder(conentResolver, accountId); Folder UIInboxFolder = queryUIInboxFolder(conentResolver, accountId); com.tct.mail.providers.Account UIAccount = queryUIaccount(conentResolver, accountId); if (UIFolder == null || UIAccount == null || UIInboxFolder == null) { LogUtils.e(LOG_TAG, "Null UIFolder or null UIAccount during showMailSendFaildNotification,do nothing,just return "); return; } //get account address String accountAddress = account.getEmailAddress(); //get account senderName,if null,use address instand String senderName = account.getSenderName(); //get the notification's title(2 emails not send or Email not send) String title = createTitle(number); //get the warning icon Bitmap icon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_warning_grey); //get the conversation final Uri.Builder uriBuilder = UIFolder.conversationListUri.buildUpon(); Cursor conversationsCursor = mContext.getContentResolver().query(uriBuilder.build(), UIProvider.CONVERSATION_PROJECTION, null, null, null); //The Martro style only supported after android L. //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060 MOD_S if (com.tct.mail.utils.Utils.isRunningLOrLater()) { notification.setColor(mContext.getResources().getColor(R.color.notification_icon_mail_orange)); //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060 MOD_E NotificationCompat.InboxStyle digest = new NotificationCompat.InboxStyle(notification); // query current account's outbox mails.and get the subject. // Subject1; // Subject2; // Subject3; if (conversationsCursor != null) { try { while (conversationsCursor.moveToNext()) { final Conversation conversation = new Conversation(conversationsCursor); String sub = createSubject(conversation); digest.addLine(sub); } } catch (Exception e) { LogUtils.e(LOG_TAG, "exception happen during get notification subject", e.getMessage()); } finally { if (conversationsCursor != null) { conversationsCursor.close(); } } } //only 1 mails failed, show the subject and its senderName and emailAddress. //Line1: show the mail's subject ,same with METHOD: notification.setContentText //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873 MOD_S if (number > 0) { if (TextUtils.isEmpty(senderName)) { //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060 DEL // digest.addLine(accountAddress); } else { digest.addLine(senderName); // Line2: show the senderName,same with METHOD:Notification#setSubText() } digest.setSummaryText(accountAddress); } //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873 MOD_E notification.setContentTitle(title); notification.setTicker(accountAddress); notification.setLargeIcon(icon); notification.setSmallIcon(R.drawable.ic_notification_mail_24dp); //set the content click/tap intent //it will trigger going to OUBOX Intent toOutboxAction = Utils.createViewFolderIntent(mContext, UIFolder.folderUri.fullUri, UIAccount); PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, toOutboxAction, PendingIntent.FLAG_UPDATE_CURRENT); notification.setContentIntent(contentIntent); //set the action click intent. //it will trigger the refresh. PendingIntent actionIntent = createRefreshIntent(UIFolder, true, account.mId); notification.addAction(R.drawable.ic_refresh_grey_24dp, mContext.getResources().getString(R.string.retry), actionIntent); //set the failed mails. //TS:kaifeng.lu 2016-01-04 EMAIL BUGFIX_1272060 DEL // notification.setNumber(number); //set the light and sound FolderPreferences folderPreferences = new FolderPreferences(mContext, UIAccount.getAccountId(), UIInboxFolder, true); boolean vibrate = folderPreferences.isNotificationVibrateEnabled(); //not give sound for retry notification //String ringtoneUri = folderPreferences.getNotificationRingtoneUri(); int defaults = 0; if (vibrate) { defaults |= Notification.DEFAULT_VIBRATE; } // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_S //defaults |= Notification.FLAG_SHOW_LIGHTS; defaults |= Notification.DEFAULT_LIGHTS; notification.setDefaults(defaults); notification.setLights(0xff00ff00, 280, 2080); // TS: zheng.zou 2015-09-10 EMAIL BUGFIX-557052 MOD_E // notification.setSound(TextUtils.isEmpty(ringtoneUri) ? null // : Uri.parse(ringtoneUri)); // LogUtils.i(LOG_TAG, "failed email in %s vibrateWhen: %s, playing notification: %s", // LogUtils.sanitizeName(LOG_TAG, account.getEmailAddress()), vibrate); // TS: chao.zhang 2015-09-24 EMAIL FEATURE-585337 MOD_S //NOTE: UE:the notification only can be cancel by click. notification.setOngoing(true); } Notification warnningNotification = notification.build(); warnningNotification.flags |= Notification.FLAG_AUTO_CANCEL; //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873 MOD_S mNotificationManager.notify(getSendFailedNotificationId(accountId), warnningNotification); //TS:kaifeng.lu 2015-11-20 EMAIL BUGFIX_709873 MOD_E // TS: chao.zhang 2015-09-24 EMAIL FEATURE-585337 MOD_S }
From source file:com.android.mail.utils.NotificationUtils.java
/** * Validate the notifications notification. *//*from w w w . j a v a 2 s.c o m*/ 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(); } } }