Как настроить канал уведомлений? - PullRequest
0 голосов
/ 04 ноября 2019

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

Это в настоящее время включено в MainActivity.java:

package com.example.reminder;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    TimePicker timePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        timePicker=(TimePicker) findViewById(R.id.timePicker);
        timePicker.setIs24HourView(true);

        findViewById(R.id.buttonSetAlarm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Calendar calendar = Calendar.getInstance();

                if(Build.VERSION.SDK_INT > 23) {
                calendar.set(
                        calendar.get(Calendar.YEAR),
                        calendar.get(calendar.MONTH),
                        calendar.get(calendar.DAY_OF_MONTH),
                        timePicker.getHour(),
                        timePicker.getMinute(),
                        0
                );
            }else {
                    calendar.set(
                            calendar.get(Calendar.YEAR),
                            calendar.get(calendar.MONTH),
                            calendar.get(calendar.DAY_OF_MONTH),
                            timePicker.getCurrentHour(),
                            timePicker.getCurrentMinute(),
                            0
                    );
                }

                setAlarm(calendar.getTimeInMillis());

            }
        });
    }

    private void setAlarm(long timeInMillis) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent intent  = new Intent(this, MyAlarm.class);

        PendingIntent pendingIntent= PendingIntent.getBroadcast(this, 0, intent, 0);

        alarmManager.setRepeating(AlarmManager.RTC, timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent);

        Toast.makeText(this, "Emlekezteto beallitva", Toast.LENGTH_SHORT).show();
    }

Как мне написать, чтобы отправить уведомление с предопределенным текстоми использовать звук?

В настоящее время я написал отдельный класс (MyAlarm), чтобы использовать рингтон системы. MyAlarm.java:

package com.example.reminder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.provider.Settings;

public class MyAlarm extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        MediaPlayer mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
                mediaPlayer.start();
    }
}

Может ли кто-нибудь мне помочь?

Заранее спасибо.

Ответы [ 2 ]

0 голосов
/ 05 ноября 2019

Пройдите через эту Среднюю статью , вы можете иметь лучшее представление о каналах уведомлений.

0 голосов
/ 04 ноября 2019

Я использовал эту функцию в своем проекте, и она отлично работает. надеюсь, это поможет вам

private void notificationDialog() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "notification01";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
        // Configure the notification channel.
        notificationChannel.setDescription("Description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setTicker("some text")
            //.setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("ContentTitle")
            .setContentText("ContentText")
            .setContentInfo("Information");
    notificationManager.notify(1, notificationBuilder.build());
}

и в вашем проекте для отправки уведомлений измените свой класс MyAlarm следующим образом

        package com.example.reminder;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.provider.Settings;

    public class MyAlarm extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            notificationDialog();
        }
    private void notificationDialog() {
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "notification01";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
        // Configure the notification channel.
        notificationChannel.setDescription("Description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setTicker("some text")
            //.setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("ContentTitle")
            .setContentText("ContentText")
            .setContentInfo("Information");
    notificationManager.notify(1, notificationBuilder.build());
}
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...