Can't synchronize call to notify()

旧巷老猫 提交于 2020-01-15 12:30:09

问题


Forgive me, but i am not able to get a call on NotificationBuilder's notify() method. I have this code:

timer.scheduleAtFixedRate(
              new TimerTask() {
                @Override
                public void run() {
                    synchronized (this) {
            Builder notif = new NotificationCompat.Builder(c);
        notif.setContentIntent(contIntent)
                .setWhen(System.currentTimeMillis())
                .setTicker("Notification ticker")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Vinceri")
                .setContentText("Ha recibido una oferta de trabajo")
                .setAutoCancel(true);

        notif.notify();
        }
}
}

And no matter where i put the synchronized block, i get the same exception:

04-05 10:42:55.116: E/AndroidRuntime(18244): FATAL EXCEPTION: Timer-0
04-05 10:42:55.116: E/AndroidRuntime(18244): java.lang.IllegalMonitorStateException: object not locked by thread before notifyAll()
04-05 10:42:55.116: E/AndroidRuntime(18244):    at java.lang.Object.notifyAll(Native Method)
04-05 10:42:55.116: E/AndroidRuntime(18244):    at com.publidirecta.vinceriazafata.NotificationService$1.run(NotificationService.java:126)
04-05 10:42:55.116: E/AndroidRuntime(18244):    at java.util.Timer$TimerImpl.run(Timer.java:284)

It is maybe a noob question but... what I must to do to not receive that Exception? thank you.


回答1:


Assuming that you are trying to add notification to the android notification drawer.. You need to do following:

Builder notif = new NotificationCompat.Builder(c);
        notif.setContentIntent(contIntent)
                .setWhen(System.currentTimeMillis())
                .setTicker("Notification ticker")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Vinceri")
                .setContentText("Ha recibido una oferta de trabajo")
                .setAutoCancel(true);
      //create notification from builder
      Notification notification = notif.build();
      //get instance of NotificationManager
      NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      //call notify method of NotificationManager to add this notification to android notification drawer..
      notificationmanager.notify(0, notification);


来源:https://stackoverflow.com/questions/15829520/cant-synchronize-call-to-notify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!