Я работаю над приложением, которое состоит из части для создания заметок и кнопки, которую пользователь может нажать, чтобы отправить случайную мотивационную цитату в форме уведомления. Заметки в приложении работают нормально, но мне не удается заставить работать кнопку уведомления. Каждый раз, когда пользователь в данный момент нажимает кнопку, ничего не происходит. В чем может быть проблема? Я прикрепил свои коды Java и XML.
Я должен добавить, что, по моему мнению, проблема может быть связана с тем, что я реализовал кнопку уведомления в классе, отличном от класса Main Activity, но я не уверен. Я сделал это, потому что мне пришлось сделать свою кнопку в отдельном макете от activity_main, потому что представление списка не допускало бы этого.
XML Код для кнопки уведомления:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
tools:context=".Home">
<Button
android:id="@+id/enterButton"
style="@style/Widget.AppCompat.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textCapSentences"
android:text="@string/start_writing"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/notification_motivation_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/need_motivation"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/enterButton"
app:layout_constraintVertical_bias="0.071" />
</androidx.constraintlayout.widget.ConstraintLayout>
Java Код для кнопки уведомления:
package com.example.notesapplication;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.util.Random;
public class NotificationButton extends AppCompatActivity {
private static final String CHANNEL_ID = "ID";
private static final String CHANNEL_NAME = "channelName";
private static final String CHANNEL_DESC = "Motivation Button Notification";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription(CHANNEL_DESC);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
findViewById(R.id.notification_motivation_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addNotifications();
}
});
}
private String[] quoteArray = {"Simplicity is the ultimate sophistication",
"Never regret anything that made you smile",
"Every moment is a fresh beginning",
"Prove them wrong",
"He who is brave is free",
"No guts, no story",
"Leave no stone unturned",
"Do it with passion or not at all",
"Every noble work is at first impossible",
"The wisest mind has something yet to learn",
"If you're going through hell, keep going",
"Persistence guarantees that results are inevitable",
"It is better to live one day as a lion, than one thousand days as a lamb",
"You can do it!",
"You make mistakes. Mistakes don't make you"
};
public static String randomQuote(String[] inputArray) {
Random r = new Random();
int randomValue = r.nextInt(inputArray.length - 1);
return inputArray[randomValue];
}
private void addNotifications() {
// Notification builder
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("A little motivation!")
.setContentText(randomQuote(quoteArray))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat nManagerCompat = NotificationManagerCompat.from(this);
nManagerCompat.notify(1, notificationBuilder.build());
}
}