即使我的应用程序已关闭,我也会尝试在Android通知栏中显示通知。
我尝试过搜索,但我没有找到帮助。
这方面的一个例子是新闻应用程序。即使手机屏幕关闭或新闻应用程序关闭,它仍然可以发送最近新闻的通知并将其显示在通知栏中。
我如何在自己的应用程序中执行此操作?
答案 0 :(得分:16)
您必须构建一个处理新闻的服务,并在知道新消息时显示通知(Service Doc)。 即使您的应用程序已关闭,该服务也将在后台运行。 启动阶段完成后,您需要 BroadcastReciever 在后台运行该服务。 (Start service after boot)。
该服务将构建您的通知并通过NotificationManager发送。
编辑:This article可能符合您的需求
答案 1 :(得分:1)
所选答案仍然正确,但仅适用于运行Android 7及以下版本的设备。
从Android 8+开始,您的应用处于闲置/关闭状态时,您将无法再在后台运行服务。
因此,现在取决于您如何通过GCM / FCM服务器设置通知。确保将其设置为最高优先级。如果您的应用程序处于后台或仅处于未激活状态,并且您仅发送通知数据,则系统会处理您的通知并将其发送到通知托盘。
答案 2 :(得分:0)
我使用this answer来编写服务,作为一个例子,您需要在一个活动中调用ShowNotificationIntentService.startActionShow(getApplicationContext())
:
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
public class ShowNotificationIntentService extends IntentService {
private static final String ACTION_SHOW_NOTIFICATION = "my.app.service.action.show";
private static final String ACTION_HIDE_NOTIFICATION = "my.app.service.action.hide";
public ShowNotificationIntentService() {
super("ShowNotificationIntentService");
}
public static void startActionShow(Context context) {
Intent intent = new Intent(context, ShowNotificationIntentService.class);
intent.setAction(ACTION_SHOW_NOTIFICATION);
context.startService(intent);
}
public static void startActionHide(Context context) {
Intent intent = new Intent(context, ShowNotificationIntentService.class);
intent.setAction(ACTION_HIDE_NOTIFICATION);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_SHOW_NOTIFICATION.equals(action)) {
handleActionShow();
} else if (ACTION_HIDE_NOTIFICATION.equals(action)) {
handleActionHide();
}
}
}
private void handleActionShow() {
showStatusBarIcon(ShowNotificationIntentService.this);
}
private void handleActionHide() {
hideStatusBarIcon(ShowNotificationIntentService.this);
}
public static void showStatusBarIcon(Context ctx) {
Context context = ctx;
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx)
.setContentTitle(ctx.getString(R.string.notification_message))
.setSmallIcon(R.drawable.ic_notification_icon)
.setOngoing(true);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, STATUS_ICON_REQUEST_CODE, intent, 0);
builder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notif = builder.build();
notif.flags |= Notification.FLAG_ONGOING_EVENT;
mNotificationManager.notify(STATUS_ICON_REQUEST_CODE, notif);
}
}