Как показать диалог на клике уведомлений - PullRequest
0 голосов
/ 21 февраля 2019

Я создаю приложение для ежедневных уведомлений, где я позволяю пользователю устанавливать время.Для разработки этой функции я использую AlarmReceiver и BroadcastReceiver.

Я хочу показывать уведомление в диалоговом окне / окне предупреждений, когда пользователь нажимает на уведомление.

Может ли кто-нибудь помочь мне в достижении этой функции?

Ниже приведен код, где я устанавливаю сообщение уведомления.

public class AlarmReceiver extends BroadcastReceiver {

String TAG = "AlarmReceiver";

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    if (intent.getAction() != null && context != null) {
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            // Set the alarm here.
            Log.d(TAG, "onReceive: BOOT_COMPLETED");
            LocalData localData = new LocalData(context);
            NotificationScheduler.setReminder(context, AlarmReceiver.class, localData.get_hour(), localData.get_min());
            return;
        }
    }

    Log.d(TAG, "onReceive: ");

    //Trigger the notification
    NotificationScheduler.showNotification(context, MainActivity.class,
            "You have New Notification", "check it now?");

    }
}

Вывод должен выглядеть так после нажатия на уведомление ...

enter image description here

Ответы [ 3 ]

0 голосов
/ 21 февраля 2019
Intent notifyIntent = new Intent(context,YourActivityClassHere.class);
notifyIntent.setFlag(Intent.FLAG_ACTIVITY_NEW_TASK);
//UNIQUE_ID if you expect more than one notification to appear
PendingIntent intent = PendingIntent.getActivity(SimpleNotification.this, UNIQUE_ID, 
            notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

просто сделайте PendingIntent открытым для одного из ваших действий, и ваша активность будет полностью прозрачной, и просто откройте диалог.

РЕДАКТИРОВАТЬ: ЕСЛИ вы хотите открыть действиев уведомлении щелкните событие:

Предполагая, что уведомление является вашим объектом уведомления:

Intent notificationIntent = new Intent(this.getApplicationContext(), ActivityToStart.class);
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, notificationIntent, 0);
notif.contentIntent = contentIntent;

Для получения дополнительной информации Подробнее

0 голосов
/ 21 февраля 2019

Измените свой AlarmReceiver класс, как показано ниже

public class AlarmReceiver extends BroadcastReceiver {

String TAG = "AlarmReceiver";
public static String NotificationMsg="You have 5 unwatched videos", NotificationTitle = "Watch them now?";
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    if (intent.getAction() != null && context != null) {
        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            // Set the alarm here.
            Log.d(TAG, "onReceive: BOOT_COMPLETED");
            LocalData localData = new LocalData(context);
            NotificationScheduler.setReminder(context, AlarmReceiver.class, localData.get_hour(), localData.get_min());
            return;
        }
    }

    Log.d(TAG, "onReceive: ");

    //Trigger the notification
    NotificationScheduler.showNotification(context, NotificationActivity.class,
            NotificationTitle, NotificationMsg);

}
}

Затем создайте здесь новое действие, которое я создал NotificationActivity

public class NotificationActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ShowDialog();
}

@SuppressLint("ResourceAsColor")
public void ShowDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(NotificationActivity.this);
    builder.setMessage("\n" + NotificationMsg);
    TextView title = new TextView(NotificationActivity.this);
    title.setText(NotificationTitle);
    title.setBackgroundColor(Color.DKGRAY);
    title.setPadding(20, 20, 20, 20);
    title.setGravity(Gravity.CENTER);
    title.setTextColor(Color.WHITE);
    title.setTextSize(20);
    builder.setCustomTitle(title)
            .setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            //finishAffinity();
                        }
                    });
    builder.show();
}
}

Вывод здесь -

Выходные данные будут такими:

Надеюсь, это сработает ... Пожалуйста, не забудьте принять ответ и проголосовать ...

0 голосов
/ 21 февраля 2019

Код уведомления с ожидающим намерением, который открывает действие и для этого действия должен кодировать это всплывающее окно

Notification notif = new Notification(R.drawable.ic_launcher,"List of Contacts...", 
System.currentTimeMillis());
Intent notificationIntent = new Intent(context,AllContacts.class);
notificationIntent.putExtra("from", "notification") 
notificationIntent.putExtra("message", "yourmessage") 
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,            
notificationIntent, 0);
notif.setLatestEventInfo(context, from, message, contentIntent);
nm.notify(1, notif);

и в AllContacts.class в onCreate

if(getIntent.getStringExtras("from").equals("notification")){
   //popup show with message
}
...