【问题标题】:Only one Looper may be created per thread每个线程只能创建一个 Looper
【发布时间】:2016-03-19 12:04:42
【问题描述】:

使用以下代码:

private void showDialog(String message) {
    try
    {
    Looper.prepare();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            try {
                Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Ringtone r = RingtoneManager.getRingtone(context.getApplicationContext(), notification);
                r.play();
            } catch (Exception e) {
                e.printStackTrace();
                UserPrefs.setLogerForException(Log.getStackTraceString(e).toString(),
                        GlobalContext.Myglobalcontext,ApiConstants.Excption_Log_Message);
            }
            CustomAlert alertDialog = new CustomAlert();
            alertDialog.setTitle(context.getResources().getString(R.string.notification_tite));
            alertDialog.setMessage(msg.obj.toString());
            alertDialog.setAlertId(Events.MORE_INFO);
            alertDialog.setTextGravity(Gravity.LEFT);
            ReplicaPrefs.showAlert(alertDialog);
        }
    };

    Message msgObj = handler.obtainMessage();
    msgObj.obj = message    ;
    handler.handleMessage(msgObj);
    }
    catch(Exception ex)
    {
        UserPrefs.setLogerForException(Log.getStackTraceString(ex).toString(),
                GlobalContext.Myglobalcontext,ApiConstants.Excption_Log_Message);
    }

}

一段时间后(不是确切的情况)我有以下错误:

java.lang.RuntimeException: android.os.Looper.prepare 的每个线程只能创建一个 Looper

有人知道我哪里出错了吗?

【问题讨论】:

    标签: android looper android-looper


    【解决方案1】:

    请注意:每个Handler 与一个Looper 捆绑在一起,每个线程只能创建一个Looper。因此,您可以通过Handler(Looper) 的构造函数创建一个Handler 实例。使用Handler() 创建一个实例时,默认Looper 来自当前Activitys 运行的主UI 线程

    至于您上面的代码,您在Activity 中定义了showDialog(String message),对吗?因此,这意味着此方法将在 主 UI 线程 上调用。因此,当您在showDialog(String message) 内部通过Handler() 的构造函数创建Handler 实例时,来自主UI 线程Looper 将默认与Handler 实例捆绑在一起。这意味着Looper.prepare(); 是多余的,然后删除Looper.prepare(); 将解决您的问题。

    【讨论】:

    • 不完全是。 Handler() 使用当前线程,如果当前线程不是Looper,则抛出异常。这是正常的,但不一定是主线程。
    • 是的,Handler() 将与运行 showDialog(String message)Thread 创建的 Looper 捆绑在一起。在这种情况下,showDialog(String message)主 UI 线程上运行。
    【解决方案2】:

    我认为你应该看看这个来了解剪枝:What is the purpose of Looper and how to use it?

    然后,看看这个:java.lang.RuntimeException: Only one Looper may be created per thread 为您的问题找到答案。

    希望有所帮助!

    【讨论】:

      猜你喜欢
      • 2012-01-16
      • 2011-04-22
      • 2014-05-27
      • 2019-05-05
      • 1970-01-01
      • 2019-01-22
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多