Ошибки при желании создать уведомление в OnReceive () - PullRequest
1 голос
/ 14 августа 2011

Я хочу отобразить уведомление и повторять его каждый период. Я прочитал, как это сделать, и сделал этот код в классе, расширяющем Broadcast Receiver:

public class OnAlarmReceiver extends BroadcastReceiver{
    @Override
     public void onReceive(Context context, Intent intent) {


        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = R.drawable.icon;
        CharSequence tickerText = "Votre vidange approche";
        long when = System.currentTimeMillis();

        Notification notification = new Notification(icon, tickerText, when);


        CharSequence contentTitle = "Notification";
        CharSequence contentText = "Vérifier votre kilométrage";
        Intent notificationIntent = new Intent(this, Acceuil.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        final int HELLO_ID = 1;

        mNotificationManager.notify(HELLO_ID, notification);
     }

Однако я не знаю, почему у меня есть такие ошибки:

The method getSystemService(String) is undefined for the type OnAlarmReceiverThe constructor Intent(OnAlarmReceiver, Class<Acceuil>) is undefined
The method getActivity(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (OnAlarmReceiver, int, Intent, int)

В другом упражнении я думаю, что я должен сделать это:

public void notifs() {
        AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i=new Intent(context, OnAlarmReceiver.class);
        PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);

        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1800000, pi);
    }

В чем здесь проблема? Большое спасибо.

1 Ответ

3 голосов
/ 14 августа 2011

Разница:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

и

AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

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

Чтобы это исправить, сделайте:

NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);


PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

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

Чтобы это исправить, сделайте:

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...