предупреждение должно появляться на переднем экране в Android

В моей задаче я выполнил процесс проверки напоминаний. Если время напоминания сравняется с текущим временем, появится всплывающее окно. В этой Задаче всплывающее окно Приходит правильно.

Но если я объединю эту задачу с каким-то большим процессом, это означает, что задача напоминания будет подпрограммой основной программы. Всплывающее окно не появляется на других экранах. Если время соответствует текущему времени, предупреждение должно быть показано пользователю, когда пользователь использует любой экран в этой программе.

if (LDbTime <= LSysTime) {
                                    rem_id = c.getString(c.getColumnIndex("reminder_id"));
                                    remName = c.getString(c.getColumnIndex("rname"));
                                    mediaPlayer.start();
                                    handler.post(new Runnable(){
                                    public void run() {
                                        alert.setTitle("Alert :"+remName);
                                        alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                mediaPlayer.pause();
                                            }
                                        });
                                        alert.show();
                                        db1.execSQL("UPDATE RemainAlarmS SET expired ='TRUE' WHERE reminder_id = " + rem_id );
                                            }
                                        });
                                    Thread.sleep(5000);
                                }

В этом предупреждающем сообщении необходимо вывести на передний экран во время пробуждения напоминания.

Пожалуйста, помогите мне найти решение ..

Заранее спасибо.


person gowri    schedule 24.09.2012    source источник


Ответы (3)


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

Intent i = new Intent("android.intent.action.DA");
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
GregorianCalendar calendar = new GregorianCalendar(y,m,d, hr, mi);
long alarm_time = calendar.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP  , alarm_time , operation);

А «android.intent.action.DA» обозначает активность класса DisplayNotification.java.

public class DisplayNotification extends Activity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int notifID = getIntent().getExtras().getInt("NotifID");
    Intent i = new Intent("android.intent.action.AD");
    i.putExtra("NotifID", notifID);  
    PendingIntent detailsIntent =PendingIntent.getActivity(this, 0, i, 0);
    NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Notification notif = new Notification(R.drawable.ic_launcher,"Time's up!",System.currentTimeMillis());
    CharSequence from = "AlarmManager - Time's up!";
    CharSequence message = "This is your alert, courtesy of the AlarmManager";        
    notif.setLatestEventInfo(this, from, message, detailsIntent);
    notif.vibrate = new long[] { 100, 250, 100, 500};        
    nm.notify(notifID, notif);
    finish();
}
}

А «android.intent.action.AD» обозначает класс AlarmDetails.java.

public class AlarmDetails extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alarmdetails);

    NotificationManager nm = (NotificationManager) 
            getSystemService(NOTIFICATION_SERVICE);
        //---cancel the notification---
        nm.cancel(getIntent().getExtras().getInt("NotifID")); 
}

}

Я надеюсь, что это поможет вам!..

person MGR    schedule 05.10.2012

Если вы пытаетесь спросить, как отобразить диалог, когда ваша деятельность не является сфокусированной активностью на телефоне пользователя, попробуйте вместо этого использовать уведомления. Открытие диалогового окна в другом приложении прерывает пользователя, когда он может делать что-то еще. Из руководства по пользовательскому интерфейсу Android:

Use the notification system — don't use dialog boxes in place of notifications

If your background service needs to notify a user, use the standard notification system — 
don't use a dialog or toast to notify them. A dialog or toast would immediately 
take focus    and interrupt the user, taking focus away from what they were doing: 
the user could be in the middle of typing text the moment the dialog appears 
and could accidentally act on the dialog. 
Users are used to dealing with notifications and 
can pull down the notification shade at their convenience to respond to your message.

Руководство по созданию уведомлений находится здесь: http://developer.android.com/guide/topics/ui/notifiers/notifications.html

person SunnySonic    schedule 25.09.2012

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

person SunnySonic    schedule 24.09.2012
comment
Это нужно на текущем рабочем или переднем экране. - person gowri; 25.09.2012