Определите addAction click для уведомлений Android
Я пытаюсь использовать новый интерфейс уведомлений. Я добавил 3 кнопки к уведомлениям и хочу сохранить что-то в своей базе данных после нажатия на каждую из них.
Само уведомление работает хорошо и отображается при вызове, я просто не знаю, как фиксировать каждое из трех разных нажатий кнопок.
Я использую BroadcastReceiver
ловить щелчки, но я не знаю, как определить, какая кнопка была нажата.
Это код AddAction
(Я исключил остальную часть уведомления, так как она работает хорошо) -
//Yes intent
Intent yesReceive = new Intent();
yesReceive.setAction(CUSTOM_INTENT);
Bundle yesBundle = new Bundle();
yesBundle.putInt("userAnswer", 1);//This is the value I want to pass
yesReceive.putExtras(yesBundle);
PendingIntent pendingIntentYes = PendingIntent.getBroadcast(this, 12345, yesReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.calendar_v, "Yes", pendingIntentYes);
//Maybe intent
Intent maybeReceive = new Intent();
maybeReceive.setAction(CUSTOM_INTENT);
Bundle maybeBundle = new Bundle();
maybeBundle.putInt("userAnswer", 3);//This is the value I want to pass
maybeReceive.putExtras(maybeBundle);
PendingIntent pendingIntentMaybe = PendingIntent.getBroadcast(this, 12345, maybeReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.calendar_question, "Partly", pendingIntentMaybe);
//No intent
Intent noReceive = new Intent();
noReceive.setAction(CUSTOM_INTENT);
Bundle noBundle = new Bundle();
noBundle.putInt("userAnswer", 2);//This is the value I want to pass
noReceive.putExtras(noBundle);
PendingIntent pendingIntentNo = PendingIntent.getBroadcast(this, 12345, noReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.calendar_x, "No", pendingIntentNo);
Это код BroadcastReceiver
-
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("shuffTest","I Arrived!!!!");
//Toast.makeText(context, "Alarm worked!!", Toast.LENGTH_LONG).show();
Bundle answerBundle = intent.getExtras();
int userAnswer = answerBundle.getInt("userAnswer");
if(userAnswer == 1)
{
Log.v("shuffTest","Pressed YES");
}
else if(userAnswer == 2)
{
Log.v("shuffTest","Pressed NO");
}
else if(userAnswer == 3)
{
Log.v("shuffTest","Pressed MAYBE");
}
}
}
Я зарегистрировал BroadcastReceiver
в манифесте. Кроме того, я хочу отметить, что BroadcastReceiver
вызывается, когда я нажимаю одну из кнопок в уведомлении, но намерение всегда включает дополнительно "2".
Это уведомление само по себе -
5 ответов
Это потому, что вы используете FLAG_UPDATE_CURRENT с Intents, которые имеют то же действие
Из документов:
если описанный PendingIntent уже существует, сохраните его, но замените его дополнительные данные тем, что находится в этом новом намерении.
Когда вы указываете pendingIntentMaybe
а также pendingIntentNo
система использует PendingIntent
предназначен для pendingIntentYes
, но это перезаписывает дополнения. Таким образом, все три переменные ссылаются на один и тот же объект, а последние указанные дополнительные значения были для pendingIntentNo
,
Вы должны указать альтернативное действие для каждого Intent
, Вы все еще можете иметь один BroadcastReceiver
и просто перехватите все три действия. Это будет менее смущать семантически, а также:)
Ваш Уведомительный постер:
//Yes intent
Intent yesReceive = new Intent();
yesReceive.setAction(YES_ACTION);
PendingIntent pendingIntentYes = PendingIntent.getBroadcast(this, 12345, yesReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.calendar_v, "Yes", pendingIntentYes);
//Maybe intent
Intent maybeReceive = new Intent();
maybeReceive.setAction(MAYBE_ACTION);
PendingIntent pendingIntentMaybe = PendingIntent.getBroadcast(this, 12345, maybeReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.calendar_question, "Partly", pendingIntentMaybe);
//No intent
Intent noReceive = new Intent();
noReceive.setAction(NO_ACTION);
PendingIntent pendingIntentNo = PendingIntent.getBroadcast(this, 12345, noReceive, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.addAction(R.drawable.calendar_x, "No", pendingIntentNo);
Ваш получатель:
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(YES_ACTION.equals(action)) {
Log.v("shuffTest","Pressed YES");
} else if(MAYBE_ACTION.equals(action)) {
Log.v("shuffTest","Pressed NO");
} else if(NO_ACTION.equals(action)) {
Log.v("shuffTest","Pressed MAYBE");
}
}
ШАГ ЗА ШАГОМ
Шаг 1
public void noto2() // paste in activity
{
Notification.Builder notif;
NotificationManager nm;
notif = new Notification.Builder(getApplicationContext());
notif.setSmallIcon(R.drawable.back_dialog);
notif.setContentTitle("");
Uri path = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notif.setSound(path);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent yesReceive = new Intent();
yesReceive.setAction(AppConstant.YES_ACTION);
PendingIntent pendingIntentYes = PendingIntent.getBroadcast(this, 12345, yesReceive, PendingIntent.FLAG_UPDATE_CURRENT);
notif.addAction(R.drawable.back_dialog, "Yes", pendingIntentYes);
Intent yesReceive2 = new Intent();
yesReceive2.setAction(AppConstant.STOP_ACTION);
PendingIntent pendingIntentYes2 = PendingIntent.getBroadcast(this, 12345, yesReceive2, PendingIntent.FLAG_UPDATE_CURRENT);
notif.addAction(R.drawable.back_dialog, "No", pendingIntentYes2);
nm.notify(10, notif.getNotification());
}
Шаг 1.5
Я создал глобальный класс AppConstant
public class AppConstant
{
public static final String YES_ACTION = "YES_ACTION";
public static final String STOP_ACTION = "STOP_ACTION";
}
Шаг 2:
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (AppConstant.YES_ACTION.equals(action)) {
Toast.makeText(context, "YES CALLED", Toast.LENGTH_SHORT).show();
}
else if (AppConstant.STOP_ACTION.equals(action)) {
Toast.makeText(context, "STOP CALLED", Toast.LENGTH_SHORT).show();
}
}
}
Шаг 3
<receiver android:name=".NotificationReceiver">
<intent-filter>
<action android:name="YES_ACTION"/>
<action android:name="STOP_ACTION"/>
</intent-filter>
</receiver>
В моем случае это сработало у меня после добавления интент-фильтра
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="YES_ACTION"/>
<action android:name="NO_ACTION"/>
<action android:name="MAYBE_ACTION"/>
</intent-filter>
</receiver>
Вот YES_ACTION
должно быть yourfullpackagename.YES
лайк
private static final String YES_ACTION = "com.example.packagename.YES";
Точно так же вы можете использовать NO_ACTION
или же MAYBE_ACTION
В BroadcastReceiver вы должны использовать один и тот же YES_ACTION
как заявлено выше,
означает, что в классе BroadcastReceiver вы можете проверить наличие специальной трансляции, выполнив
public class NotificationReceiver extends BroadcastReceiver {
private static final String YES_ACTION = "com.example.packagename.YES";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if(YES_ACTION.equals(action)) {
Toast.makeText(context, "CALLED", Toast.LENGTH_SHORT).show();
}
}
}
примечание: вместо YES в строке YES_ACTION вы можете использовать и другое слово.
Это работа для меня
В вашем сервисе
private void sendNotification(String title, String body) {
Intent activityIntent = new Intent(this, HomeActivity.class);
activityIntent.setAction(Long.toString(System.currentTimeMillis()));
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, MyReceiver.class);
broadcastIntent.putExtra("quotes_copy", body);
PendingIntent actionIntent = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(NOTI_CHANNEL_ID, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mChannel.setShowBadge(false);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), NOTI_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setContentTitle(title)
.addAction(R.drawable.ic_logo, "Copy", actionIntent);
random = new Random();
NOTIFY_ID = random.nextInt(1000);
notificationManager.notify(NOTIFY_ID, builder.build());
}
В вашем классе приемника
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("quotes_copy");
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
Манифест
<receiver android:name=".Utils.MyReceiver"/>