有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓上显示通知?

我有以下功能:

public void startApp(View v){
        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this);
        mBuilder.setSmallIcon(R.drawable.a);
        mBuilder.setContentTitle("arroz");
        mBuilder.setContentText("LOL ARROZ MASSA");
        mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }

当我点击一个按钮时,我调用这个函数

我希望在执行此操作时显示通知,因此我使用了此代码,但通知没有显示。我错过了什么

编辑:

public void startApp(View v){
        final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this);
        mBuilder.setSmallIcon(R.drawable.a);
        mBuilder.setContentTitle("arroz");
        mBuilder.setContentText("LOL ARROZ MASSA");
        mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
        mBuilder.setChannelId("1");
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }

共 (1) 个答案

  1. # 1 楼答案

    您没有设置通知通道,这可能是原因。尝试设置channelId并检查

     final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, "YOUR_CHANNEL_ID")
     mBuilder.setSmallIcon(R.drawable.a);
     mBuilder.setContentTitle("arroz");
     mBuilder.setContentText("LOL ARROZ MASSA");
     mBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
    

    通知

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    
    NotificationChannel notificationChannel = new NotificationChannel("YOUR_CHANNEL_ID", "CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
    mNotificationManager.createNotificationChannel(notificationChannel);
    mNotificationManager.notify(1, mBuilder.build())