Gmail喜欢通知功能android

时间:2014-12-24 09:30:04

标签: android android-notifications

我需要实现GMAIL之类的通知功能,即如果屏幕当前打开,则列表应自动刷新并且不会收到通知。如果应用已关闭,我们会收到通知。在GMAIL中,如果我们在收件箱中并且新邮件到达,它会自动附加在顶部而不通知,如果应用程序未打开,我们会收到新邮件的通知。 我编写了通知部分及其工作正常,但即使我正在进行当前活动,我仍然会收到通知,我仍然会收到通知。

以下是Intent类发送通知的代码

Intent listIntent = new Intent(this, ListActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ListActivity.class);
stackBuilder.addNextIntent(listIntent);

PendingIntent listPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("xxxx")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText("Update List"))
                .setContentText("Update List").setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setWhen(System.currentTimeMillis());
        builder.setContentIntent(listPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NOTIFICATION_ID, builder.build());

我在网络上研究了很多。但是没有得到任何相关的指示。 CommonsWare似乎有一个解决方案,但我不想使用任何外部库。同样在我的研究过程中,我发现知道哪项活动是最重要的并不是生产中的一个好习惯,因此也不能使用它来停止通知是我目前的活动是最重要的。请指教。

1 个答案:

答案 0 :(得分:1)

这个解决了你的问题

 ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
            boolean isActivityFound = false;

            if (services.get(0).topActivity.getPackageName().toString().equalsIgnoreCase(getPackageName().toString()))
            {
                isActivityFound = true;
            }
            if (!isActivityFound)
            {
                NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("xxxx")
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText("Update List"))
            .setContentText("Update List").setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setWhen(System.currentTimeMillis());
    builder.setContentIntent(listPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIFICATION_ID, builder.build());
            }