2012-01-27 2 views
10

Я пытаюсь получить уведомление об успешной загрузке из ASyncTask для работы весь день. Я не получаю никаких ошибок из моего текущего кода, но я не могу получить уведомление для показа в панели уведомлений (или где-либо еще). Я не получаю сообщений в LogCat, и на панели уведомлений не появляется уведомление. Это мой код:Уведомление Android не работает

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

CharSequence contentTitle = "upload completed."; 
CharSequence contentText = "upload completed."; 

Intent notificationIntent = new Intent(context, CastrActivity.class); 
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_NO_CREATE); 
mNotification.contentIntent = contentIntent; 
mNotification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 
mNotificationManager.notify(NOTIFICATION_ID, mNotification); 

Это вызвано методом onPostExecute() ASyncTask. Честно говоря, я немного запутался в части PendingIntent. Любое разъяснение того, что я подозреваю, было неправильным кодом, было бы весьма признательно.

ответ

4

Я создал класс, чтобы показать уведомления:

public class NotificationData { 

    public static NotificationManager mNotificationManager; 
    public static int SIMPLE_NOTFICATION_ID; 
    private Context _context; 

    public NotificationData(Context context) { 
     _context = context; 
    } 

    public void clearNotification() { 
     mNotificationManager.cancel(SIMPLE_NOTFICATION_ID); 
    } 

    public void SetNotification(int drawable, String msg, String action_string, Class cls) { 
     mNotificationManager = (NotificationManager) _context.getSystemService(Context.NOTIFICATION_SERVICE); 
     final Notification notifyDetails = new Notification(drawable, "Post Timer", System.currentTimeMillis()); 
     long[] vibrate = { 100, 100, 200, 300 }; 
     notifyDetails.vibrate = vibrate; 
     notifyDetails.ledARGB = 0xff00ff00; 
     notifyDetails.ledOnMS = 300; 
     notifyDetails.ledOffMS = 1000; 
    // notifyDetails.number=4; 
     notifyDetails.defaults =Notification.DEFAULT_ALL; 
     Context context = _context; 
     CharSequence contentTitle = msg; 
     CharSequence contentText = action_string;  
     Intent notifyIntent = new Intent(context, cls); 
    // Bundle bundle = new Bundle(); 
    // bundle.putBoolean(AppConfig.IS_NOTIFICATION, true); 
     notifyIntent.putExtras(bundle); 
     PendingIntent intent = PendingIntent.getActivity(_context, 0,notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK); 
     notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent); 
     mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);   
    } 
} 

Как использовать этот класс:

NotificationData notification; //create object 
notification = new NotificationData(this); 
notification.SetNotification(R.drawable.notification, "Notification Title", "Click to open", YourClassName.class); 

Добавить разрешения android.permission.VIBRATE

+0

Прошу прощения, но что такое AppConfig? Есть ли библиотека, которую мне нужно включить, чтобы использовать ее? Eclipse, похоже, не знает этого, если есть, поэтому мне придется добавить его в мой путь сборки. – Carnivoris

+0

Appconfig - это класс, а IS_NOTIFICATION является статическим членом, вы можете удалить эту строку. Bundle bundle = new Bundle(); bundle.putBoolean (AppConfig.IS_NOTIFICATION, true); notifyIntent.putExtras (расслоение); –

+0

К сожалению, я все равно не получаю уведомления. Я вызываю его из метода onPostExecute() класса ASyncTask. Я подтверждаю, что ASyncTask завершен сообщением в LogCat, но я не получаю уведомления, отправленного на панель уведомлений. – Carnivoris

2

Попробуйте это:

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

int icon = R.drawable.icon;  // icon from resources 
CharSequence tickerText = "Any thing";    // ticker-text 
long when = System.currentTimeMillis();   // notification time 
Context context21 = getApplicationContext();  // application Context 
CharSequence contentTitle = "Anything"; // expanded message title 
CharSequence contentText = (CharSequence) extras.get("message");  // expanded message text 

Intent notificationIntent = new Intent(this, MainStart.class); 
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 

// the next two lines initialize the Notification, using the configurations above 
Notification notification = new Notification(icon, tickerText, when); 
notification.defaults |= Notification.DEFAULT_VIBRATE; 
notification.defaults |= Notification.DEFAULT_LIGHTS; 
notification.defaults |= Notification.DEFAULT_SOUND; 
notification.flags |= Notification.FLAG_AUTO_CANCEL; 
/* long[] vibrate = { 0, 100, 200, 300 }; 
notification.vibrate = vibrate; 
notification.ledARGB = Color.RED; 
notification.ledOffMS = 300; 
notification.ledOnMS = 300;*/ 
notification.setLatestEventInfo(context21, contentTitle, contentText, contentIntent); 
mNotificationManager.notify(Constants.NOTIFICATION_ID, notification); 
+0

Я столкнулся с подобными проблемами с этим, как и раньше. Intent notificationIntent = новое намерение (это, CastrRecorder.class); Эта строка отмечена Eclipse, и единственным разрешением для нее является удаление аргументов. Кроме того, это вызвано внутри класса, который расширяет ASyncTask и getActivity() не работает. – Carnivoris

2

Еще одна вещь, чтобы попытаться это сделать, что ваш манифест содержит

<permission android:name="android.permission.STATUS_BAR_SERVICE" android:protectionLevel="signature" /> 

Также мое, казалось, игнорируют последовательные уведомления с той же NOTIFICATION_ID.

30

Даже если ваша проблема решена, я просто опубликовать, как я решить мою проблему, что уведомление не показывал, возможно, это могло бы помочь другим людям читать ответы:

В моем уведомлении здания, которое я пропускал значок. Как только я добавил что-то вроде setSmallIcon(R.drawable.ic_launcher), было показано уведомление.

+0

получил точно такую ​​же проблему .. решена, спасибо! – akhyar

+0

Да, работал и на меня. Первый раз работает с уведомлениями.Большое спасибо! –

+0

Точно! Большое спасибо! – Alexandr

0

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

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