下面列出了android.app.Notification#Builder ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Notification getServiceNotification(Context context) {
Notification.Builder builder = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(context, mChannelServiceId);
} else {
builder = new Notification.Builder(context);
}
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, new Intent(context, HomeActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(StringUtils.getTextFromResId(R.string.service_notify_title))
.setContentText(StringUtils.getTextFromResId(R.string.service_notify_content))
.setContentIntent(pendingIntent)
.build();
notification.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONGOING_EVENT;
return notification;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Notification.Builder builder = new Notification.Builder(SendRepostService.this)
.setTicker(getString(R.string.sending_repost))
.setContentTitle(getString(R.string.sending_repost)).setContentText(content).setOnlyAlertOnce(true)
.setOngoing(true)
.setSmallIcon(R.drawable.upload_white);
builder.setProgress(0, 100, true);
int notificationId = new Random().nextInt(Integer.MAX_VALUE);
notification = builder.getNotification();
NotificationUtility.show(notification, notificationId);
tasksNotifications.put(WeiboSendTask.this, notificationId);
}
/**
* Displays a notification with the location results.
*/
void showNotification() {
Intent notificationIntent = new Intent(mContext, MainActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = new Notification.Builder(mContext)
.setContentTitle(getLocationResultTitle())
.setContentText(getLocationResultText())
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentIntent(notificationPendingIntent);
getNotificationManager().notify(0, notificationBuilder.build());
}
private void notify(String methodName) {
String name = this.getClass().getName();
String[] strings = name.split("\\.");
Notification.Builder notificationBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
notificationBuilder = new Notification.Builder(this, TRACER);
} else {
//noinspection deprecation
notificationBuilder = new Notification.Builder(this);
}
Notification notification = notificationBuilder
.setContentTitle(methodName + " " + strings[strings.length - 1])
.setAutoCancel(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(name).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify((int) System.currentTimeMillis(), notification);
}
private Notification.Builder getNotification(String title, String text) {
// Intent intent = ClockActivity.newIntent(getApplicationContext());
Intent intent = new Intent(getBaseContext(),ClockActivity.class);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.clock)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(text)
.setContentIntent(pi);
// 兼容 API 26,Android 8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
// 第三个参数表示通知的重要程度,默认则只在通知栏闪烁一下
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, NotificationManager.IMPORTANCE_LOW);
// 注册通道,注册后除非卸载再安装否则不改变
notificationManager.createNotificationChannel(notificationChannel);
notificationChannel.setSound(null,null);
builder.setChannelId(CHANNEL_ONE_ID);
}
return builder;
}
private void startServiceInternal() {
setNotifyChannel();
Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
// 设置PendingIntent
Intent nfIntent = new Intent(this, MainActivity.class);
builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, FLAG_UPDATE_CURRENT))
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
.setContentTitle("G4Proxy") // 设置下拉列表里的标题
.setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
.setContentText("代理服务agent") // 设置上下文内容
.setWhen(System.currentTimeMillis()); // 设置该通知发生的时间
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(BuildConfig.APPLICATION_ID);
}
Notification notification = builder.build(); // 获取构建好的Notification
notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
startForeground(110, notification);// 开始前台服务
String clientKey = Settings.System.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
//新的代理服务器实现
LogbackConfig.config();
G4ProxyClient g4ProxyClient = new G4ProxyClient("www.scumall.com", 50000, clientKey);
g4ProxyClient.startup();
}
static Notification add(Context context, Notification n,
CharSequence contentTitle, CharSequence contentText, CharSequence contentInfo,
RemoteViews tickerView, int number,
PendingIntent contentIntent, PendingIntent fullScreenIntent, Bitmap largeIcon,
int mProgressMax, int mProgress, boolean mProgressIndeterminate) {
Notification.Builder b = new Notification.Builder(context)
.setWhen(n.when)
.setSmallIcon(n.icon, n.iconLevel)
.setContent(n.contentView)
.setTicker(n.tickerText, tickerView)
.setSound(n.sound, n.audioStreamType)
.setVibrate(n.vibrate)
.setLights(n.ledARGB, n.ledOnMS, n.ledOffMS)
.setOngoing((n.flags & Notification.FLAG_ONGOING_EVENT) != 0)
.setOnlyAlertOnce((n.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0)
.setAutoCancel((n.flags & Notification.FLAG_AUTO_CANCEL) != 0)
.setDefaults(n.defaults)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setContentInfo(contentInfo)
.setContentIntent(contentIntent)
.setDeleteIntent(n.deleteIntent)
.setFullScreenIntent(fullScreenIntent,
(n.flags & Notification.FLAG_HIGH_PRIORITY) != 0)
.setLargeIcon(largeIcon)
.setNumber(number)
.setProgress(mProgressMax, mProgress, mProgressIndeterminate);
return b.getNotification();
}
/**
* Build a notification.
*
* @param text the text of the notification
* @param pendingIntent the body, pending intent for the notification
* @param extras extras passed with the notification
* @return the builder
*/
@TargetApi(Build.VERSION_CODES.O)
private Notification buildNotification(String text, PendingIntent pendingIntent, Bundle extras,
final CallInvite callInvite,
int notificationId,
String channelId) {
Intent rejectIntent = new Intent(getApplicationContext(), IncomingCallNotificationService.class);
rejectIntent.setAction(Constants.ACTION_REJECT);
rejectIntent.putExtra(Constants.INCOMING_CALL_INVITE, callInvite);
rejectIntent.putExtra(Constants.INCOMING_CALL_NOTIFICATION_ID, notificationId);
PendingIntent piRejectIntent = PendingIntent.getService(getApplicationContext(), 0, rejectIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent acceptIntent = new Intent(getApplicationContext(), IncomingCallNotificationService.class);
acceptIntent.setAction(Constants.ACTION_ACCEPT);
acceptIntent.putExtra(Constants.INCOMING_CALL_INVITE, callInvite);
acceptIntent.putExtra(Constants.INCOMING_CALL_NOTIFICATION_ID, notificationId);
PendingIntent piAcceptIntent = PendingIntent.getService(getApplicationContext(), 0, acceptIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder =
new Notification.Builder(getApplicationContext(), channelId)
.setSmallIcon(R.drawable.ic_call_end_white_24dp)
.setContentTitle(getString(R.string.app_name))
.setContentText(text)
.setCategory(Notification.CATEGORY_CALL)
.setFullScreenIntent(pendingIntent, true)
.setExtras(extras)
.setAutoCancel(true)
.addAction(android.R.drawable.ic_menu_delete, getString(R.string.decline), piRejectIntent)
.addAction(android.R.drawable.ic_menu_call, getString(R.string.answer), piAcceptIntent)
.setFullScreenIntent(pendingIntent, true);
return builder.build();
}
private void createNotification() {
Log.i(TAG, "Create running notification");
// Create open and pause action intents
Intent openIntent = new Intent(this, MainActivity.class);
Intent pauseIntent = new Intent(this, ActionReceiver.class);
pauseIntent.setAction(Constants.ACTION_UPDATE_STATUS);
pauseIntent.putExtra(Constants.Extra.ACTION, Constants.Action.PAUSE);
pauseIntent.putExtra(Constants.Extra.BRIGHTNESS, mBrightness);
Notification.Action pauseAction = new Notification.Action(
R.drawable.ic_wb_incandescent_black_24dp,
getString(R.string.notification_action_turn_off),
PendingIntent.getBroadcast(getBaseContext(), 0, pauseIntent, Intent.FILL_IN_DATA)
);
// Create notification
Notification.Builder builder = new Notification.Builder(getApplicationContext())
.setContentTitle(getString(R.string.notification_running_title))
.setContentText(getString(R.string.notification_running_msg))
.setSmallIcon(R.drawable.ic_brightness_2_white_36dp)
.addAction(pauseAction)
.setContentIntent(PendingIntent.getActivity(getApplicationContext(),
0, openIntent, PendingIntent.FLAG_UPDATE_CURRENT))
.setAutoCancel(false)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setShowWhen(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId(Constants.NOTIFICATION_CHANNEL_ID_RS);
}
mNotification = builder.build();
}
Notification AppUpdateNotification(PendingIntent intent, String version, String filesize) {
Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
mBuilder.setContentText(String.format(mXmppConnectionService.getString(R.string.update_available), version, filesize));
mBuilder.setSmallIcon(R.drawable.ic_update_notification);
mBuilder.setContentIntent(intent);
mBuilder.setOngoing(true);
if (Compatibility.runsTwentySix()) {
mBuilder.setChannelId(UPDATE_CHANNEL_ID);
}
return mBuilder.build();
}
@TargetApi(Build.VERSION_CODES.N)
private static void updateSummaryNotification(Context context, String packageName, String groupId) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
StatusBarNotification[] activeNotifications = manager.getActiveNotifications();
int notificationCntInGroup = 0;
for (StatusBarNotification statusBarNotification : activeNotifications) {
if (groupId.equals(statusBarNotification.getNotification().getGroup())) {
notificationCntInGroup++;
}
}
if (notificationCntInGroup > 1) {
CharSequence appName = ApplicationNameCache.getInstance().getAppName(context, packageName);
Bundle extras = new Bundle();
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(context, getChannelIdByPkg(packageName));
builder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN);
} else {
builder = new Notification.Builder(context);
}
int color = getIconColor(context, packageName);
if (color != Notification.COLOR_DEFAULT) {
CharSequence subText = ColorUtil.createColorSubtext(appName, color);
if (subText != null) {
extras.putCharSequence(NotificationCompat.EXTRA_SUB_TEXT, subText);
}
builder.setColor(color);
} else {
extras.putCharSequence(NotificationCompat.EXTRA_SUB_TEXT, appName);
}
builder.setExtras(extras);
// Set small icon
NotificationController.processSmallIcon(context, packageName, builder);
builder.setCategory(Notification.CATEGORY_EVENT)
.setGroupSummary(true)
.setGroup(groupId);
Notification notification = builder.build();
manager.notify(packageName.hashCode(), notification);
} else {
manager.cancel(packageName.hashCode());
}
}
private void buildNotification(String uid) {
ValueWrapper valueWrapper = valueBagHashMap.get(uid);
if (valueWrapper == null) {
return;
}
final AccountBean accountBean = valueWrapper.accountBean;
final UnreadBean unreadBean = valueWrapper.unreadBean;
Intent clickToOpenAppPendingIntentInner = valueWrapper.clickToOpenAppPendingIntentInner;
String ticker = valueWrapper.ticker;
final RecordOperationAppBroadcastReceiver clearNotificationEventReceiver = valueWrapper.clearNotificationEventReceiver;
Notification.Builder builder = new Notification.Builder(getBaseContext()).setTicker(ticker)
.setContentText(accountBean.getUsernick())
.setSmallIcon(R.drawable.ic_notification).setAutoCancel(true)
.setContentIntent(getPendingIntent(clickToOpenAppPendingIntentInner))
.setOnlyAlertOnce(true);
builder.setContentTitle(ticker);
Utility.unregisterReceiverIgnoredReceiverNotRegisteredException(BeeboApplication.getInstance(),
clearNotificationEventReceiver);
valueWrapper.clearNotificationEventReceiver = new RecordOperationAppBroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
new Thread(new Runnable() {
@Override
public void run() {
try {
new ClearUnreadDao(accountBean.getAccess_token()).clearMentionStatusUnread(unreadBean,
accountBean.getUid());
new ClearUnreadDao(accountBean.getAccess_token()).clearMentionCommentUnread(unreadBean,
accountBean.getUid());
new ClearUnreadDao(accountBean.getAccess_token()).clearCommentUnread(unreadBean,
accountBean.getUid());
} catch (WeiboException ignored) {
} finally {
Utility.unregisterReceiverIgnoredReceiverNotRegisteredException(BeeboApplication.getInstance(),
clearNotificationEventReceiver);
if (Utility.isDebugMode()) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "iBeebo的通知被移除",
Toast.LENGTH_SHORT).show();
}
});
}
}
}
}).start();
}
};
IntentFilter intentFilter = new IntentFilter(RESET_UNREAD_MENTIONS_WEIBO_ACTION);
BeeboApplication.getInstance().registerReceiver(valueWrapper.clearNotificationEventReceiver, intentFilter);
Intent broadcastIntent = new Intent(RESET_UNREAD_MENTIONS_WEIBO_ACTION);
PendingIntent deletedPendingIntent = PendingIntent.getBroadcast(BeeboApplication.getInstance(), accountBean.getUid()
.hashCode(), broadcastIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setDeleteIntent(deletedPendingIntent);
Utility.configVibrateLedRingTone(builder);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(
NOTIFICATION_SERVICE);
notificationManager.notify(getMentionsWeiboNotificationId(accountBean), builder.build());
}
/**
* Shows the notification that informs the user a dictionary is available.
*
* When this notification is clicked, the dialog for downloading the dictionary
* over a metered connection is shown.
*/
private static void showDictionaryAvailableNotification(final Context context,
final String clientId, final ContentValues installCandidate) {
final String localeString = installCandidate.getAsString(MetadataDbHelper.LOCALE_COLUMN);
final Intent intent = new Intent();
intent.setClass(context, DownloadOverMeteredDialog.class);
intent.putExtra(DownloadOverMeteredDialog.CLIENT_ID_KEY, clientId);
intent.putExtra(DownloadOverMeteredDialog.WORDLIST_TO_DOWNLOAD_KEY,
installCandidate.getAsString(MetadataDbHelper.WORDLISTID_COLUMN));
intent.putExtra(DownloadOverMeteredDialog.SIZE_KEY,
installCandidate.getAsInteger(MetadataDbHelper.FILESIZE_COLUMN));
intent.putExtra(DownloadOverMeteredDialog.LOCALE_KEY, localeString);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
final PendingIntent notificationIntent = PendingIntent.getActivity(context,
0 /* requestCode */, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
final NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// None of those are expected to happen, but just in case...
if (null == notificationIntent || null == notificationManager) return;
final String language = (null == localeString) ? ""
: LocaleUtils.constructLocaleFromString(localeString).getDisplayLanguage();
final String titleFormat = context.getString(R.string.dict_available_notification_title);
final String notificationTitle = String.format(titleFormat, language);
final Notification.Builder builder = new Notification.Builder(context)
.setAutoCancel(true)
.setContentIntent(notificationIntent)
.setContentTitle(notificationTitle)
.setContentText(context.getString(R.string.dict_available_notification_description))
.setTicker(notificationTitle)
.setOngoing(false)
.setOnlyAlertOnce(true)
.setSmallIcon(R.drawable.ic_notify_dictionary);
NotificationCompatUtils.setColor(builder,
context.getResources().getColor(R.color.notification_accent_color));
NotificationCompatUtils.setPriorityToLow(builder);
NotificationCompatUtils.setVisibilityToSecret(builder);
NotificationCompatUtils.setCategoryToRecommendation(builder);
final Notification notification = NotificationCompatUtils.build(builder);
notificationManager.notify(DICT_AVAILABLE_NOTIFICATION_ID, notification);
}
private void showFailedNotification(final WeiboSendTask task) {
Notification.Builder builder = new Notification.Builder(SendRepostService.this)
.setTicker(getString(R.string.send_failed))
.setContentTitle(getString(R.string.send_faile_click_to_open)).setContentText(content)
.setOnlyAlertOnce(true).setAutoCancel(true)
.setSmallIcon(R.drawable.send_failed).setOngoing(false);
Intent notifyIntent = WriteRepostActivity.startBecauseSendFailed(SendRepostService.this, account, content,
oriMsg, repostDraftBean, e.getError());
PendingIntent pendingIntent = PendingIntent.getActivity(SendRepostService.this, 0, notifyIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notification;
if (Utility.isJB()) {
Notification.BigTextStyle bigTextStyle = new Notification.BigTextStyle(builder);
bigTextStyle.setBigContentTitle(getString(R.string.send_faile_click_to_open));
bigTextStyle.bigText(content);
bigTextStyle.setSummaryText(account.getUsernick());
builder.setStyle(bigTextStyle);
Intent intent = new Intent(SendRepostService.this, SendRepostService.class);
intent.putExtra("oriMsg", oriMsg);
intent.putExtra("content", content);
intent.putExtra("is_comment", is_comment);
intent.putExtra(Constants.TOKEN, token);
intent.putExtra(Constants.ACCOUNT, account);
intent.putExtra("lastNotificationId", tasksNotifications.get(task));
PendingIntent retrySendIntent = PendingIntent.getService(SendRepostService.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.send_light, getString(R.string.retry_send), retrySendIntent);
notification = builder.build();
} else {
notification = builder.getNotification();
}
final int id = tasksNotifications.get(task);
NotificationUtility.show(notification, id);
handler.postDelayed(new Runnable() {
@Override
public void run() {
stopServiceIfTasksAreEnd(task);
}
}, 3000);
}
public void showNotification(JSONObject dataToReturnOnClick, JSONObject notificationOptions){
Options options = new Options(notificationOptions, this.context.getApplicationContext());
this.createNotificationChannel(options);
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(this.context, options.getChannelId());
} else {
builder = new Notification.Builder(this.context);
}
builder.setDefaults(0)
.setContentTitle(options.getTitle()).setSmallIcon(options.getSmallIconResourceId())
.setLargeIcon(options.getLargeIconBitmap()).setAutoCancel(options.doesAutoCancel());
if(options.getBigPictureBitmap() != null)
builder.setStyle(new BigPictureStyle().bigPicture(options.getBigPictureBitmap()));
if(options.doesVibrate() && options.getVibratePattern() != null)
builder.setVibrate(options.getVibratePattern());
else if (Build.VERSION.SDK_INT >= 21 && options.doesHeadsUp())
builder.setVibrate(new long[0]);
if(options.doesHeadsUp()) {
builder.setPriority(Notification.PRIORITY_HIGH);
}
if(options.doesSound() && options.getSoundUri() != null)
builder.setSound(options.getSoundUri(), android.media.AudioManager.STREAM_NOTIFICATION);
if (options.doesColor() && Build.VERSION.SDK_INT >= 22)
builder.setColor(options.getColor());
this.setContentTextAndMultiline(builder, options);
this.setOnClick(builder, dataToReturnOnClick);
Notification notification;
if (Build.VERSION.SDK_INT < 16) {
notification = builder.getNotification(); // Notification for HoneyComb to ICS
} else {
notification = builder.build(); // Notification for Jellybean and above
}
if(options.doesAutoCancel())
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if(options.doesVibrate() && options.getVibratePattern() == null)
notification.defaults |= Notification.DEFAULT_VIBRATE;
if(options.doesSound() && options.getSoundUri() == null)
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager notificationManager
= (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(options.getId(), notification);
if(options.doesOpenApp())
openApp();
}
Down_handler(Context context, Notification.Builder builder, NotificationManager notificationManager) {
mContextReference = new WeakReference<>(context);
this.builder = builder;
this.notificationManager = notificationManager;
}
void notify(Notification.Builder builder) {
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, builder.build());
}
/**
* Shows the notification that informs the user a dictionary is available.
*
* When this notification is clicked, the dialog for downloading the dictionary
* over a metered connection is shown.
*/
private static void showDictionaryAvailableNotification(final Context context,
final String clientId, final ContentValues installCandidate) {
final String localeString = installCandidate.getAsString(MetadataDbHelper.LOCALE_COLUMN);
final Intent intent = new Intent();
intent.setClass(context, DownloadOverMeteredDialog.class);
intent.putExtra(DownloadOverMeteredDialog.CLIENT_ID_KEY, clientId);
intent.putExtra(DownloadOverMeteredDialog.WORDLIST_TO_DOWNLOAD_KEY,
installCandidate.getAsString(MetadataDbHelper.WORDLISTID_COLUMN));
intent.putExtra(DownloadOverMeteredDialog.SIZE_KEY,
installCandidate.getAsInteger(MetadataDbHelper.FILESIZE_COLUMN));
intent.putExtra(DownloadOverMeteredDialog.LOCALE_KEY, localeString);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
final PendingIntent notificationIntent = PendingIntent.getActivity(context,
0 /* requestCode */, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
final NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// None of those are expected to happen, but just in case...
if (null == notificationIntent || null == notificationManager) return;
final String language = (null == localeString) ? ""
: LocaleUtils.constructLocaleFromString(localeString).getDisplayLanguage();
final String titleFormat = context.getString(R.string.dict_available_notification_title);
final String notificationTitle = String.format(titleFormat, language);
final Notification.Builder builder = new Notification.Builder(context)
.setAutoCancel(true)
.setContentIntent(notificationIntent)
.setContentTitle(notificationTitle)
.setContentText(context.getString(R.string.dict_available_notification_description))
.setTicker(notificationTitle)
.setOngoing(false)
.setOnlyAlertOnce(true)
.setSmallIcon(R.drawable.ic_notify_dictionary);
NotificationCompatUtils.setColor(builder,
context.getResources().getColor(R.color.notification_accent_color));
NotificationCompatUtils.setPriorityToLow(builder);
NotificationCompatUtils.setVisibilityToSecret(builder);
NotificationCompatUtils.setCategoryToRecommendation(builder);
final Notification notification = NotificationCompatUtils.build(builder);
notificationManager.notify(DICT_AVAILABLE_NOTIFICATION_ID, notification);
}
@TargetApi(26)
public static NotificationChannel getChan(Notification.Builder wip) {
final Notification temp = wip.build();
if (temp.getChannelId() == null) return null;
// create generic audio attributes
final AudioAttributes generic_audio = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.build();
// create notification channel for hashing purposes from the existing notification builder
NotificationChannel template = new NotificationChannel(
temp.getChannelId(),
getString(temp.getChannelId()),
NotificationManager.IMPORTANCE_DEFAULT);
// mirror the notification parameters in the channel
template.setGroup(temp.getChannelId());
template.setVibrationPattern(temp.vibrate);
template.setSound(temp.sound, generic_audio);
template.setLightColor(temp.ledARGB);
if ((temp.ledOnMS != 0) && (temp.ledOffMS != 0))
template.enableLights(true); // weird how this doesn't work like vibration pattern
template.setDescription(temp.getChannelId() + " " + wip.hashCode());
// get a nice string to identify the hash
final String mhash = my_text_hash(template);
// create another notification channel using the hash because id is immutable
final NotificationChannel channel = new NotificationChannel(
template.getId() + mhash,
getString(temp.getChannelId()) + mhash,
NotificationManager.IMPORTANCE_DEFAULT);
// mirror the settings from the previous channel
channel.setSound(template.getSound(), generic_audio);
if (addChannelGroup()) {
channel.setGroup(template.getGroup());
} else {
channel.setGroup(channel.getId());
}
channel.setDescription(template.getDescription());
channel.setVibrationPattern(template.getVibrationPattern());
template.setLightColor(temp.ledARGB);
if ((temp.ledOnMS != 0) && (temp.ledOffMS != 0))
template.enableLights(true); // weird how this doesn't work like vibration pattern
template.setDescription(temp.getChannelId() + " " + wip.hashCode());
// create a group to hold this channel if one doesn't exist or update text
getNotifManager().createNotificationChannelGroup(new NotificationChannelGroup(channel.getGroup(), getString(channel.getGroup())));
// create this channel if it doesn't exist or update text
getNotifManager().createNotificationChannel(channel);
return channel;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private Notification.Builder getChannelNotification(String title, String content, int icon) {
Notification.Builder builder = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
Notification.Builder notificationBuilder = builder
//设置标题
.setContentTitle(title)
//消息内容
.setContentText(content)
//设置通知的图标
.setSmallIcon(icon)
//让通知左右滑的时候是否可以取消通知
.setOngoing(ongoing)
//设置优先级
.setPriority(priority)
//是否提示一次.true - 如果Notification已经存在状态栏即使在调用notify函数也不会更新
.setOnlyAlertOnce(onlyAlertOnce)
.setAutoCancel(true);
if (remoteViews != null) {
//设置自定义view通知栏
notificationBuilder.setContent(remoteViews);
}
if (intent != null) {
notificationBuilder.setContentIntent(intent);
}
if (ticker != null && ticker.length() > 0) {
//设置状态栏的标题
notificationBuilder.setTicker(ticker);
}
if (when != 0) {
//设置通知时间,默认为系统发出通知的时间,通常不用设置
notificationBuilder.setWhen(when);
}
if (sound != null) {
//设置sound
notificationBuilder.setSound(sound);
}
if (defaults != 0) {
//设置默认的提示音
notificationBuilder.setDefaults(defaults);
}
if (pattern != null) {
//自定义震动效果
notificationBuilder.setVibrate(pattern);
}
return notificationBuilder;
}