【问题标题】:Illegal monitor state exception on notification in postexecute of async task异步任务执行后通知中的非法监视器状态异常
【发布时间】:2014-01-02 08:18:50
【问题描述】:

我正在制作一个应用程序,它会在在线存储的数据发生变化时发出通知。为此,我使用alarmmanager/broadcastreceiver 定期检查广播接收器中使用异步任务的任何更改。如果有任何更改,在线程的帖子执行部分中,我将开始通知。 在“nm.notify();”行我使用调试器得到一个 InvocationTargetException 异常的原因是“IllegalMonitorStateException:对象在 notify() 之前没有被线程锁定” 有人可以阐明正在发生的事情。提前致谢。

OnPostExecute 的代码是:

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    resultstr=result;
    SharedPreferences sp=context.getSharedPreferences("Prefs", 3);
    String oldresult=sp.getString("notification", "hello world");
    if (resultstr.equals("unable to connect to internet")){}else if(resultstr.equals("")){}else
    if (!oldresult.equals(resultstr)){
        NotificationManager nm = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.ic_launcher,"Tax Tracker 2014",System.currentTimeMillis());
         final Intent notificationIntent = new Intent(context,
                 FB.class);
         PendingIntent p = PendingIntent
                 .getActivity(context, 0, notificationIntent, 0);
         notification.setLatestEventInfo(context, "Tax Tracker 2014", "new info alert", p);
         nm.notify();
    SharedPreferences.Editor edit=sp.edit();
    edit.putString("notification", resultstr).commit();
    }
  }

【问题讨论】:

    标签: java android multithreading android-asynctask android-notifications


    【解决方案1】:

    Ankit 你使用了错误的方法,你需要NotificationManager 中定义的notify(id,notification) 方法但是你使用的是Object#notify()

    我想你需要这个NotificationManager#notify(int id, Notification notification)

    public void notify (int id, Notification notification)
    

    发布要在状态栏中显示的通知。如果有通知 您的应用程序已经发布了具有相同 ID 的 尚未取消,将替换为更新的信息。

    参数

    id - An identifier for this notification unique within your application.
    notification -  A Notification object describing what to show the user. Must not be null.
    

    例外的原因,但我猜这不是你想做的。

    在调用notify()之前,您需要先锁定nm,使用synchronized(nm){nm.notify();}

    【讨论】:

      【解决方案2】:

      在调用 wait() 或 notify() 之前,您需要锁定监视器。

      尝试将其放入 synchronized(nm) 块中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-13
        相关资源
        最近更新 更多