问题 如果应用关闭,后台有android通知吗?


即使我的应用程序已关闭,我也会尝试在Android通知栏中显示通知。

我试过搜索,但我找不到帮助。

一个例子是新闻应用程序。即使手机屏幕关闭或新闻应用程序关闭,它仍然可以发送最近新闻的通知并将其显示在通知栏中。

我如何在自己的应用程序中执行此操作?


6321
2017-09-15 12:48


起源

你找到了答案吗?!同样的问题在这里 - Mr.Hyde


答案:


你必须建立一个 服务 处理您的新闻并在知道新消息时显示通知(服务文件)。 即使您的应用程序已关闭,该服务也将在后台运行。 你需要一个 BroadcastReciever 在引导阶段完成后在后台运行服务。 (启动后启动服务)。

该服务将构建您的通知并通过它发送 NotificationManager

编辑: 本文 可能适合您的需求


14
2017-09-15 13:01





我用了 这个答案 写一个服务,作为一个例子你需要打电话 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);
    }
}

0
2017-08-02 18:09