Определите addAction для уведомлений 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".
Это обозначение iteslf -
![notification]()
Ответы
Ответ 1
Это потому, что вы используете FLAG_UPDATE_CURRENT с намерениями, которые имеют одно и то же действие
Из документов:
если описанный 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");
}
}
Ответ 2
В моем случае это сработало для меня после добавления фильтра намерения
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="YES_ACTION"/>
<action android:name="NO_ACTION"/>
<action android:name="MAYBE_ACTION"/>
</intent-filter>
</receiver>
Ответ 3
Step_by_Step
Шаг 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
Я создал глобальный класс AppContant
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>
Ответ 4
здесь 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 вы также можете использовать другое слово.