java - 创建通知android未在手机中显示

标签 java android service notifications

目前正在开发 Android 应用程序,我的通知未显示在手机中。

我正在将我的物理手机连接到 android studio,并且我看到发送通知的方法已被调用,但没有在手机中显示任何通知。

private void createNotification(){
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_chat)
                .setContentTitle("New match!!!")
                .setContentText("You got a new match!!!")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        mNotificationManager.notify(001,builder.build());
    }

之前我初始化mNotoficationManager如下:

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

知道为什么当我收到该方法调用时我的手机不显示通知吗?是从我创建的用于更改数据库中的事件的服务中调用的。

最佳答案

发现此代码适用于 android 8 及以上版本。

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "Tortuga");
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);
        mBuilder.setContentTitle("New match on WeRoom")
                .setContentText("You got a new match, you can now chat with someone more!!!")
                .setAutoCancel(false)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI);


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

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            String NOTIFICATION_CHANNEL_ID = "1001";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            assert mNotificationManager != null;
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            mNotificationManager.createNotificationChannel(notificationChannel);
        }
        assert mNotificationManager != null;
        mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

关于java - 创建通知android未在手机中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56030818/

相关文章:

java - 与SVN服务器交互的API?

用于 UI Windows 应用程序的 Java

java - 如何在 Grails 中迭代上传的文件

android - 如何在android中获取应用程序的名称?

android - 使用 Butterknife 注入(inject) View 数组

android - 如何在 Maven 中正确设置 actionbarsherlock 依赖项?

android - 如果我尝试启动服务,为什么会收到 InstantiationException?

java - 关于服务、Daos 及其之间 - 初学者的困境

android - 使下载器在后台下载文件并更新进度条

java - 如何对可以为空的列使用 hibernate 延迟加载