将按钮添加到通知

Add Button to Notification

我的通知中需要一个按钮,但是我在网上找到的所有内容都不起作用。我需要它来取消播放将在指定时间响起的闹钟。任何人都可以 link 给我一些文章来阅读或告诉我应该使用什么代码才能让它工作。

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;

import com.example.oceansscheduler.MainActivity;
import com.example.oceansscheduler.R;


public class AlarmReceiver extends BroadcastReceiver {

    public void showNotification(Context context, String title, String message, Intent intent, int reqCode) {
        PendingIntent pendingIntent = PendingIntent.getActivity(context, reqCode, intent, PendingIntent.FLAG_ONE_SHOT);
        String CHANNEL_ID = "channel_name";// The id of the channel.
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_baseline_alarm_24)
                .setContentTitle(title)
                .setStyle(new NotificationCompat.BigTextStyle())
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Channel Name";// The user-visible name of the channel.
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
            notificationManager.createNotificationChannel(mChannel);
        }
        notificationManager.notify(reqCode, notificationBuilder.build()); // 0 is the request code, it should be unique id

        Log.d("showNotification", "showNotification: " + reqCode);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        SQLiteDatabase db = context.openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
        Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);

        Log.d("Count", String.valueOf(data.getCount()));
        if (data.getCount() > 0) {
            data.moveToFirst();
            String NameOfNotif = (data.getString(0));


            Toast.makeText(context, NameOfNotif, Toast.LENGTH_LONG).show();
            int reqCode = 1;
            Intent intentNotif = new Intent(context, MainActivity.class);
            showNotification(context, NameOfNotif, "Your Reminder is going off!", intentNotif, reqCode);

        }

    }
};

要在您的通知中添加按钮,您需要使用 addAction 功能。

它需要一个 Action object 需要:

  • 一个图标(奇怪),
  • 一个标题,
  • 一个PendingIntent

PendingItent 可以封装一个 Intent,它可以是一个 Service,它将被委派取消播放闹钟,或者是一个 Receiver,它将取消播放闹钟。

让我们继续使用接收器。我们可以创建一个 - CancelAlarmReceiver:

public class CancelAlarmReceiver extends BroadcastReceiver {

    public static String ACTION_CANCEL = "actionCancelAlarm";

    public CancelAlarmReceiver() {}

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_CANCEL)) {
            // Here You will cancel the alarm.
        }
    }
}

记得在Manifest中注册:

<receiver
    android:name=".CancelAlarmReceiver"
    android:enabled="true"
    android:exported="false">
    <intent-filter>
        <action android:name="com.your.app.CancelAlarmReceiver.ACTION_CANCEL" />
    </intent-filter>
</receiver>

稍后,当创建带有 builder 的通知时,您将必须提供 action 导致我们的 Receiver:

Intent cancelIntent = new Intent(this, CancelAlarmReceiver.class);
cancelIntent.setAction(ACTION_CANCEL);
PendingIntent cancelPendingIntent =
    PendingIntent.getBroadcast(this, NOTIFICATION_ID,
        cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);

builder.addAction(
    new Notification.Action(
        R.drawable.ic_alarm_cancel,
        getString(R.string.cancel_alarm), 
        cancelPendingIntent
    )
);

这应该确保您的通知会出现一个按钮,它会触发接收器并禁用警报(或您将要执行的任何操作)。