安卓通知在按钮按下时未触发(Java)

huangapple 未分类评论49阅读模式
英文:

Android notification isn't triggered when a button is pressed (Java)

问题

以下是您提供的Java和XML代码的翻译部分:

XML代码中的通知按钮部分:

<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" />

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() {
        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());
    }
}
英文:

I'm working on an app which consists of a note taking portion and a button that the user can press to send a random motivational quote in the form of a notification. The note taking part of the app is working fine, but I'm struggling with getting the notification button to work. Whenever a user currently presses the button, nothing occurs. What might be the issue here? I have attached my Java and XML code.

I should add that I think the issue may be due to me implementing the notification button in a different class from Main Activity, but Im not sure. I did this because I had to make my button in a separate layout from activity_main because the List View wouldn't allow for it.

XML Code for Notification Button:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:id=&quot;@+id/relativeLayout&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:background=&quot;@drawable/gradient_background&quot;
    tools:context=&quot;.Home&quot;&gt;


    &lt;Button
        android:id=&quot;@+id/enterButton&quot;
        style=&quot;@style/Widget.AppCompat.Button&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:inputType=&quot;textCapSentences&quot;
        android:text=&quot;@string/start_writing&quot;
        android:textSize=&quot;12sp&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;

    &lt;Button
        android:id=&quot;@+id/notification_motivation_button&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:text=&quot;@string/need_motivation&quot;
        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
        app:layout_constraintEnd_toEndOf=&quot;parent&quot;
        app:layout_constraintHorizontal_bias=&quot;0.498&quot;
        app:layout_constraintStart_toStartOf=&quot;parent&quot;
        app:layout_constraintTop_toBottomOf=&quot;@+id/enterButton&quot;
        app:layout_constraintVertical_bias=&quot;0.071&quot; /&gt;


&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

Java Code for Notification Button:

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 = &quot;ID&quot;;
    private static final String CHANNEL_NAME = &quot;channelName&quot;;
    private static final String CHANNEL_DESC = &quot;Motivation Button Notification&quot;;

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

        if (Build.VERSION.SDK_INT &gt;= 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 = {&quot;Simplicity is the ultimate sophistication&quot;,
            &quot;Never regret anything that made you smile&quot;,
            &quot;Every moment is a fresh beginning&quot;,
            &quot;Prove them wrong&quot;,
            &quot;He who is brave is free&quot;,
            &quot;No guts, no story&quot;,
            &quot;Leave no stone unturned&quot;,
            &quot;Do it with passion or not at all&quot;,
            &quot;Every noble work is at first impossible&quot;,
            &quot;The wisest mind has something yet to learn&quot;,
            &quot;If you&#39;re going through hell, keep going&quot;,
            &quot;Persistence guarantees that results are inevitable&quot;,
            &quot;It is better to live one day as a lion, than one thousand days as a lamb&quot;,
            &quot;You can do it!&quot;,
            &quot;You make mistakes. Mistakes don&#39;t make you&quot;
    };
    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(&quot;A little motivation!&quot;)
                .setContentText(randomQuote(quoteArray))
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat nManagerCompat = NotificationManagerCompat.from(this);
        nManagerCompat.notify(1, notificationBuilder.build());
    }
}

huangapple
  • 本文由 发表于 2020年5月5日 11:00:05
  • 转载请务必保留本文链接:https://java.coder-hub.com/61604996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定