Android 8 上未显示通知

Notification is not shown on Android 8

我需要在 Android 上显示通知,但我找不到正确的解决方案。看起来一切都很完美。

XML of main Class(只是 ImageButton): **

<ImageButton
        android:id="@+id/notification"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="@color/colorPrimaryDark"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.35"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.695"
        app:srcCompat="@android:drawable/btn_star_big_on" />

**

初始化按钮:

private void addelement(){
notify = (ImageButton) findViewById(R.id.notification);
}

Notification() 方法:

public void notification (View view){
        Intent intent = new Intent(this, notification.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder b = new NotificationCompat.Builder(this);

    b.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setTicker("Hearty365")
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle("Default notification")
            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
            .setContentIntent(contentIntent)
            .setContentInfo("Info");


    NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, b.build());
}

我在 ImageButton

上调用我的 notifiction() 方法
notify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notification(view);
            }  
        });

现在这是我的通知activity:

public class notification extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);
    }
}

还有我的通知XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.carlosroldan.merlinminerapp.notification">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Info on the notification"
            android:id="@+id/Texto"
            android:textSize="16sp"
            />

</android.support.constraint.ConstraintLayout>

我调试了这个项目,它卡在了this:

public boolean performClick() {
        throw new RuntimeException("Stub!");
    }

主要LogCat错误:

07-28 11:17:08.595 1487-2742/? E/NotificationService: No Channel found for pkg=com.example.carlosroldan.merlinminerapp, channelId=null, opPkg=com.example.carlosroldan.merlinminerapp, callingUid=10084, userId=0, incomingUserId=0, notificationUid=10084, notification=Notification(channel=null pri=0 contentView=null vibrate=null sound=default defaults=0x1 flags=0x10 color=0x00000000 vis=PRIVATE)

这是 我的 LogCat 当 运行 并尝试执行方法时:

07-28 11:13:45.062 7553-7553/? I/zygote: Not late-enabling -Xcheck:jni (already on)
07-28 11:13:45.122 7553-7553/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
07-28 11:13:45.779 7553-7553/com.example.carlosroldan.merlinminerapp I/InstantRun: starting instant run server: is main process
07-28 11:13:46.576 7553-7598/com.example.carlosroldan.merlinminerapp D/OpenGLRenderer: HWUI GL Pipeline
07-28 11:13:46.695 7553-7598/com.example.carlosroldan.merlinminerapp I/OpenGLRenderer: Initialized EGL, version 1.4
07-28 11:13:46.695 7553-7598/com.example.carlosroldan.merlinminerapp D/OpenGLRenderer: Swap behavior 1
07-28 11:13:46.695 7553-7598/com.example.carlosroldan.merlinminerapp W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
07-28 11:13:46.695 7553-7598/com.example.carlosroldan.merlinminerapp D/OpenGLRenderer: Swap behavior 0
07-28 11:13:46.705 7553-7598/com.example.carlosroldan.merlinminerapp D/EGL_emulation: eglCreateContext: 0xa39fd3c0: maj 2 min 0 rcv 2
07-28 11:13:46.755 7553-7598/com.example.carlosroldan.merlinminerapp D/EGL_emulation: eglMakeCurrent: 0xa39fd3c0: ver 2 0 (tinfo 0xa4bf2d40)
07-28 11:13:46.803 7553-7598/com.example.carlosroldan.merlinminerapp W/android.hardware.graphics.mapper@2.0::Mapper: getService: found null hwbinder interface
07-28 11:13:46.847 7553-7598/com.example.carlosroldan.merlinminerapp I/vndksupport: sphal namespace is not configured for this process. Loading /system/lib/hw/gralloc.ranchu.so from the current namespace instead.
07-28 11:13:46.972 7553-7598/com.example.carlosroldan.merlinminerapp D/EGL_emulation: eglMakeCurrent: 0xa39fd3c0: ver 2 0 (tinfo 0xa4bf2d40)
07-28 11:13:48.891 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Do partial code cache collection, code=19KB, data=25KB
07-28 11:13:48.939 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: After code cache collection, code=19KB, data=26KB
07-28 11:13:48.939 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Increasing code cache capacity to 128KB
07-28 11:13:48.945 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Do partial code cache collection, code=19KB, data=43KB
07-28 11:13:48.946 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: After code cache collection, code=19KB, data=43KB
07-28 11:13:48.946 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Increasing code cache capacity to 256KB
07-28 11:13:48.947 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: JIT allocated 72KB for compiled code of void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
07-28 11:13:48.947 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
07-28 11:13:49.098 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Do full code cache collection, code=100KB, data=60KB
07-28 11:13:49.101 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: After code cache collection, code=97KB, data=45KB
07-28 11:13:49.891 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Do partial code cache collection, code=125KB, data=57KB
07-28 11:13:49.896 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: After code cache collection, code=121KB, data=56KB
07-28 11:13:49.896 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Increasing code cache capacity to 512KB
07-28 11:13:50.904 7553-7598/com.example.carlosroldan.merlinminerapp D/EGL_emulation: eglMakeCurrent: 0xa39fd3c0: ver 2 0 (tinfo 0xa4bf2d40)
07-28 11:13:56.008 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: Do full code cache collection, code=240KB, data=163KB
07-28 11:13:56.009 7553-7558/com.example.carlosroldan.merlinminerapp I/zygote: After code cache collection, code=162KB, data=113KB

谢谢

您的activity名称方法名称相同。重命名任何一个。 让我们像这样重命名方法,

showMyNotification 方法:

public void showMyNotification (View view){
        Intent intent = new Intent(this, notification.class);
        PendingIntent contentIntent = P

然后像这样从通知 (YourActivity) 调用,

notify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showMyNotification(view);
            }  
        });

正在显示通知!

尝试使用以下代码,它有效:

public void showNotification(Context context, String title, String message) {
        Intent notifyIntent = new Intent(context, notification.class);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivities(context, 0,
                new Intent[]{notifyIntent}, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(context)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
        notification.defaults |= Notification.DEFAULT_SOUND;
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, notification);
    }

来自Android 8 documentation:

Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.

因此,请按照文档中的上述 link 进行操作,了解如何 (1) 创建通知渠道以及 (2) 在显示通知时使用该渠道。

自 API 26 (Android 8.0) 您需要注册并设置 NotificationChannel 才能显示通知。

  1. 注册一个 NotificationChannel 例如在您的 MainActivity 中:

    // Register NotificationChannels needed for API 26+ to display notification messages
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager mNotificationManager = (NotificationManager)getSystemService(
                Context.NOTIFICATION_SERVICE);
        NotificationChannel infoChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO,
                getString(R.string.notification_channel_name_info), NotificationManager.IMPORTANCE_DEFAULT);
        infoChannel.setDescription(getString(R.string.notification_channel_description_info));
        infoChannel.enableLights(false);
        infoChannel.enableVibration(false);
        mNotificationManager.createNotificationChannel(infoChannel);
    }
    
  2. 为您的通知定义一个 NotificationChannel:

    Notification notification = new NotificationCompat.Builder(getContext())
            (...)
            .setChannelId(NOTIFICATION_CHANNEL_ID_INFO)
            .build();
    NotificationManager notificationManager = (NotificationManager)getContext().getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(CAPTURING_ONGOING_NOTIFICATION_ID, notification);