Android Studio - Уведомление из базы данных SQLite - PullRequest
0 голосов
/ 01 марта 2019

У меня есть приложение, которое сохраняет события в базе данных как plan_title, plan_date и plan_time.Я должен генерировать уведомления или тревоги в зависимости от даты и времени, сохраненных в базе данных SQLite.Вот что я пытался сделать:

public class AlarmSet extends AppCompatActivity {
    Databasehelper databasehelper;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SQLiteDatabase db = databasehelper.getReadableDatabase();
        //To fetch the event from the database
        Cursor cursor = db.query(Databasehelper.TABLE_NAME,
                new String[]{Databasehelper.COL_1, Databasehelper.COL_4, Databasehelper.COL_3, Databasehelper.COL_2},
                null, null, null, null, null);

        cursor.moveToFirst();

        while (!cursor.isAfterLast()) { // Loop until all vales have been seen

            String time = cursor.getString(1);
            String[] Timesplit = time.split(":"); //Split  String Value stored in db
            String hour = Timesplit[0]; // hour
            String minute = Timesplit[1]; // minute
            String Date = cursor.getString(2);
            String[] Datesplit = Date.split("-"); //Split  String Value stored in db
            String day = Datesplit[0]; // day
            String month = Datesplit[1]; // month
            String year = Datesplit[2]; // year
            String title = cursor.getString(3);
            int hr = Integer.parseInt(hour);
            int min = Integer.parseInt(minute);
            int d = Integer.parseInt(day);
            int m = Integer.parseInt(month);
            int y = Integer.parseInt(year);

            final int id=(int)System.currentTimeMillis();
            //Assigning the event in the alarm
            Calendar calendar1 = Calendar.getInstance();
            calendar1.set(Calendar.YEAR,y);
            calendar1.set(Calendar.MONTH,m);
            calendar1.set(Calendar.DAY_OF_MONTH,d);
            calendar1.set(Calendar.HOUR_OF_DAY, hr);
            calendar1.set(Calendar.MINUTE, min);
            calendar1.set(Calendar.MILLISECOND, 0);
            if (calendar1.before(Calendar.getInstance())) {
                calendar1.add(Calendar.DATE, 1);
            }
            Intent intent = new Intent(AlarmSet.this, Alarm.class);

            intent.putExtra("title",title);
            intent.putExtra("id",   id);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            final AlarmManager alarm1 = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarm1.setExact(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), pendingIntent);
            Toast.makeText(AlarmSet.this, "alarms",Toast.LENGTH_SHORT).show();




            cursor.moveToNext();
        }

    }
    }

И это приемник.

public class Alarm extends BroadcastReceiver {


    @Override
    public void onReceive(Context context, Intent intent) {
        int id= Integer.valueOf(intent.getStringExtra("id"));
        String title=intent.getStringExtra("title");


        NotificationManager notificationManager=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
        Intent intent1=new Intent(context, AlarmSet.class);
        intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent=PendingIntent.getActivity(context, id,intent1, PendingIntent.FLAG_ONE_SHOT);;
        NotificationCompat.Builder builder2=new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setContentTitle(title)
                .setVibrate(new long[] { 1000, 1000})
                .setAutoCancel(true);
        notificationManager.notify(id,builder2.build());
    }


}

Уведомление не генерируется.Я относительно новичок в Android Studio, поэтому буду очень признателен за любую помощь или советы

1 Ответ

0 голосов
/ 01 марта 2019

устройств, работающих с Android 8.0 (уровень API 26), имеют незначительно отличающиеся уведомления, показывающие реализацию, и могут не отображать уведомления, если реализованы неправильно, пожалуйста, прочитайте и следуйте официальному руководству Уведомления * Пример работы с 1002 *

все устройства:

 public void showNotification() {
    NotificationManager notificationManager =
            (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
    if (notificationManager != null) {
        Intent intent = new Intent(getContext(), MainActivity.class);
        boolean isSound = getCloudMessage().isWithSound();
        if (isSound) {
            getCloudMessage().setSoundMute();
        }
        intent.putExtra(KEY_CLOUD_MESSAGE, getCloudMessage());
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), REQUEST_CODE,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID, getTitle(), importance);
            channel.setDescription(getBodyMessage());
            channel.enableVibration(true);
            notificationManager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(getContext(), CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(getContext());
        }

        builder.setContentTitle(getTitle())
                .setContentTitle(getTitle())
                .setContentText(getBodyMessage())
                .setSmallIcon(R.drawable.ic_notification)
                .setSmallIcon(R.drawable.ic_notification)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getContext().getResources(), R.mipmap.ic_launcher))
                .setBadgeIconType(R.mipmap.ic_launcher)
                .setColor(ContextCompat.getColor(getContext(),
                        R.color.primary_color))
                .setStyle(new NotificationCompat
                        .BigTextStyle()
                        .setBigContentTitle(getTitle())
                        .bigText(getBodyMessage()))
                .setAutoCancel(true)
                .setContentIntent(pendingIntent);
        if (isSound) {
            builder.setSound(sound);
        }

        Notification notification = builder.build();
        notificationManager.notify(NOTIFICATION_ID, notification);
    }
}
...