有 Java 编程相关的问题?

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

Android中的java通知代码

我试图在一个按钮中编写一个简单的通知代码,当我按下按钮时,它会创建一个通知,但当我按下按钮时,通知不会出现。这是我正在使用的代码

int notificationId = 001;
        // Build intent for notification content
        Intent viewIntent = new Intent(SessionsActivity.this, MainActivity.class);
        PendingIntent viewPendingIntent =
                PendingIntent.getActivity(SessionsActivity.this, 0, viewIntent, 0);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(SessionsActivity.this)
                        .setContentTitle("hii")
                        .setContentText("hii2")
                        .setContentIntent(viewPendingIntent);
        // Get an instance of the NotificationManager service
        NotificationManagerCompat notificationManager =NotificationManagerCompat.from(SessionsActivity.this);
        // Build the notification and issues it with notification manager.
        notificationManager.notify(notificationId, notificationBuilder.build());

共 (1) 个答案

  1. # 1 楼答案

    Intent viewIntent = new Intent(SessionsActivity.this, MainActivity.class);
    
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, viewIntent , PendingIntent.FLAG_UPDATE_CURRENT);
    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    
    
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    notificationBuilder.setStyle(inboxStyle);
    inboxStyle.setBigContentTitle("sdjshfjnds");
    inboxStyle.addLine("sdjjsdfn");
    notificationBuilder.setStyle(inboxStyle);
    
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    int NOTIFICATION_ID = 100;
    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());