English 中文(简体)
Anders: got CalledFromWrongThreadException in onPostExecute() - How can it?
原标题:Android: got CalledFromWrongThreadException in onPostExecute() - How could it be?
  • 时间:2012-05-03 06:19:11
  •  标签:
  • android

我用RAA对生产进行了数周的估算,在今天报告的一个奇怪错误之前,我有零的错误。

页: 1

    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

摘自这种方法(检索):

at my.app.CountdownFragment$1.void onPostExecute(java.lang.Object)(SourceFile:1)

这是相关的消息来源:

    private void addInstructionsIfNeeded() {
    if (S.sDisplayAssist) {
        new AsyncTask<String, Void, String>() {

            @Override
            protected String doInBackground(String... params) {
                return null;
            }

            /*
             * runs on the ui thread
             */
            protected void onPostExecute(String result) {

                Activity a = getActivity();

                if (S.sHelpEnabled && a != null) {

                    in = new InstructionsView(a.getApplicationContext());

                    RelativeLayout mv = (RelativeLayout) a
                            .findViewById(R.id.main_place);

                    mv.addView(in.prepareView());
                }

            };

        }.execute("");
    }
}

  • onPostExecute() runs on the UI thread, so why I ve got "wrong thread"?
  • This code ran already on more than 150 devices, and more than 100000 times (according to Flurry), and never had this error.
  • The originating device is Samsung SGH-I997 running SDK 4.0.4

我的问题是:怎么办?

EDIT: This all happens in a fragment

最佳回答

i) 患有同样的问题,这是另一个roid框架。

<>亮度>

在某些情况下,申请可能有一个以上的“路器”,因此不止一个“天线”

http://www.ohchr.org。 i 在本答复中,在松散的感觉中使用了“信号”一词,因为当人们说“信号”通常是指主要或切身,就像摆在它面前的许多其他专业组织一样,允许使用多种电传泵(即<代码>Looperin >,见:,http://en.wikipedia.org/wiki/Event_loop/),用于不同用途的树木(例如,用于特定用途和具有一定距离的树木)。 <>-/>

this means:

由于申请可以有一个以上的“概念”和一个<条码>AsyncTask, 总是“统一概念”>[ref]/a>, 某人决定[很少],而不是AsyncTask(在99.99%的案例中)总是在设计线上运行,他们决定使用“天线”作为“主线”。

    Log.i("AsyncTask / Handler created ON: " + Thread.currentThread().getId());
    Log.i("Main Looper: " + Looper.getMainLooper().getThread().getId() + "      myLooper: "+ Looper.myLooper().getThread().getId());

    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            Log.i("doInBackground ran ON: " + Thread.currentThread().getId());
            // I m in the background, all is normal

            handler.post(new Runnable() {

                @Override
                public void run() {
                    Log.i("Handler posted runnable ON: " + Thread.currentThread().getId());
                    // this is the correct thread, that onPostExecute should be on
                }
            });

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i("onPostExecute ran ON: " + Thread.currentThread().getId());
            // this CAN be the wrong thread in certain situations
        }

    }.execute();

如果从上述坏情况来看,产出将考虑这样的内容:

    AsyncTask / Handler created ON: 16
    Main Looper: 1      myLooper: 16
    doInBackground ran ON: 12
    onPostExecute ran ON: 1
    Handler posted runnable ON: 16

<><>, 编号为AsyncTask>。

as shown this can be mitigated using a Handler.post(Runnable) in my specific case the duality of my "UI thread" situation was caused by the fact that I was creating a dialog in response to a JavaScript interface method called from a WebView, basically: the WebView had its own "UI thread" and that was the one that i was currently running on..

从我能够告诉的(没有真正关心或读到太多)来看,<代码>似乎 AsyncTask par callsback methods in generalfall from a individual Koreanvertiatedhandler (eg:

希望——

问题回答

如果有同样的问题。 在我的案件中结案

www.un.org/spanish/ecosoc 简要解释:

  1. Running AsynckTask for the very first time on non UI thread with looper leads to loading AsyncTask.class and initialization sHandler to handler constructed on that non UI looper.
  2. Now sHandler is connected to that non UI thread for ANY instance of AsyncTask subclasses and onPreExecute, onProgressUpdate and onPostExecute methods will be invoked on that non UI thread (unless AsyncTask.class will be unloaded)
  3. Any attempt to deal with UI inside any of the above methods will lead to crash with android.view.ViewRootImpl$CalledFromWrongThreadException
  4. To avoid such situation one should always run (at least for the very first time) AsyncTask on UI thread in order to let AsyncTask s sHandler-field be initialized with UI s looper

www.un.org/spanish/ecosoc 故事:

有两个生产图:A - main android app and B - some utilty app.

一体化之后,我们收到了许多坠毁事件:

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

http://strong>AsynckTask.onPostExecute()

经过一些调查,似乎在其<>HandlerThread<>/strong>内使用了AsyncTask

The traces was found in AsyncTask s source code:

private static final InternalHandler sHandler = new InternalHandler();

This is the handler which is used to send onPostExecute() to UI thread.

This handler is static and it will be initialized during class loading i.e. first new AsyncTask() appearance

这意味着,onPostExecute将永远张贴到这个深层:new AsyncTask()第一次被征召(除非AsyncTask.class将卸下,再装上)

In my case the flow was something like this:

1 - starting app A
2 - initializing B form A
3 - B creates its own HandlerThread and launches AsyncTask <- now onPostExecute wil be posted to this HandlerThread no matter where from an instance of AsyncTask will be launched in future
4 - create AsyncTask in the app A for a long operation and update UI in its onPostExecute
5 - when executing onPostExecute() the CalledFromWrongThreadException is thrown

然后,一位地雷的朋友从android.developers 上向我出示了相关的文件。 (Threading Rules section):

The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN. The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread.

希望能够有助于澄清局势

Maybe the reason is Flurry? I had this exception when I used Flurry 3.2.1. But when I went back to Flurry 3.2.0 I didn t have this exception

Use Flurry 3.2.2 and above.

在“Create”申请中加入以下法典应解决这一问题:

     /**
     * Fixing AsyncTask Issue not called on main thread
     */
    try {
        Class.forName("android.os.AsyncTask");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

问题似乎是在阿辛卡茨克族首次在不属于我们主线的不同主线上启动时产生的,我通过在我申请Create时在底层添加该法典加以检查。

    new Thread(new Runnable() {


        @Override
        public void run() {

            Log.i("tag","1.3onPostExecute ran ON: " + Thread.currentThread().getId());
            Looper.prepare();
            new AsyncTask<Void,Void,Void>(){
                @Override
                protected Void doInBackground(Void... params) {
                    Log.i("tag","2onPostExecute ran ON: " + Thread.currentThread().getId());
                    return null;
                }

                @Override
                protected void onPostExecute(Void aVoid) {
                    Log.i("tag","1.2onPostExecute ran ON: " + Thread.currentThread().getId());
                    super.onPostExecute(aVoid);
                }
            }.execute();
            Looper.loop();
            Looper.myLooper().quit();
        }
    }).start();

该法典将把阿斯恩·塔克带入一个不是申请主的主线,并将造成在阿辛卡茨塔克的任何其他航道上坠毁的申请。 与FromWrongThreadException发生碰撞

Hope it cleared things a little bit more.

感谢大家为此提供的巨大帮助。

地点

runOnUiThread(new Runnable() {
    public void run() { /*code*/ } );

页: 1

/*
             * runs on the ui thread
             */
            protected void onPostExecute(String result) {

                Activity a = getActivity();

                if (S.sHelpEnabled && a != null) {

                    in = new InstructionsView(a.getApplicationContext());

                    runOnUiThread(new Runnable() {
                       public void run() {

                    RelativeLayout mv = (RelativeLayout) a
                            .findViewById(R.id.main_place);

                    mv.addView(in.prepareView());
                   }
                }

            };

引证该法典。 我认为,这将解决问题。

我认为,问题在于:<条码>a = 主动性;。 我认为,在进入AsyncTask之前,你应该这样做。





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签