下面列出了android.app.Notification#FLAG_NO_CLEAR 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private Notification getServiceRunningNotification()
{
Intent i = new Intent(this, FileManagerActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CompatHelper.getServiceRunningNotificationsChannelId(this))
.setContentTitle(getString(R.string.eds_service_is_running))
.setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_notification_new : R.drawable.ic_notification)
.setContentText("")
.setContentIntent(PendingIntent.getActivity(this, 0, i, 0))
.setOngoing(true)
.addAction(
R.drawable.ic_action_cancel,
getString(R.string.close_all_containers),
PendingIntent.getActivity(
this,
0,
new Intent(this, CloseLocationsActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT
)
);
Notification n = builder.build();
n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_FOREGROUND_SERVICE;
return n;
}
@SuppressWarnings("deprecation")
protected void notice() {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launch_notice,
getString(R.string.app_name), System.currentTimeMillis());
n.flags = Notification.FLAG_NO_CLEAR;
Intent intent = new Intent(this, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this,
R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
n.setLatestEventInfo(this, this.getString(R.string.app_name),
my_ticker_text, contentIntent);
nm.notify(my_notice_id, n);
}
public Notify show() {
if (!enabled) return this;
Notification notification = build();
if (locked && context instanceof Service) {
((Service) context).startForeground(id, notification);
return this;
}
if (locked) {
notification.flags |= Notification.FLAG_NO_CLEAR;
}
nm.notify(id, build()); return this;
}
@SuppressWarnings("deprecation")
private void enableNotification() {
// Intent to call to turn off AutoAnswer
Intent notificationIntent = new Intent(mContext, AutoAnswerPreferenceActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
// Create the notification
Notification n = new Notification(R.drawable.ic_launcher, null, 0);
n.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
n.setLatestEventInfo(mContext, mContext.getString(R.string.notification_title), mContext.getString(R.string.notification_text), pendingIntent);
mNotificationManager.notify(NOTIFICATION_ID, n);
}
synchronized
private void innerStartListening() {
switch(state) {
case STATE_READY:
break;
case STATE_LISTENING:
case STATE_RECORDING:
return;
}
state = STATE_LISTENING;
Log.d(TAG, "STARTING LISTENING");
Notification note = new Notification( 0, null, System.currentTimeMillis() );
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground( 42, note );
audioThread = new HandlerThread("audioThread", Thread.MAX_PRIORITY);
audioThread.start();
audioHandler = new Handler(audioThread.getLooper());
audioHandler.post(new Runnable() {
@Override
public void run() {
audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC,
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
44100 * 5 * 2); // five seconds in bytes
audioRecord.startRecording();
}
});
audioHandler.post(audioReader);
}
/**
* Displays the server status notification
*
* @param notificationId notification ID to use
* @param notificationDrawableId Drawable ID to use
* @param appName application name
* @param notificationTitle the notification title
* @param notificationMessage the notification message
*/
@SuppressWarnings("deprecation")
private void displayNotification(int notificationId, int notificationDrawableId, String appName, String notificationTitle, String notificationMessage) {
try {
int icon = notificationDrawableId;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, notificationTitle, when);
Context context = getApplicationContext();
Intent notificationIntent = new Intent(this,
Class.forName(activityClass));
notificationIntent.setAction("android.intent.action.MAIN");
notificationIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context,
appName,
notificationMessage,
contentIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
//notificationManager.notify(NOTIFICATION_ID, notification);
ServiceCompat sc = new ServiceCompat(this);
sc.startForegroundCompat(notificationId, notification);
} catch (Resources.NotFoundException e) {
// shouldn't happen
} catch (ClassNotFoundException ec) {
Log.e(TAG, "Could not create notification: " + ec.getMessage());
}
}
/**
* show current enviroment
*
* @param rscId
*/
private void showNotification(int rscId) {
Notification n = new Notification(R.drawable.switchenv, getResources().getString(rscId),
(System.currentTimeMillis() + 1000));
n.flags = Notification.FLAG_NO_CLEAR;
n.setLatestEventInfo(context, getResources().getString(R.string.app_name), getResources().getString(rscId),
null);
n.contentView.setViewVisibility(android.R.id.progress, View.GONE);
n.contentIntent = PendingIntent.getActivity(context, 0, new Intent(this, MainActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
notiManager.notify(0, n);
}
private void initNotification() {
notification = new Notification(R.drawable.icon, "Pedometer started.", System.currentTimeMillis());
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
}
/** Convenience method to check the notification's flags for
* either {@link Notification#FLAG_ONGOING_EVENT} or
* {@link Notification#FLAG_NO_CLEAR}.
*/
public boolean isClearable() {
return ((notification.flags & Notification.FLAG_ONGOING_EVENT) == 0)
&& ((notification.flags & Notification.FLAG_NO_CLEAR) == 0);
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "service started");
sPausedVoluntarilz = false;
wasVoluntaryStart();
settings = PreferenceManager.getDefaultSharedPreferences(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
filter.addAction(Intent.ACTION_REBOOT);
filter.addAction(Intent.ACTION_SHUTDOWN);
filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mTrustReceivers = new TrustReceivers();
registerReceiver(mTrustReceivers, filter);
IntentFilter filterPackage = new IntentFilter();
filterPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
filterPackage.addAction(Intent.ACTION_PACKAGE_CHANGED);
filterPackage.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
filterPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
filterPackage.addAction(Intent.ACTION_PACKAGE_REPLACED);
filterPackage.addAction(Intent.ACTION_PACKAGE_RESTARTED);
filterPackage.addDataScheme("package");
registerReceiver(mTrustReceivers, filterPackage);
sIsRunning = true;
mNotification = new Notification(R.drawable.ic_launcher, "Trust is good", System.currentTimeMillis());
Intent i = new Intent(this, TrustActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mPendingIntent = PendingIntent.getActivity(this, 0, i, 0);
mNotification.setLatestEventInfo(this, "Control is better", "Trust running", mPendingIntent);
mNotification.flags |= Notification.FLAG_NO_CLEAR;
mNotification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
if (settings.getBoolean("general.notification", false))
startForeground(NOTIFICATION_ID, mNotification);
mAppWatcher = new AppWatcher(this);
mAppWatcher.startWatching();
}
private void showNotification(long millisUntilFinished) {
String text;
if (millisUntilFinished > 0) {
text = getString(R.string.mobile_cells_registration_pref_dlg_status_started);
String time = getString(R.string.mobile_cells_registration_pref_dlg_status_remaining_time);
long iValue = millisUntilFinished / 1000;
time = time + ": " + GlobalGUIRoutines.getDurationString((int) iValue);
text = text + "; " + time;
if (android.os.Build.VERSION.SDK_INT < 24) {
text = text + " (" + getString(R.string.ppp_app_name) + ")";
}
}
else {
text = getString(R.string.mobile_cells_registration_pref_dlg_status_stopped);
}
PPApplication.createMobileCellsRegistrationNotificationChannel(this);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, PPApplication.MOBILE_CELLS_REGISTRATION_NOTIFICATION_CHANNEL)
.setColor(ContextCompat.getColor(this, R.color.notificationDecorationColor))
.setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
.setContentTitle(getString(R.string.phone_profiles_pref_applicationEventMobileCellsRegistration_notification)) // title for notification
.setContentText(text) // message for notification
.setAutoCancel(true); // clear notification after click
if (millisUntilFinished > 0) {
Intent stopRegistrationIntent = new Intent(ACTION_MOBILE_CELLS_REGISTRATION_STOP_BUTTON);
PendingIntent stopRegistrationPendingIntent = PendingIntent.getBroadcast(context, 0, stopRegistrationIntent, 0);
mBuilder.addAction(R.drawable.ic_action_stop_white,
context.getString(R.string.phone_profiles_pref_applicationEventMobileCellsRegistration_stop),
stopRegistrationPendingIntent);
}
mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
//if (android.os.Build.VERSION.SDK_INT >= 21)
//{
mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
//}
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
notification.flags &= ~Notification.FLAG_SHOW_LIGHTS;
notification.ledOnMS = 0;
notification.ledOffMS = 0;
notification.sound = null;
notification.vibrate = null;
notification.defaults &= ~DEFAULT_SOUND;
notification.defaults &= ~DEFAULT_VIBRATE;
startForeground(PPApplication.MOBILE_CELLS_REGISTRATION_SERVICE_NOTIFICATION_ID, notification);
}
@Override
public void onWorkerStarted() {
notification.flags |= Notification.FLAG_NO_CLEAR;
notificationManager.notify(uniqueId, notification);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.switch_only_alert_once:
mBuilder.setOnlyAlertOnce(binding.switchOnlyAlertOnce.isChecked());
break;
case R.id.switch_auto_cancel:
mBuilder.setAutoCancel(binding.switchAutoCancel.isChecked());
break;
case R.id.switch_ongoing:
mBuilder.setOngoing(binding.switchOngoing.isChecked());
break;
case R.id.switch_info:
mBuilder.setContentInfo("info");
break;
case R.id.switch_public:
if (binding.switchPublic.isChecked()) {
mBuilder.setPublicVersion(NotifyUtil.create(this, R.mipmap.ic_wazhi, "public title", "public content.").build());
} else {
mBuilder.setPublicVersion(null);
}
break;
case R.id.switch_large_icon:
if (binding.switchLargeIcon.isChecked()) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.large_icon);
mBuilder.setLargeIcon(bitmap);
} else {
mBuilder.setLargeIcon(null);
}
break;
case R.id.switch_ticker:
if (binding.switchTicker.isChecked()) {
mBuilder.setTicker("this is ticker");
} else {
mBuilder.setTicker(null);
}
break;
case R.id.switch_sub:
if (binding.switchSub.isChecked()) {
mBuilder.setSubText("his is sub");
} else {
mBuilder.setSubText(null);
}
break;
case R.id.switch_content_intent:
if (binding.switchContentIntent.isChecked()) {
mBuilder.setContentIntent(pi(2000));
} else {
mBuilder.setContentIntent(null);
mBuilder.mNotification.contentIntent = null;
}
break;
case R.id.switch_delete_intent:
if (binding.switchDeleteIntent.isChecked()) {
mBuilder.setDeleteIntent(pi(2001));
} else {
mBuilder.setDeleteIntent(null);
mBuilder.mNotification.deleteIntent = null;
}
break;
case R.id.switch_full_screen_intent:
if (binding.switchFullScreenIntent.isChecked()) {
mBuilder.setFullScreenIntent(pi(2002), true);
} else {
mBuilder.setFullScreenIntent(null, false);
mBuilder.mNotification.fullScreenIntent = null;
}
break;
case R.id.clear_all:
NotifyUtil.cancelAll(this);
break;
case R.id.clear:
NotifyUtil.cancel(this, mNotifyId);
break;
case R.id.send:
mNotifyId++;
final Notification notification = mBuilder.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (notification.publicVersion != null && notification.visibility == Notification.VISIBILITY_PUBLIC) {
binding.getRoot().postDelayed(new Runnable() {
@Override
public void run() {
NotifyUtil.notify(mBuilder.mContext, mNotifyId, notification);
}
}, 5000);
break;
}
}
if (binding.switchInsistent.isChecked()) {
notification.flags |= Notification.FLAG_INSISTENT;
}
if (binding.switchNoClear.isChecked()) {
notification.flags |= Notification.FLAG_NO_CLEAR;
}
NotifyUtil.notify(this, mNotifyId, notification);
break;
}
}
private void pingNotification(){
notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
remoteViews = new RemoteViews(getPackageName(),
R.layout.remote_notification);
// Open NotificationView Class on Notification Click
Intent intent = new Intent(this, MainActivity.class);
// Send data to NotificationView Class
// Open NotificationView.java Activity
PendingIntent pIntent = PendingIntent.getService(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
android.support.v4.app.NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// Set Icon
.setSmallIcon(R.mipmap.ic_launcher)
// Set Ticker Message
.setTicker("Use notification to paste account info")
// Set PendingIntent into Notification
.setContentIntent(pIntent);
notification = builder.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.bigContentView = remoteViews;
notification.contentView = remoteViews;
//Wire up actions.
Intent pasteAccountIntent = new Intent(this, NotificationService.class);
pasteAccountIntent.setAction(AppConstants.SERVICE_CMD_PASTE_ACCT);
PendingIntent pasteAccountPendingIntent = PendingIntent.getService(this, 0, pasteAccountIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.account, pasteAccountPendingIntent);
Intent pastePasswordIntent = new Intent(this, NotificationService.class);
pastePasswordIntent.setAction(AppConstants.SERVICE_CMD_PASTE_PSWD);
PendingIntent pastePasswordPendingIntent = PendingIntent.getService(this, 0, pastePasswordIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.password, pastePasswordPendingIntent);
Intent pasteAddtIntent = new Intent(this, NotificationService.class);
pasteAddtIntent.setAction(AppConstants.SERVICE_CMD_PASTE_ADDT);
PendingIntent pasteAddtPendingIntent = PendingIntent.getService(this, 0, pasteAddtIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.additional, pasteAddtPendingIntent);
Intent clearIntent = new Intent(this, NotificationService.class);
clearIntent.setAction("stop");
PendingIntent clearPendingIntent = PendingIntent.getService(this, 0, clearIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.clear, clearPendingIntent);
//Setup remote views.
if (StringUtil.isNullOrEmpty(account))
remoteViews.setViewVisibility(R.id.account, View.GONE);
if (StringUtil.isNullOrEmpty(password))
remoteViews.setViewVisibility(R.id.password, View.GONE);
if (StringUtil.isNullOrEmpty(additional))
remoteViews.setViewVisibility(R.id.additional, View.GONE);
remoteViews.setTextViewText(R.id.remote_name, name);
Picasso.with(this).load(ResUtil.getInstance(getApplicationContext()).getBmpUri(icon))
.into(remoteViews, R.id.remote_icon, 22333, notification);
startForeground(22333, notification);
}
/**
* Updates the notification in the notification bar which shows the current step and the remaining
* time left. This is updated every time the timer ticks down, as well as in special cases (like
* when the timer changes state).
*
* @param title
* @param remaining
*/
public void updateNotification(String title, int remaining) {
// Build remaining time string
java.text.DecimalFormat nft = new java.text.DecimalFormat("#00.###");
nft.setDecimalSeparatorAlwaysShown(false);
// Grab hours, minutes, and seconds
int hours = (int) (remaining / 3600);
int minutes = (int) ((remaining - 3600 * hours) / 60);
int seconds = remaining - (hours * 3600) - (minutes * 60);
String remainingTime = "Next step in: " +
nft.format(hours) + ":" +
nft.format(minutes) + ":" +
nft.format(seconds);
// If no time remains, the timer is paused.
if (timer.timerState == Constants.PAUSED) {
remainingTime = "Paused";
}
// Notification builders
NotificationCompat.Builder nBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(title)
.setContentText(remainingTime);
// Intent for when notification is clicked.
brewTimerIntent = new Intent(this, BrewTimerActivity.class);
brewTimerIntent.putExtra(Constants.KEY_RECIPE, r);
brewTimerIntent.putExtra(Constants.KEY_STEP_NUMBER, currentStepNumber);
brewTimerIntent.putExtra(Constants.KEY_TIMER_STATE, timer.timerState);
brewTimerIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, brewTimerIntent, PendingIntent.FLAG_UPDATE_CURRENT);
nBuilder.setContentIntent(pi);
Notification note = nBuilder.build();
note.flags |= Notification.FLAG_NO_CLEAR;
// Start the notification
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (! notificationStarted) {
startForeground(notificationId, note);
notificationStarted = true;
}
else {
nm.notify(notificationId, note);
}
}
private void innerStartListening() {
switch(state) {
case STATE_READY:
break;
case STATE_LISTENING:
case STATE_RECORDING:
return;
}
state = STATE_LISTENING;
Log.d(TAG, "Queueing: START LISTENING");
startService(new Intent(this, this.getClass()));
final long memorySize = getSharedPreferences(PACKAGE_NAME, MODE_PRIVATE).getLong(AUDIO_MEMORY_SIZE_KEY, Runtime.getRuntime().maxMemory() / 4);
Notification note = new Notification( 0, null, System.currentTimeMillis() );
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(42, note);
startService(new Intent(this, FakeService.class));
audioHandler.post(new Runnable() {
@Override
public void run() {
Log.d(TAG, "Executing: START LISTENING");
Log.d(TAG, "Audio: INITIALIZING AUDIO_RECORD");
audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC,
SAMPLE_RATE,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
512 * 1024); // .5MB
if(audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
Log.e(TAG, "Audio: INITIALIZATION ERROR - releasing resources");
audioRecord.release();
audioRecord = null;
state = STATE_READY;
return;
}
Log.d(TAG, "Audio: STARTING AudioRecord");
audioMemory.allocate(memorySize);
Log.d(TAG, "Audio: STARTING AudioRecord");
audioRecord.startRecording();
audioHandler.post(audioReader);
}
});
}
void createNotification() {
if (notification != null) return;
createMediaSession();
Intent playPauseIntent = new Intent(context, MusicService.class);
playPauseIntent.putExtra(MusicService.KEY_ACTION, MusicService.ACTION_PLAY_PAUSE);
PendingIntent playPausePendingIntent = PendingIntent.getService(context, MusicService.ACTION_PLAY_PAUSE, playPauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent previousIntent = new Intent(context, MusicService.class);
previousIntent.putExtra(MusicService.KEY_ACTION, MusicService.ACTION_PREVIOUS);
PendingIntent previousPendingIntent = PendingIntent.getService(context, MusicService.ACTION_PREVIOUS, previousIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent nextIntent = new Intent(context, MusicService.class);
nextIntent.putExtra(MusicService.KEY_ACTION, MusicService.ACTION_NEXT);
PendingIntent nextPendingIntent = PendingIntent.getService(context, MusicService.ACTION_NEXT, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent addIntent = new Intent(context, MusicService.class);
addIntent.putExtra(MusicService.KEY_ACTION, MusicService.ACTION_ADD);
PendingIntent addPendingIntent = PendingIntent.getService(context, MusicService.ACTION_ADD, addIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent dismissIntent = new Intent(context, MusicService.class);
dismissIntent.putExtra(MusicService.KEY_ACTION, MusicService.ACTION_DISMISS);
PendingIntent dismissPendingIntent = PendingIntent.getService(context, MusicService.ACTION_DISMISS, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent openActivityIntent = new Intent(context, MusicService.class);
openActivityIntent.putExtra(MusicService.KEY_ACTION, MusicService.ACTION_OPEN_ACTIVITY);
PendingIntent openActivityPendingIntent = PendingIntent.getService(context, MusicService.ACTION_OPEN_ACTIVITY, openActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationViewSmall = new RemoteViews(context.getPackageName(), R.layout.layout_notification_small);
notificationViewSmall.setTextViewText(R.id.title, context.getString(R.string.no_track_playing));
notificationViewSmall.setTextViewText(R.id.artist, "");
notificationViewSmall.setOnClickPendingIntent(R.id.play_pause, playPausePendingIntent);
notificationViewSmall.setOnClickPendingIntent(R.id.previous, previousPendingIntent);
notificationViewSmall.setOnClickPendingIntent(R.id.next, nextPendingIntent);
notificationViewSmall.setOnClickPendingIntent(R.id.dismiss, dismissPendingIntent);
notificationViewLarge = new RemoteViews(context.getPackageName(), R.layout.layout_notification_large);
notificationViewLarge.setTextViewText(R.id.title, context.getString(R.string.no_track_playing));
notificationViewLarge.setTextViewText(R.id.artist, "");
notificationViewLarge.setOnClickPendingIntent(R.id.play_pause, playPausePendingIntent);
notificationViewLarge.setOnClickPendingIntent(R.id.previous, previousPendingIntent);
notificationViewLarge.setOnClickPendingIntent(R.id.next, nextPendingIntent);
notificationViewLarge.setOnClickPendingIntent(R.id.dismiss, dismissPendingIntent);
notificationViewLarge.setOnClickPendingIntent(R.id.add, addPendingIntent);
notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(openActivityPendingIntent)
.setContentTitle("vk Music")
.setContent(notificationViewSmall)
.setCustomBigContentView(notificationViewLarge)
.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
notificationManager = (android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
}
public static Notification makeNotification(Context context, String artist, String track, long duration, boolean retentionNotif, boolean isPlaying) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
boolean prefOverlay = sharedPref.getBoolean("pref_overlay", false) && (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(context));
int notificationPref = prefOverlay ? 2 : Integer.valueOf(sharedPref.getString("pref_notifications", "0"));
Intent activityIntent = new Intent(context.getApplicationContext(), MainActivity.class)
.setAction("com.geecko.QuickLyric.getLyrics")
.putExtra("retentionNotif", retentionNotif)
.putExtra("TAGS", new String[]{artist, track});
Intent wearableIntent = new Intent("com.geecko.QuickLyric.SEND_TO_WEARABLE")
.putExtra("artist", artist).putExtra("track", track).putExtra("duration", duration);
final Intent overlayIntent = new Intent(context.getApplicationContext(), LyricsOverlayService.class)
.setAction(LyricsOverlayService.CLICKED_FLOATING_ACTION);
PendingIntent overlayPending = PendingIntent.getService(context.getApplicationContext(), 0, overlayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent openAppPending = PendingIntent.getActivity(context.getApplicationContext(), 0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent wearablePending = PendingIntent.getBroadcast(context.getApplicationContext(), 8, wearableIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Action wearableAction =
new NotificationCompat.Action.Builder(R.drawable.ic_watch,
context.getString(R.string.wearable_prompt), wearablePending)
.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(notificationPref == 1 && isPlaying ? TRACK_NOTIF_CHANNEL : TRACK_NOTIF_HIDDEN_CHANNEL,
context.getString(R.string.pref_notifications),
notificationPref == 1 && isPlaying ? NotificationManager.IMPORTANCE_LOW : NotificationManager.IMPORTANCE_MIN);
notificationChannel.setShowBadge(false);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(context.getApplicationContext(), notificationPref == 1 && isPlaying ? TRACK_NOTIF_CHANNEL : TRACK_NOTIF_HIDDEN_CHANNEL);
NotificationCompat.Builder wearableNotifBuilder = new NotificationCompat.Builder(context.getApplicationContext(), TRACK_NOTIF_HIDDEN_CHANNEL);
int[] themes = new int[]{R.style.Theme_QuickLyric, R.style.Theme_QuickLyric_Red,
R.style.Theme_QuickLyric_Purple, R.style.Theme_QuickLyric_Indigo,
R.style.Theme_QuickLyric_Green, R.style.Theme_QuickLyric_Lime,
R.style.Theme_QuickLyric_Brown, R.style.Theme_QuickLyric_Dark};
int themeNum = Integer.valueOf(sharedPref.getString("pref_theme", "0"));
context.setTheme(themes[themeNum]);
notifBuilder.setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_notif : R.drawable.ic_notif4)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(String.format("%s - %s", artist, track))
.setContentIntent(prefOverlay ? overlayPending : openAppPending)
.setVisibility(-1) // Notification.VISIBILITY_SECRET
.setGroup("Lyrics_Notification")
.setColor(ColorUtils.getPrimaryColor(context))
.setShowWhen(false)
.setGroupSummary(true);
wearableNotifBuilder.setSmallIcon(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_notif : R.drawable.ic_notif4)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(String.format("%s - %s", artist, track))
.setContentIntent(openAppPending)
.setVisibility(-1) // Notification.VISIBILITY_SECRET
.setGroup("Lyrics_Notification")
.setOngoing(false)
.setColor(ColorUtils.getPrimaryColor(context))
.setGroupSummary(false)
.setShowWhen(false)
.extend(new NotificationCompat.WearableExtender().addAction(wearableAction));
if (notificationPref == 2) {
notifBuilder.setOngoing(true).setPriority(-2); // Notification.PRIORITY_MIN
wearableNotifBuilder.setPriority(-2);
} else
notifBuilder.setPriority(-1); // Notification.PRIORITY_LOW
Notification notif = notifBuilder.build();
Notification wearableNotif = wearableNotifBuilder.build();
if (notificationPref == 2 || Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
notif.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
if (notificationPref == 1)
notif.flags |= Notification.FLAG_AUTO_CANCEL;
try {
context.getPackageManager().getPackageInfo("com.google.android.wearable.app", PackageManager.GET_META_DATA);
NotificationManagerCompat.from(context).notify(8, wearableNotif); // TODO Make Android Wear app
} catch (PackageManager.NameNotFoundException ignored) {
}
return notif;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification note = new Notification( 0, null, System.currentTimeMillis() );
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(42, note);
stopForeground(true);
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
private void createShowNotification() {
NotificationManager mNF = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String name = "com_hardwork_fg607_relaxfinger_channel";
String id = "悬浮助手";
String description = "悬浮助手channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNF.createNotificationChannel(mChannel);
mBuilder =
new NotificationCompat.Builder(mContext,id)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("RelaxFinger")
.setTicker("悬浮球隐藏到通知栏啦,点击显示!")
.setContentText("点击显示悬浮球");
}else{
mBuilder =
new NotificationCompat.Builder(mContext)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("RelaxFinger")
.setTicker("悬浮球隐藏到通知栏啦,点击显示!")
.setContentText("点击显示悬浮球");
}
Intent resultIntent = new Intent(Config.ACTION_SHOW_FLOATBALL);
PendingIntent resultPendingIntent = PendingIntent.getBroadcast(mContext,(int) SystemClock.uptimeMillis(), resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
mNF.notify(R.string.app_name, notification);
}