Проблема с уведомлением Android - PullRequest
0 голосов
/ 21 марта 2011

Я создал Alarm с помощью AlarmManager.

Intent intent = new Intent(MyApp.this,NotificationMessage.class);
PendingIntent sender = PendingIntent.getBroadcast(MyApp.this, 0, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, nextAlarmTime,sender);

Вот класс NotificationMessage.

public class NotificationMessage extends BroadcastReceiver {
    // Display an alert that we've received a message.
    // @Override
    public void onReceive(Context context, Intent intent) {


        Intent myIntent = new Intent();
        myIntent.setClass(context, ScheduleAlert.class);
        myIntent.setAction(ScheduleAlert.class.getName());
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        context.startActivity(myIntent);
    }
}

Вызывает Intent для создания Notification.Чтобы получить текст уведомления, я должен получить доступ к базе данных.Я хочу создать звук и вибрацию для уведомления.А также показать значок уведомления в верхней панели, но нет просмотра.Но он показывает черный экран во время уведомления.Как это решить?

public class ScheduleAlert extends Activity {

    private String notificationAlart;

    // ************* Notification and AlarmManager ************//

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


                // get contentText from the database


        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                final Notification notifyDetails = new Notification(
                        R.drawable.icon, "MyApp", nextAlarmTime);

                Context context = getApplicationContext();
                CharSequence contentTitle = "MyApp";
                CharSequence contentText = notificationAlart;

                Intent notifyIntent = new Intent(context, MyApp.class);

                PendingIntent pendingIntent = PendingIntent.getActivity(
                        ScheduleAlert.this, 0, notifyIntent,
                        android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
                notifyDetails.setLatestEventInfo(context, contentTitle,
                        contentText, pendingIntent);


                notifyDetails.flags = Notification.FLAG_AUTO_CANCEL;
                notifyDetails.defaults |= Notification.DEFAULT_SOUND
                        | Notification.DEFAULT_VIBRATE;
                mNotificationManager.notify((int) editEventid, notifyDetails);
                Log.d(null,"notification set");
    }


}

Ответы [ 3 ]

1 голос
/ 21 марта 2011

Ваш код показывает пустой экран, потому что вы запустили Activity в результате срабатывания тревоги, и Activity без contentView по-прежнему будет работать в полноэкранном режиме, но будет пустым.Вы должны создавать и запускать Notification непосредственно в BroadcastReceiver, не вызывая другие системные компоненты.

public class NotificationMessage extends BroadcastReceiver {
    // Display an alert that we've received a message.

    public void onReceive(Context context, Intent intent) {
        NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
        Notification notifyDetails = new Notification(R.drawable.icon, "MyApp", nextAlarmTime);

        CharSequence contentTitle = "MyApp";
        CharSequence contentText = notificationAlart;

        Intent notifyIntent = new Intent(context, MyApp.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(
                ScheduleAlert.this, 0, notifyIntent,
                android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
        notifyDetails.setLatestEventInfo(context, contentTitle,
                contentText, pendingIntent);


        notifyDetails.flags = Notification.FLAG_AUTO_CANCEL;
        notifyDetails.defaults |= Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE;
        mNotificationManager.notify((int) editEventid, notifyDetails);
        Log.d(null,"notification set");
    }
}

Обратите внимание, что вам предоставляется контекст при вызове этого метода, поэтому вы нене нужно создавать активность или службу только для получения доступа к ней.

ЕДИНСТВЕННОЕ исключение из этого, если ожидается, что создание Notification займет много времени (с вашим доступом к БД), в этом случае вы должны создать IntentService из onReceive(), чтобы сделать работу.

Надеюсь, что поможет!

1 голос
/ 21 марта 2011

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

Подумайте об использовании API Buzzbox, чтобы сделать вашу жизнь проще. Вы должны создать задачу и поместить свой код БД в метод doWork. Затем вы можете запланировать свою задачу, используя строку cron.

Подробнее: http://hub.buzzbox.com/android-sdk/

1 голос
/ 21 марта 2011

Ваш ScheduleAlert действительно должен быть активным? Разве Сервис не будет лучше? Класс Service не предоставляет никакого графического интерфейса, поэтому черный экран отсутствует.

...