Как отправить уведомление, не будучи онлайн? - PullRequest
0 голосов
/ 05 сентября 2018

Я создаю приложение, в которое пользователь помещает свои тесты и задания и все, что угодно. Я хочу знать, будет ли у моего приложения возможность выводить уведомление, например, за неделю и за день до теста?

Куда бы я ни заглянул, это повсюду.

Мне не нужны эти онлайн-уведомления, мне нужно приложение, чтобы отправлять их в автономном режиме. Возможно ли это?

Ответы [ 2 ]

0 голосов
/ 05 сентября 2018

Позвольте мне добавить обходной путь, который вы можете найти в других уроках за пределами ..

Расширение класса первого получателя BroadcastReceiver.

public class ReminderReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    int Request_Code = intent.getExtras().getInt("TIME",0);
    showNotification(context, MainActivity.class,
            "New Notification Alert..!", "scheduled for " + Request_Code + " seconds",Request_Code);
}

public void showNotification(Context context, Class<?> cls, String title, String content,int RequestCode)
{
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Intent notificationIntent = new Intent(context, cls);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(cls);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(
            RequestCode,PendingIntent.FLAG_ONE_SHOT);

    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = context.getString(R.string.channel_name);
        String description = context.getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("my_channel_01", name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        notificationManager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"my_channel_01");
    Notification notification = builder.setContentTitle(title)
            .setContentText(content).setAutoCancel(true)
       .setSound(alarmSound).setSmallIcon(R.drawable.ic_launcher_background)
            .setContentIntent(pendingIntent).build();


    notificationManager.notify(RequestCode,notification);
}

}

Объявление получателя в классе манифеста под тегом активности.

 <receiver android:enabled="true" android:name=".ReminderReceiver"/>

Затем установите напоминание диспетчеру тревог.

 public void setReminder(Context context,Class<?> cls,int sec)
{
    Intent intent = new Intent(context, cls);
        intent.putExtra("TIME",sec);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, sec, intent,
            PendingIntent.FLAG_ONE_SHOT);/* Find more about flags: https://developer.android.com/reference/android/app/PendingIntent */

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (sec * 1000), pendingIntent );//Add time in milliseconds. if you want to minute or hour mutiply by 60.. For ex: You want to trigger 5 Min then here you need to change 5 * 60 * 1000


}

Наконец, установите напоминание

setReminder(_Context,ReminderReceiver.class,time);

Обновлено

Для поддержки Android версии 8.0 и выше необходимо создать канал уведомлений. Узнайте больше здесь Управление каналами

Добавьте это в коде выше:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = context.getString(R.string.channel_name);
        String description = context.getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel("my_channel_01", name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        notificationManager.createNotificationChannel(channel);
    }

Обратите внимание, что для небольших иконок можно использовать рисование, но не использовать mipmap или адаптивные значки. Уведомление Android Oreo приводит к сбою пользовательского интерфейса системы

Для отмены запланированного уведомления

 public void cancelReminder(Context context,Class<?> cls)
{
    Intent intent1 = new Intent(context, cls);
    intent1.putExtra("TIME",time);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
            time, intent1, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if(pendingIntent != null) {
        am.cancel(pendingIntent);
    }
}

И используйте вышеуказанный метод для удаления

cancelReminder(_Context,ReminderReceiver.class);

Примечание: _Context должен быть таким же, как в setreminder() метод

0 голосов
/ 05 сентября 2018

Предлагаю прочитать Обзор уведомлений . Это поможет вам понять, как работает уведомление.

Чтобы построить уведомление, вот это Вот официальная документация для уведомления .

Читать и понимать. Тогда, когда вы столкнетесь с какой-либо проблемой, вы можете вернуться сюда для решения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...