AsyncTask中的Android NetworkOnMainThreadException

时间:2012-02-22 16:04:59

标签: android google-calendar-api google-api-java-client

当我尝试使用谷歌日历API时,我在ICS上遇到了问题。要获取事件列表,我有一个AsyncTask,并在doInBackground()内部进行服务调用但仍然收到NetworkOnMainThreadException错误。

这是我的代码:

我像这样调用我的AsyncTask:

new GoogleCalendarEvents().execute(new Object());

我的AsyncTask看起来像这样:

private class GoogleCalendarEvents extends AsyncTask<Object, Object, Object> {

        @Override
        protected Object doInBackground(Object... objects) {

            OAuthManager manager = OAuthManager.getInstance();
            /* login to google api and get the auth token */
            manager.doLogin("", true, mActivity, new OAuthManager.AuthHandler() {
                @Override
                public void handleAuth(Account account, String authToken) {
                    if (account != null) {
                        /* create a google Calendar service if the returned account is not null */
                        com.google.api.services.calendar.Calendar service = CalendarServiceBuilder.build(OAuthManager.getInstance().getAuthToken());
                        try {

                            /* get the list of events for the primary calendar */
                            /* ---------HERE THE APP IS CRUSHING  --------- */
                            mEvents = service.events().list(mCalendarId).execute();

                            while (true) {
                                /* get the next page token if any */
                                String pageToken = mEvents.getNextPageToken();

                                if (pageToken != null && !pageToken.equals("")) {
                                    /* if there are other pages, get the next page */
                                    Events newPageEvents = service.events().list(mCalendarId)
                                            .setPageToken(pageToken).execute();

                                    for (Event event : newPageEvents.getItems()) {
                                        /* loop through all the events and add them into the mEvents  */
                                        mEvents.put(event.getId(), event);
                                    }

                                } else {
                                    break;
                                }
                            }
                            /* make sure we wont have memory leaks */
                            mActivity = null;
                            /* notify the caller that the calendar events are ready */
                            mEventsReceiverCallback.calendarEventsReceived(true);
                            mEventsReceiverCallback = null;

                        } catch (IOException e) {
                            /* let the user know that the event could not be created */
                            Utility.showInformationDialog(mActivity, mActivity.getString(R.string.error),
                                    mActivity.getString(R.string.error_message_bad_request_get_events));
                            /* make sure we wont have memory leaks */
                            mActivity = null;
                            /* print the error into the log */
                            e.printStackTrace();
                            /* notify the caller that the manager could not get the calendar events */
                            mEventsReceiverCallback.calendarEventsReceived(false);
                            mEventsReceiverCallback = null;

                        }

                    } else {

                        /* le the user know that the event could not be created */
                        Utility.showInformationDialog(mActivity, mActivity.getString(R.string.error),
                                mActivity.getString(R.string.error_message_connection));
                        /* make sure we wont have memory leaks */
                        mActivity = null;
                        /* notify the caller that the manager could not get the calendar events */
                        mEventsReceiverCallback.calendarEventsReceived(false);
                        mEventsReceiverCallback = null;

                    }
                }
            });

            return null;
        }

    }

日志:

02-22 10:32:08.597: ERROR/AndroidRuntime(13924): FATAL EXCEPTION: main
        android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
        at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
        at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
        at java.net.InetAddress.getAllByName(InetAddress.java:220)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
        at com.google.api.client.http.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:58)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:639)
        at com.google.api.client.http.json.JsonHttpClient.execute(JsonHttpClient.java:257)
        at com.google.api.client.googleapis.services.GoogleClient.execute(GoogleClient.java:121)
        at com.google.api.client.http.json.JsonHttpRequest.executeUnparsed(JsonHttpRequest.java:67)
        at com.google.api.services.calendar.Calendar$Events$List.execute(Calendar.java:2643)
        at /* here is the error, I think */com.google.calendar.manager.business.CalendarEventProvider$GoogleCalendarEvents$1.handleAuth(CalendarEventProvider.java:118)
        at com.google.calendar.manager.utils.OAuthManager$1.run(OAuthManager.java:194)
        at android.accounts.AccountManager$10.run(AccountManager.java:1264)
        at android.os.Handler.handleCallback(Handler.java:605)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4424)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

Here说我必须使用AndroidHttp.newCompatibleTransport()作为传输类,我在CalendarServiceBuilder中使用它。

什么可能导致此错误以及我如何解决问题?

谢谢!

2 个答案:

答案 0 :(得分:3)

似乎问题出在清单中..我在uses-sdk标签中有这个属性:

android:targetSdkVersion="10"

删除此属性后,应用程序正常运行。

答案 1 :(得分:0)

您是否在模拟器上测试了这个?出于某种原因,我在AsyncTask中流式传输.mpjeg时在模拟器上进行测试时遇到了同样的问题。但是,当我在设备上测试时,它工作正常。

这可能是模拟器问题;然而它也可能是ICS(我的模拟器4.0.3,但在我的手机上运行2.3.7 CM7b257),但尝试一下,因为这很可能是你的问题。