使通知可点击且不可破坏

时间:2013-08-30 14:52:02

标签: java android android-intent notifications android-pendingintent

我尝试创建一个通知,通过点击它来启动活动,但是你无法轻扫。

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("DroidSchool")
                .setContentText("DroidSchool l\u00E4uft im Hintergrund...");

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_FROM_BACKGROUND);

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        int mId = 1234567890;
        mNotificationManager.notify(mId, mBuilder.build());

使用上面的代码显示通知但是当我点击它时没有任何反应,你可以将它滑开。

5 个答案:

答案 0 :(得分:3)

要保留通知,用户不能以任何方式点击它,添加此标志

Notification mNotification = mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(mId, notification);

要启动活动,您必须将此标志用于您的意图

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

答案 1 :(得分:1)

这样做:

 NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("DroidSchool")
            .setContentText("DroidSchool l\u00E4uft im Hintergrund...");

    Intent intent = new Intent(YourActivity.this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);


   Notification noti = mBuilder.build();

   noti.flags |= mBuilder.build().FLAG_NO_CLEAR | mBuilder.build().FLAG_ONGOING_EVENT;

   NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.notify(0, noti);  

答案 2 :(得分:0)

您希望前台服务详细here

值得注意的是,只有android 4.3添加了您似乎要遵循的持久通知,并且可以通过用户设置覆盖它。

答案 3 :(得分:0)

尝试使用像这样的

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_UPDATE_CURRENT);
MainActivity.java中的

不要使用您的通知;即不是在onDestro()

下的oncreate()调用中调用低于2行代码
 NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancel(mId);

答案 4 :(得分:0)

您可以使用NotificationCompat.Builder的{​​{1}},像这样使用它:

.setOngoing(true)