如何创建通知

时间:2018-05-25 21:27:08

标签: java android push-notification android-notifications

我想在我的应用中创建一个简单的通知,但我不能。我搜索了这个,我在这里阅读了问题和谷歌文档,但我不知道为什么它不起作用。我观看了视频中的代码,但它也没有用。

private final String CHANNEL_ID = "personal_notifications";
private final int NOTIFICATION_ID = 001;

public void displayNotification(View view) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this,CHANNEL_ID);
        builder.setSmallIcon(R.drawable.power);
        builder.setContentTitle("Noti");
        builder.setContentText("mukodj mar");
        builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);

2 个答案:

答案 0 :(得分:0)

我在BroadcastReceiver中使用此代码:

public class NotificationReceiver extends BroadcastReceiver{


@Override
public void onReceive(Context context, Intent intent) {

NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent repeating_intent = new Intent(context, MainActivity.class);
    repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);

StringBuilder sb = new StringBuilder();
NotificationCompat.BigTextStyle contentStyle = new NotificationCompat.BigTextStyle();
        contentStyle.bigText((CharSequence) sb.toString()); 
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) // channel ID missing
                    .setContentIntent(pendingIntent)
                    .setSmallIcon(R.drawable.icon)
                    .setStyle(contentStyle)
                    .setContentTitle("Title")
                    .setContentText(sb.toString())
                    .setAutoCancel(true);
            notificationManager.notify(100, builder.build());
}

我想你忘记了最后一行:

notificationManager.notify(100, builder.build());

答案 1 :(得分:0)

我明白了。我做了通知频道,现在正在工作,无论如何,谢谢你们!