通知无法在 android studio 上工作(API 27,ANDROID 8.1.0)

notify not working on android studio ( API 27, ANDROID 8.1.0)

我正在尝试修复我的代码,我想在我的应用程序上添加通知,但我不知道为什么它不起作用。 这是 notificaService.java:

public class notificaService extends BroadcastReceiver {
    DatabaseHelper db;
    String CHANNEL_ID = "150";
    String id;
    String KEY_TEXT_REPLY = "key_text_reply";
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context context, Intent intent) {

        db = new DatabaseHelper (context);
        String temperatura1, glicemia1, battito1, peso1;
        temperatura1 = "temperatura";
        glicemia1 = "glicemia";
        battito1 = "battito";
        peso1 = "peso";


        //verify whether if user as inserted any record today
        long reports = db.countRows(temperatura1) + db.countRows(glicemia1)
                + db.countRows(peso1) + db.countRows(battito1);

        String haji1 = String.valueOf (reports);
        Log.i("LALALALALALSERVICE",  haji1);

        //builder for the notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);

        //as the user clicks on the intent, open MainActivity aka ReportFragment
        Intent myIntent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                context, 0, myIntent, PendingIntent.FLAG_ONE_SHOT
        );


        Intent intent1 = new Intent(context, MainActivity.class);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context,0,intent1,PendingIntent.FLAG_ONE_SHOT);

        //set notification features
        builder.setContentTitle("Daily Reminder")
                .setContentText("Remember to fill today's report")
                .setSmallIcon(R.drawable.alarmclock)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setColor(Color.BLUE)
                .setAutoCancel(true)
                //.setChannelId(id)
                //.addAction(R.drawable.logout_icon, "SET TIME", resultPendingIntent)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        //if no reports are recorded, trigger notification
        if(reports == 0)
            notificationManager.notify(1, builder.build());

    }



}

这里是Notifica.java,我在这里设置通知时间:

public class Notifica extends AppCompatActivity  {
    private EditText edt_orario;
    private Button btnInvio, btn_setOrario;
    DatabaseHelper db = new DatabaseHelper(this);
    Calendar calendar = Calendar.getInstance ( );
long reports;

    String channel = "100";

    private final boolean[] vibration = new boolean[1];
    private NotificationManager notificationManager;
    String KEY_TEXT_REPLY = "key_text_reply";
    String CHANNEL_ID = "200";

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_notifica);
            edt_orario=findViewById(R.id.edt_orario);
            btn_setOrario=findViewById(R.id.btn_setOrario);
        btnInvio=findViewById(R.id.btnInvio);
        db = new DatabaseHelper (this);
        String temperatura1, glicemia1, battito1, peso1;
        temperatura1 = "temperatura";
        glicemia1 = "glicemia";
        battito1 = "battito";
        peso1 = "peso";
         reports = db.countRows(temperatura1) + db.countRows(glicemia1)
                + db.countRows(peso1) + db.countRows(battito1);

        String haji1 = String.valueOf (reports);
        Log.i("LALALALALAL",  haji1);

        //instatiate the notification manager



        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        createNotificationChannel(CHANNEL_ID);



        //create the channel through which the notification should communicate.
        /*dataSpe = oggi.format (new Date());
          cursor = db.viewDataOggi("peso",dataSpe);
          cursor1 = db.viewDataOggi("temperatura",dataSpe);
           cursor2 = db.viewDataOggi("glicemia", dataSpe);
       cursor3 = db.viewDataOggi("battito", dataSpe);
        Log.i("kkkkkkkkkkkk", " "+ cursor2.getCount());*/

        //bottone per impostare l'orario in cui arriverà la notifica
            btn_setOrario.setOnClickListener(new View.OnClickListener() {
                Calendar c = Calendar.getInstance();
                int hour = c.get(Calendar.HOUR_OF_DAY);
                int min = c.get(Calendar.MINUTE);


                @Override
                public void onClick(View v) {
                    TimePickerDialog timePickerDialog = new TimePickerDialog(Notifica.this, new TimePickerDialog.OnTimeSetListener() {

                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {



                                String realMinute, realHour;
                                //controllo per inserire l'orario in formato leggibile
                                if (minute < 10) {
                                    realMinute = "0" + minute;
                                } else {
                                    realMinute = String.valueOf (minute);
                                }
                                if (hourOfDay < 10) {
                                    realHour = "0" + hourOfDay;
                                } else {
                                    realHour = String.valueOf (hourOfDay);
                                }
                                edt_orario.setText (realHour + ":" + realMinute);
                            }

                    }, hour, min, true);
                    timePickerDialog.show();
                }
            });
            btnInvio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //se non c'è nessun report inserito per la data di oggi, allora ...
                //if ((cursor.getCount() == 0) || (cursor1.getCount() == 0) || (cursor2.getCount() == 0) || (cursor3.getCount() == 0)) {
                //classe per gestire lo scatto della notifica alla stessa ora tutti i giorni
                //if (reports == 0) {
                AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                    Intent intent;
                    PendingIntent pendingIntent;
                    //impostazione dell'orario in cui scatterà la notifica
                    int hour, min;
                    hour = Integer.parseInt (edt_orario.getText ( ).toString ( ).substring (0, 2));
                    min = Integer.parseInt (edt_orario.getText ( ).toString ( ).substring (3));
                    Calendar c = Calendar.getInstance ( );
                    c.set (Calendar.HOUR_OF_DAY, hour);
                    c.set (Calendar.MINUTE, min);
                    c.set (Calendar.SECOND, 1);
                    //passo la gestione della notifica al NotificationService tramite l'intent
                    intent = new Intent (Notifica.this, notificaService.class);

                    //gestisco lo scatto della notifica tramite broadcast
                    pendingIntent = PendingIntent.getBroadcast (Notifica.this, 0, intent, 0);
                    alarmManager.setInexactRepeating (alarmManager.RTC_WAKEUP, c.getTimeInMillis ( ), AlarmManager.INTERVAL_DAY, pendingIntent);

                    Toast.makeText (getApplicationContext ( ), "Impostazioni salvate", Toast.LENGTH_SHORT).show ( );
                }
          //  }
        }

            );

        }




    /*@Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        calendar.set(Calendar.MINUTE, minute);
    }

*/

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel (String id){
        int importanza = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel(id, "info", importanza);
        notificationChannel.setDescription("info");
        notificationChannel.enableVibration(true);
        notificationChannel.setLightColor(Color.RED);
        notificationManager.createNotificationChannel(notificationChannel);
    }

    }

在我的 Db 中,一切正常,因为我已经看到了,感谢 Log。所以我不知道我在哪里犯了错误。 感谢您的帮助!

以下代码将创建一个通知,您可以设置标题和 body :

public void showNotification(Context context, String title, String body, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        int notificationId = 1;
        String channelId = "channel-01";
        String channelName = "Channel Name";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
                .setContentTitle(title)
                .setContentText(body);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );
        mBuilder.setContentIntent(resultPendingIntent);

        notificationManager.notify(notificationId, mBuilder.build());
    }

要显示通知,您需要做的就是调用函数:

showNotification(getApplicationContext(),"This is the title", "This is the body", getIntent());