2013-05-05 5 views
2

Я пытаюсь показать небольшое уведомление в своем приложении для Android, но я ничего не вижу визуально. MainActivity класс имеет static field, названный activity, который равен this. message.data просто вытащил из объекта. Вот что я называю:Уведомление Android не отображается

sendNotification(MainActivity.activity.getApplicationContext(), 
       null, 
       message.data, 
       message.data, 
       1, true, true, true, 0); 

А вот мясо:

public static void sendNotification(Context caller, Class<?> activityToLaunch, String title, String msg, int numberOfEvents,boolean sound, boolean flashLed, boolean vibrate,int iconID) { 
    NotificationManager notifier = (NotificationManager) caller.getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification notify = new Notification(R.drawable.ic_launcher,"Notification",System.currentTimeMillis()); 

    notify.icon   = iconID; 
    notify.tickerText = title; 
    notify.when   = System.currentTimeMillis(); 
    notify.number  = numberOfEvents; 
    notify.flags  |= Notification.FLAG_AUTO_CANCEL; 

    if (sound) notify.defaults |= Notification.DEFAULT_SOUND; 
    if (vibrate) notify.vibrate  = new long[] {100, 200, 300}; 
    if (flashLed) { 
     notify.flags |= Notification.FLAG_SHOW_LIGHTS; 
     notify.ledARGB = Color.CYAN; 
     notify.ledOnMS = 500; 
     notify.ledOffMS = 500; 
    } 

    int NOTIFICATION_ID = 1232; 

    Intent notificationIntent = new Intent(); 
    PendingIntent contentIntent = PendingIntent.getActivity(caller, 0, notificationIntent, 0); 
    notify.setLatestEventInfo(caller, title, msg, contentIntent); 
    notifier.notify(NOTIFICATION_ID, notify); 
} 

Я могу войти сообщения, так что я знаю, что это вызывалось и Сучковый однако, я новичок в андроид развития и, вероятно, я пропустил критическую часть. Я запускаю эмулятор Android 2.2. Это все в объекте плагина, который я связал с кордорой, которая работает в фоновом режиме, если это вообще имеет значение.

+1

Это может или не может вызвать проблему или внести вклад в это или нет, но в любом случае: Забудьте о 'static', он не будет работать на Android, как вы думаете, потому что класс может не загружаться,' static' или нет. Единственное место, где 'static' _may_ имеет смысл, - это« Приложение », но даже там он не будет делать то, что вы хотите, когда вы его объявите. –

+0

Хм, я буду помнить об этом, спасибо. После быстрого теста он, похоже, не исправляет или не изменяет программу. – jett

+1

Вопрос в том, почему, по-вашему, вам нужно сохранить этот «Контекст». Важно понимать, что 'Context's имеют разные lifespans (Application vs Activity) и разные значения. Использование устаревшего 'Context' в основном не даст желаемого результата. И использование того же метода с «Activity» как «Context» может привести к другому результату, чем использовать его с «Приложением» как «Контекст». Кроме того, здесь обсуждается SO о различии между 'getApplication()' и 'getApplicationContext()'. –

ответ

0

Я создал новый класс для намерения:

public class StatusNotificationIntent { 
    public static Notification buildNotification(Context context, CharSequence tag, CharSequence contentTitle, CharSequence contentText) { 
     int icon = R.drawable.notification; 
     long when = System.currentTimeMillis(); 
     Notification noti = new Notification(icon, contentTitle, when); 
     noti.flags |= flag; 

     PackageManager pm = context.getPackageManager(); 
     Intent notificationIntent = pm.getLaunchIntentForPackage(context.getPackageName()); 
     notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
     notificationIntent.putExtra("notificationTag", tag); 

     PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); 
     noti.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
     return noti; 
    } 
} 

И я называю его с помощью этой функции

public void showNotification(CharSequence tag, CharSequence contentTitle, CharSequence contentText, int flag) { 
    String ns = Context.NOTIFICATION_SERVICE; 
    context = cordova.getActivity().getApplicationContext(); 
    mNotificationManager = (NotificationManager) context.getSystemService(ns); 

    Notification noti = StatusNotificationIntent.buildNotification(context, tag, contentTitle, contentText); 
    mNotificationManager.notify(tag.hashCode(), noti); 
} 

ClassStacker и Дэвид Wasser (в комментариях) были правы в том, что сочетание использования правильного намерения и правильного контекста решает эту проблему.

Смежные вопросы