下面列出了android.app.NotificationManager#IMPORTANCE_NONE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* {@hide}
*/
public static String importanceToString(int importance) {
switch (importance) {
case NotificationManager.IMPORTANCE_UNSPECIFIED:
return "UNSPECIFIED";
case NotificationManager.IMPORTANCE_NONE:
return "NONE";
case NotificationManager.IMPORTANCE_MIN:
return "MIN";
case NotificationManager.IMPORTANCE_LOW:
return "LOW";
case NotificationManager.IMPORTANCE_DEFAULT:
return "DEFAULT";
case NotificationManager.IMPORTANCE_HIGH:
case NotificationManager.IMPORTANCE_MAX:
return "HIGH";
default:
return "UNKNOWN(" + String.valueOf(importance) + ")";
}
}
@RequiresApi(Build.VERSION_CODES.O)
public static String createSilentNotificationChannel(String channelId, String channelName, Context context){
NotificationChannel chan = new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE);
chan.setDescription("Silent channel");
chan.setSound(null,null);
chan.enableLights(false);
chan.setLightColor(Color.BLUE);
chan.enableVibration(false);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (service != null) {
service.createNotificationChannel(chan);
}
return channelId;
}
private Notification createNotification() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel(TAG, TAG, NotificationManager.IMPORTANCE_NONE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
}
Intent intent = new Intent(this, IdenticonsSettings.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
return new NotificationCompat.Builder(this, TAG)
.setAutoCancel(false)
.setOngoing(true)
.setContentTitle(getString(R.string.identicons_remove_service_running_title))
.setContentText(getString(R.string.identicons_remove_service_running_summary))
.setSmallIcon(R.drawable.ic_settings_identicons)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.build();
}
private Notification createNotification() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
NotificationChannel chan = new NotificationChannel(TAG, TAG, NotificationManager.IMPORTANCE_NONE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
}
Intent intent = new Intent(this, IdenticonsSettings.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
return new NotificationCompat.Builder(this, TAG)
.setAutoCancel(false)
.setOngoing(true)
.setContentTitle(getString(R.string.identicons_creation_service_running_title))
.setContentText(getString(R.string.identicons_creation_service_running_summary))
.setSmallIcon(R.drawable.ic_settings_identicons)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.build();
}
@Override
public void onCreate() {
super.onCreate();
if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) || new AppPreferences(getApplicationContext()).getBoolean("useForegroundService", false)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder mBuilder = new Notification.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setContentText(getString(R.string.backgroundService));
NotificationChannel channel = new NotificationChannel("BackgroundService", getString(R.string.backgroundService), NotificationManager.IMPORTANCE_NONE);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null)
notificationManager.createNotificationChannel(channel);
mBuilder.setChannelId("BackgroundService");
Intent resultIntent = new Intent(getApplicationContext(), Main.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
startForeground(1, mBuilder.build());
} else {
startForeground(1, new Notification());
}
}
}
@TargetApi(26)
private boolean isChannelBlocked(@ChannelDefinitions.ChannelId String channelId) {
// Use non-compat notification manager as compat does not have getNotificationChannel (yet).
NotificationManager notificationManager =
ContextUtils.getApplicationContext().getSystemService(NotificationManager.class);
/*
The code in the try-block uses reflection in order to compile as it calls APIs newer than
our compileSdkVersion of Android. The equivalent code without reflection looks like this:
NotificationChannel channel = notificationManager.getNotificationChannel(channelId);
return (channel.getImportance() == NotificationManager.IMPORTANCE_NONE);
*/
// TODO(crbug.com/707804) Remove the following reflection once compileSdk is bumped to O.
try {
Method getNotificationChannel = notificationManager.getClass().getMethod(
"getNotificationChannel", String.class);
Object channel = getNotificationChannel.invoke(notificationManager, channelId);
Method getImportance = channel.getClass().getMethod("getImportance");
int importance = (int) getImportance.invoke(channel);
return (importance == NotificationManager.IMPORTANCE_NONE);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
Log.e(TAG, "Error checking channel importance:", e);
}
return false;
}
@RequiresApi(api = Build.VERSION_CODES.O)
private static Notification buildForegroundNotification(Context context) {
NotificationChannel channel = new NotificationChannel("foreground-service", "Foreground Service", NotificationManager.IMPORTANCE_NONE);
channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);
channel.setShowBadge(false);
channel.setVibrationPattern(new long[0]);
context.getSystemService(NotificationManager.class).createNotificationChannel(channel);
return new Notification.Builder(context, channel.getId())
.setOngoing(true)
.setContentTitle("Running in background")
.setSmallIcon(R.drawable.gcm_bell)
.build();
}
private String buildChannel() {
String channelId = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = getString(R.string.adamant_default_notification_channel);
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel chan = new NotificationChannel(ADAMANT_DEFAULT_NOTIFICATION_CHANNEL_ID,
channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.RED);
chan.enableLights(true);
chan.enableVibration(true);
chan.setVibrationPattern(NotificationHelper.VIBRATE_PATTERN);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
chan.setSound(NotificationHelper.SOUND_URI, attributes);
NotificationManager service = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (service != null) {
service.createNotificationChannel(chan);
channelId = ADAMANT_DEFAULT_NOTIFICATION_CHANNEL_ID;
}
}
return channelId;
}
public static Notification.Builder getNotificationBuilder(final Context context) {
NotificationManager manager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel =
new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_ID,
NotificationManager.IMPORTANCE_NONE);
channel.setImportance(NotificationManager.IMPORTANCE_MIN); // ignored by Android O ...
channel.enableLights(false);
channel.enableVibration(false);
channel.setBypassDnd(false);
channel.setSound(null, null);
manager.createNotificationChannel(channel);
Notification.Builder builder = new Notification.Builder(context, NOTIFICATION_CHANNEL_ID);
return builder;
}
/**
* Displays a notification.
* @param platformTag The notification tag, see
* {@link NotificationManager#notify(String, int, Notification)}.
* @param platformId The notification id, see
* {@link NotificationManager#notify(String, int, Notification)}.
* @param notification The notification to be displayed, constructed by the provider.
* @param channelName The name of the notification channel that the notification should be
* displayed on. This method gets or creates a channel from the name and
* modifies the notification to use that channel.
* @return Whether the notification was successfully displayed (the channel/app may be blocked
* by the user).
*/
protected boolean notifyNotificationWithChannel(String platformTag, int platformId,
Notification notification, String channelName) {
ensureOnCreateCalled();
if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) return false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = channelNameToId(channelName);
// Create the notification channel, (no-op if already created).
mNotificationManager.createNotificationChannel(new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_DEFAULT));
// Check that the channel is enabled.
if (mNotificationManager.getNotificationChannel(channelId).getImportance() ==
NotificationManager.IMPORTANCE_NONE) {
return false;
}
// Set our notification to have that channel.
Notification.Builder builder = Notification.Builder.recoverBuilder(this, notification);
builder.setChannelId(channelId);
notification = builder.build();
}
mNotificationManager.notify(platformTag, platformId, notification);
return true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= 26) {
Notification.Builder mBuilder = new Notification.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setContentText(getString(R.string.oneKeyFreeze));
NotificationChannel channel = new NotificationChannel("OneKeyFreeze", getString(R.string.oneKeyFreeze), NotificationManager.IMPORTANCE_NONE);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null)
notificationManager.createNotificationChannel(channel);
mBuilder.setChannelId("OneKeyFreeze");
startForeground(2, mBuilder.build());
} else {
startForeground(2, new Notification());
}
boolean auto = intent.getBooleanExtra("autoCheckAndLockScreen", true);
String pkgNames = new AppPreferences(getApplicationContext()).getString(getString(R.string.sAutoFreezeApplicationList), "");
if (pkgNames != null) {
if (Build.VERSION.SDK_INT >= 21 && isDeviceOwner(getApplicationContext())) {
oneKeyActionMRoot(this, true, pkgNames.split(","));
checkAuto(auto, this);
} else {
oneKeyActionRoot(this, true, pkgNames.split(","));
checkAuto(auto, this);
}
}
return super.onStartCommand(intent, flags, startId);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private String createNotificationChannel(String channelId, String channelName){
NotificationChannel chan = new NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager service = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
service.createNotificationChannel(chan);
return channelId;
}
@SuppressLint("InlinedApi")
public NotificationFactory(
@NonNull final String channelId, @Nullable final String channelTitle,
@DrawableRes final int smallIconId, @DrawableRes final int largeIconId) {
this(channelId, channelId,
BuildCheck.isAndroid7() ? NotificationManager.IMPORTANCE_NONE : 0,
null, null, smallIconId, largeIconId);
}
/**
* Notification生成用のファクトリーメソッド
* @return
*/
@SuppressLint("InlinedApi")
public Notification build() {
if (mChannelBuilder.getImportance() == NotificationManager.IMPORTANCE_NONE) {
// importanceが設定されていないときでmPriorityがセットされていればそれに従う
switch (mPriority) {
case NotificationCompat.PRIORITY_MIN:
mChannelBuilder.setImportance(NotificationManager.IMPORTANCE_MIN);
break;
case NotificationCompat.PRIORITY_LOW:
mChannelBuilder.setImportance(NotificationManager.IMPORTANCE_LOW);
break;
case NotificationCompat.PRIORITY_DEFAULT:
mChannelBuilder.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
break;
case NotificationCompat.PRIORITY_HIGH:
mChannelBuilder.setImportance(NotificationManager.IMPORTANCE_HIGH);
break;
case NotificationCompat.PRIORITY_MAX:
mChannelBuilder.setImportance(NotificationManager.IMPORTANCE_HIGH);
break;
default:
// ChannelBuilder側の設定に従う==IMPORTANCE_DEFAULT
break;
}
}
mChannelBuilder.build();
super.setContentIntent(createContentIntent());
super.setDeleteIntent(createDeleteIntent());
super.setFullScreenIntent(createFullScreenIntent(), isHighPriorityFullScreenIntent());
return super.build();
}
/**
* 既存のNotificationChannelが存在すればその設定をコピーしてChannelBuilderを生成する。
* 既存のNotificationChannelがなければ新規生成する。
* @param context
* @param channelId 通知チャネルid
* @return
*/
@NonNull
public static ChannelBuilder getBuilder(@NonNull final Context context,
@NonNull final String channelId) {
if (DEBUG) Log.v(TAG, "getBuilder:" + channelId);
final NotificationManager manager
= ContextUtils.requireSystemService(context, NotificationManager.class);
final NotificationChannel channel = manager.getNotificationChannel(channelId);
if (channel != null) {
// 既にNotificationChannelが存在する場合はその設定を取得して生成
final ChannelBuilder builder = new ChannelBuilder(context,
channelId, channel.getName(), channel.getImportance());
builder.setLockscreenVisibility(channel.getLockscreenVisibility())
.setBypassDnd(channel.canBypassDnd())
.setShowBadge(channel.canShowBadge())
.setDescription(channel.getDescription())
.setLightColor(channel.getLightColor())
.setVibrationPattern(channel.getVibrationPattern())
.enableLights(channel.shouldShowLights())
.enableVibration(channel.shouldVibrate())
.setSound(channel.getSound(), channel.getAudioAttributes())
.setGroup(channel.getGroup(), null)
.setCreateIfExists(true);
return builder;
} else {
// 存在しない場合は新規に生成
return new ChannelBuilder(context,
channelId, null, NotificationManager.IMPORTANCE_NONE);
}
}
/**
* コンストラクタ
* チャネルidはDEFAULT_CHANNEL_IDになる
* 新規に作成するとわかっている場合・上書きする場合を除いて#getBuilderを使うほうがいい。
*/
public ChannelBuilder(@NonNull final Context context) {
this(context,
DEFAULT_CHANNEL_ID,
DEFAULT_CHANNEL_ID,
NotificationManager.IMPORTANCE_NONE,
null, null);
}
NotificationChannelData(Map<String, Object> channel) {
id = (String) channel.get("id");
name = (String) channel.get("name");
description = (String) channel.get("description");
groupId = (String) channel.get("groupId");
importance = (int) CollectionUtil.getOrDefault(channel, "importance",
importance);
enableLights = (boolean) CollectionUtil.getOrDefault(channel, "enable_lights",
enableLights);
lightColor = (int) CollectionUtil.getOrDefault(channel, "light_color", lightColor);
enableVibration = (boolean) CollectionUtil.getOrDefault(channel, "enable_vibration",
enableVibration);
lockscreenVisibility = (int) CollectionUtil.getOrDefault(channel, "lockscreen_visibility",
lockscreenVisibility);
bypassDnd = (boolean) CollectionUtil.getOrDefault(channel, "bypass_dnd", bypassDnd);
showBadge = (boolean) CollectionUtil.getOrDefault(channel, "show_badge", showBadge);
try {
List<Number> pattern = CollectionUtil.uncheckedCast(
CollectionUtil.getOrDefault(channel, "vibration_pattern", null));
if (pattern != null) {
vibrationPattern = new long[pattern.size()];
Iterator<Number> iterator = pattern.iterator();
for (int i = 0; i < vibrationPattern.length; i++) {
Number next = iterator.next();
if (next != null) {
vibrationPattern[i] = next.longValue();
}
}
}
} catch (Exception e) {
Log.w("Failed to parse vibration pattern.");
}
// Sanity checks.
if (importance < NotificationManager.IMPORTANCE_NONE &&
importance > NotificationManager.IMPORTANCE_MAX) {
importance = NotificationManager.IMPORTANCE_DEFAULT;
}
if (lockscreenVisibility < Notification.VISIBILITY_SECRET &&
lockscreenVisibility > Notification.VISIBILITY_PUBLIC) {
lockscreenVisibility = Notification.VISIBILITY_PUBLIC;
}
}
@Override
public void onCreate() {
// registerNetReceiver();
super.onCreate();
if (isOAndBoot) {
//android 8.0 boot
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("vhosts_channel_id", "System", NotificationManager.IMPORTANCE_NONE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
Notification notification = new Notification.Builder(this, "vhosts_channel_id")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Virtual Hosts Running")
.build();
startForeground(1, notification);
}
isOAndBoot=false;
}
setupHostFile();
setupVPN();
if (vpnInterface == null) {
LogUtils.d(TAG, "unknow error");
stopVService();
return;
}
isRunning = true;
try {
udpSelector = Selector.open();
tcpSelector = Selector.open();
deviceToNetworkUDPQueue = new ConcurrentLinkedQueue<>();
deviceToNetworkTCPQueue = new ConcurrentLinkedQueue<>();
networkToDeviceQueue = new ConcurrentLinkedQueue<>();
udpSelectorLock = new ReentrantLock();
tcpSelectorLock = new ReentrantLock();
executorService = Executors.newFixedThreadPool(5);
executorService.submit(new UDPInput(networkToDeviceQueue, udpSelector, udpSelectorLock));
executorService.submit(new UDPOutput(deviceToNetworkUDPQueue, networkToDeviceQueue, udpSelector, udpSelectorLock, this));
executorService.submit(new TCPInput(networkToDeviceQueue, tcpSelector, tcpSelectorLock));
executorService.submit(new TCPOutput(deviceToNetworkTCPQueue, networkToDeviceQueue, tcpSelector, tcpSelectorLock, this));
executorService.submit(new VPNRunnable(vpnInterface.getFileDescriptor(),
deviceToNetworkUDPQueue, deviceToNetworkTCPQueue, networkToDeviceQueue));
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_VPN_STATE).putExtra("running", true));
LogUtils.i(TAG, "Started");
} catch (Exception e) {
// TODO: Here and elsewhere, we should explicitly notify the user of any errors
// and suggest that they stop the service, since we can't do it ourselves
LogUtils.e(TAG, "Error starting service", e);
stopVService();
}
}
public static boolean isPermissionOpen(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
return NotificationManagerCompat.from(context).getImportance() != NotificationManager.IMPORTANCE_NONE;
}
return NotificationManagerCompat.from(context).areNotificationsEnabled();
}
/**
* Checks whether notifications are enabled.
* @param channelName The name of the notification channel to be used on Android O+.
* @return Whether notifications are enabled.
*/
protected boolean areNotificationsEnabled(String channelName) {
ensureOnCreateCalled();
if (!NotificationManagerCompat.from(this).areNotificationsEnabled()) return false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return true;
String channelId = channelNameToId(channelName);
NotificationChannel channel = mNotificationManager.getNotificationChannel(channelId);
return channel == null || channel.getImportance() != NotificationManager.IMPORTANCE_NONE;
}