下面列出了android.app.Service#startForeground ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Posts the notification and starts tracking the session to keep it
* updated. The notification will automatically be removed if the session is
* destroyed before {@link #stopNotification} is called.
*/
public void startNotification(Service service) {
if (!mStarted) {
mMetadata = mController.getMetadata();
mPlaybackState = mController.getPlaybackState();
// The notification must be updated after setting started to true
Notification notification = createNotification();
if (notification != null) {
mController.registerCallback(mCb);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_NEXT);
filter.addAction(ACTION_PAUSE);
filter.addAction(ACTION_PLAY);
filter.addAction(ACTION_PREV);
filter.addAction(ACTION_STOP_CASTING);
mContext.registerReceiver(this, filter);
service.startForeground(NOTIFICATION_ID, notification);
mStarted = true;
}
}
}
@Override
public void startServiceForeground(Service service, String title, String contentText, int priority) {
Intent i = new Intent(service, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(service, 0, i, 0);
builder = new NotificationCompat.Builder(service);
builder.setContentTitle(title).setContentText(contentText)
.setSmallIcon(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP ? R.drawable.ic_notification : R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setAutoCancel(false)
.setOngoing(true)
.setPriority(priority)
.setContentIntent(pendIntent);
Notification notification = builder.build();
service.startForeground(myID, notification);
}
/**
* フォアグラウンドサービス用に通知を発行する
* @param service
* @param tag
* @param notificationId
* @return
*/
public NotificationBuilder notifyForeground(@NonNull final Service service,
@Nullable final String tag, final int notificationId) {
final Notification notification = build();
service.startForeground(notificationId, notification);
notify(service, tag, notificationId, notification);
return this;
}
/**
* DConnectServiceがOFF時にstartForegroundService()が行われた時にキャンセルする.
*/
public static void fakeStartForeground(final Service service,
final String channelId,
final String title,
final String description,
final int notificationId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder builder = new Notification.Builder(service.getApplicationContext(),
channelId)
.setContentTitle("").setContentText("");
NotificationChannel channel = new NotificationChannel(
channelId,
title,
NotificationManager.IMPORTANCE_LOW);
channel.setDescription(description);
int iconType = Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ?
R.drawable.icon : R.drawable.on_icon;
builder.setSmallIcon(iconType);
NotificationManager mNotification = (NotificationManager) service.getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotification.createNotificationChannel(channel);
builder.setChannelId(channelId);
service.startForeground(notificationId, builder.build());
service.stopForeground(true);
service.stopSelf();
}
}
public static void createStopNotification(MediaSessionCompat mediaSession,
Service context,
Class<?> serviceClass,
String NOTIFICATION_CHANNEL_ID,
int NOTIFICATION_ID,
String httpStreamUrl) {
createNotificationChannel(context, NOTIFICATION_CHANNEL_ID);
PendingIntent stopIntent = PendingIntent.getService(context, 0, getServiceActionIntent(VinylCastService.ACTION_STOP_RECORDING, context, serviceClass), PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent mainActivityIntent = PendingIntent.getActivity(context, 0, getActivityIntent(context, MainActivity.class), 0);
MediaControllerCompat controller = mediaSession.getController();
MediaMetadataCompat mediaMetadata = controller.getMetadata();
MediaDescriptionCompat mediaDescription = mediaMetadata == null ? null : mediaMetadata.getDescription();
CharSequence contentTitle = mediaDescription == null ? context.getString(R.string.notification_content_title) : mediaDescription.getTitle();
CharSequence contentText = mediaDescription == null ? httpStreamUrl : mediaDescription.getSubtitle();
CharSequence subText = mediaDescription == null ? null : mediaDescription.getDescription();
Bitmap largeIcon = mediaDescription == null ? null : mediaDescription.getIconBitmap();
// Start foreground service to avoid unexpected kill
Notification notification = new Builder(context)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setSubText(subText)
.setLargeIcon(largeIcon)
.setContentIntent(mainActivityIntent)
.setDeleteIntent(stopIntent)
.setShowWhen(false)
// Add a pause button
.addAction(new Action(
R.drawable.ic_stop_black_24dp, context.getString(R.string.button_stop),
MediaButtonReceiver.buildMediaButtonPendingIntent(context,
PlaybackStateCompat.ACTION_STOP)))
.setStyle(new MediaStyle()
.setMediaSession(mediaSession.getSessionToken())
.setShowActionsInCompactView(0)
.setShowCancelButton(true)
.setCancelButtonIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(context,
PlaybackStateCompat.ACTION_STOP)))
.setSmallIcon(R.drawable.ic_record_black_100dp)
.setVisibility(VISIBILITY_PUBLIC)
.build();
context.startForeground(NOTIFICATION_ID, notification);
}
public static void startForeground(Service service) {
service.startService(new Intent(service, MPushFakeService.class));
service.startForeground(NOTIFICATION_ID, new Notification());
}
/**
* Post a notification displaying the given track in the status bare.
*
* @param service service started as foreground if no dismissible.
* @param track track displayed.
* @param isPaused true if the current player is paused. Then play action will be displayed.
* Otherwise, pause action will be displayed.
*/
public void notify(final Service service, final SoundCloudTrack track, boolean isPaused) {
if (mNotificationBuilder == null) {
initNotificationBuilder(service);
}
// set the title
mNotificationView.setTextViewText(R.id.simple_sound_cloud_notification_title, track.getArtist());
mNotificationView.setTextViewText(R.id.simple_sound_cloud_notification_subtitle, track.getTitle());
mNotificationExpandedView.setTextViewText(R.id.simple_sound_cloud_notification_title, track.getArtist());
mNotificationExpandedView.setTextViewText(R.id.simple_sound_cloud_notification_subtitle, track.getTitle());
// set the right icon for the toggle playback action.
if (isPaused) {
mNotificationView.setImageViewResource(
R.id.simple_sound_cloud_notification_play,
R.drawable.simple_sound_cloud_notification_play
);
mNotificationExpandedView.setImageViewResource(
R.id.simple_sound_cloud_notification_play,
R.drawable.simple_sound_cloud_notification_play
);
mNotificationBuilder.setOngoing(false);
} else {
mNotificationView.setImageViewResource(
R.id.simple_sound_cloud_notification_play,
R.drawable.simple_sound_cloud_notification_pause
);
mNotificationExpandedView.setImageViewResource(
R.id.simple_sound_cloud_notification_play,
R.drawable.simple_sound_cloud_notification_pause
);
mNotificationBuilder.setOngoing(true);
}
service.startForeground(NOTIFICATION_ID, buildNotification());
// since toggle playback is often pressed for the same track, only load the artwork when a
// new track is passed.
int newTrackId = track.getId();
if (mTrackId == -1 || mTrackId != newTrackId) {
loadArtwork(
service,
SoundCloudArtworkHelper.getArtworkUrl(track, SoundCloudArtworkHelper.XLARGE)
);
mTrackId = newTrackId;
}
}
static void startForeground(Service service, int id, Notification notification) {
service.startForeground(id, notification);
}
static void startForeground(Service service, int id, Notification notification) {
service.startForeground(id, notification);
}
public void startForeground(@NonNull Notification notification) {
Service service = (Service) context;
service.startForeground(notificationId, notification.onCreateNotification(context));
}
public static void show(Service ctx, boolean enable) {
NotificationManager ntfMgr = (NotificationManager)ctx.getSystemService(Service.NOTIFICATION_SERVICE);
if (enable || Cfg.PersistentNotification) {
PendingIntent edit = PendingIntent.getActivity(ctx, 0, new Intent(Intent.ACTION_EDIT, null, ctx, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent cancel = PendingIntent.getService(ctx, 0, new Intent(enable ? Intent.ACTION_DELETE : Intent.ACTION_RUN, null, ctx, FilterService.class), PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent increase = PendingIntent.getService(ctx, 0, new Intent(ctx.getString(R.string.intent_darker), null, ctx, FilterService.class), PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent decrease = PendingIntent.getService(ctx, 0, new Intent(ctx.getString(R.string.intent_brighter), null, ctx, FilterService.class), PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Action.Builder ntf_act_increase = new NotificationCompat.Action.Builder(R.drawable.ic_add_circle_outline,
ctx.getString(R.string.darker), increase);
NotificationCompat.Action.Builder ntf_act_decrease = new NotificationCompat.Action.Builder(R.drawable.ic_remove_circle_outline,
ctx.getString(R.string.brighter), decrease);
NotificationCompat.Action.Builder ntf_act_configure = new NotificationCompat.Action.Builder(R.drawable.ic_build,
ctx.getString(R.string.configure), edit);
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx)
.setContentTitle(ctx.getString(R.string.app_name) +
(enable ? " - " + Grids.PatternNames[Cfg.Pattern] : ""))
.setContentText(enable ? ctx.getString(R.string.tap_to_disable) : ctx.getString(R.string.enable_filter_checkbox))
.setContentInfo(ctx.getString(R.string.swipe_to_configure))
.setContentIntent(cancel)
.addAction(ntf_act_configure.build())
.addAction(ntf_act_increase.build())
.addAction(ntf_act_decrease.build())
.setDeleteIntent(cancel)
.setPriority(Cfg.HideNotification ? NotificationCompat.PRIORITY_MIN : NotificationCompat.PRIORITY_LOW)
.setSmallIcon(R.drawable.notification)
.setSound(null)
.setOngoing(true)
.setLocalOnly(true)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setTicker(null)
.setShowWhen(false);
Notification ntf = builder.build();
ctx.startForeground(NTF_ID, ntf);
} else {
ctx.stopForeground(true);
ntfMgr.cancel(NTF_ID);
}
}
public static void completeForegroundService(Service service, Intent intent, String tag) {
if (intent.getBooleanExtra(EXTRA_FOREGROUND, false) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.d(tag, "Started in foreground mode.");
service.startForeground(tag.hashCode(), buildForegroundNotification(service));
}
}