【问题标题】:Asynctask causes exception 'Can't create handler inside thread that has not called Looper.prepare()'Asynctask 导致异常“无法在未调用 Looper.prepare() 的线程内创建处理程序”
【发布时间】:2012-12-05 19:18:02
【问题描述】:

我正在开发一个 android 应用程序。在我的活动中,我使用以下代码。

LocationResult locationResult = new LocationResult(){

        @Override
        public void gotLocation(Location location){
            //Got the location!




            Drawable marker = getResources().getDrawable(
                    R.drawable.currentlocationmarker);//android.R.drawable.btn_star_big_on
            int markerWidth = marker.getIntrinsicWidth();
            int markerHeight = marker.getIntrinsicHeight();
            marker.setBounds(0, markerHeight, markerWidth, 0);
            MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(marker);
            currentmarkerPoint = new GeoPoint((int) (location.getLatitude() * 1E6),
                    (int) (location.getLongitude() * 1E6));

            currLocation = location;

            mBlippcoordinate = currentmarkerPoint;
            mBlippLocation = location;
            myItemizedOverlay.addItem(currentmarkerPoint, "", "");

            mBlippmapview.getOverlays().add(myItemizedOverlay);
            animateToCurrentLocation(currentmarkerPoint);


        }
    };


    MyLocation myLocation = new MyLocation();
    myLocation.getLocation(this, locationResult);

我正在使用上面的代码从 gps 或网络中查找位置。animateToCurrentLocation(currentmarkerPoint); 方法包含一个异步任务。所以我得到了

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

提前致谢。

【问题讨论】:

  • 我敢打赌,你的 asynctask 中有某种对话框或 toast :) 你需要重新排列你的代码,这样你就不会从 UI 进行网络操作

标签: android android-asynctask handler


【解决方案1】:

当您尝试从没有附加 Looper 的线程创建和运行 AsyncTask 时,您会收到此错误。 AsyncTasks 需要一个 Looper 来将其“任务完成”消息发送回启动 AsyncTask 的线程。

现在你真正的问题是:如何使用 Looper 获取线程?事实证明你已经有了一个:主线程。正如文档还指出的那样,您应该从主线程创建并 .execute() AsyncTask。然后 doInBackground() 将在工作线程(来自 AsyncTask 线程池)上运行,您可以在那里访问网络。在通过主线程的 Handler/Looper 发布后,onPostExecute() 将在您的主线程上运行。

【讨论】:

  • @baske ....我明白了一些东西..但是不知道如何解决我当前的问题..现在我的 asynctask 是从线程调用的。如何让我的 asynctask 任务从主线程工作?...
  • 如果我理解正确,您现在正在从工作线程创建和执行 AsyncTask,您想知道如何在主线程上执行此操作?好吧,我能想到的最俗气的方法是使用 Activity 的 runOnUiThread() 方法。您当前的代码(样机代码,实际上不起作用;-): ... task = new AsyncTask(); task.execute() ... 你的新代码: ... runOnUiThread(new Runnable() { @override public void run() { task = new AsyncTask(); task.execute(); }); ...
  • 对不起,糟糕的标记.. StackOverflow 的新手,所以仍然必须习惯论坛提供的所有东西。希望你能理解。它的基本作用是将你现有的代码包装在一个 Runnable 中,并将这个 runnable 发布到主线程的处理程序上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 2017-03-07
  • 2018-12-10
  • 2014-11-04
  • 2015-07-26
相关资源
最近更新 更多