當我嘗試使用谷歌日曆api時,我在ICS上遇到問題。要獲取事件列表,我有一個AsyncTask,並在doInBackground()內進行服務調用,但仍收到NetworkOnMainThreadException錯誤。AsyncTask中的Android 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中使用它。
什麼可能導致此錯誤,以及我如何解決問題?
謝謝!
聽起來有點奇怪。引入這種異常是爲了避免UI Thread中長時間運行的任務。我會建議再次檢查你的代碼,以確保所有需要網絡訪問的東西都不在UI線程上執行。 onPostExecute中的任何內容? – Blackbelt 2012-02-22 16:46:13
我再次檢查,謝謝你的提示,我知道爲什麼該錯誤應該開始,我試圖做出一個簡單的谷歌請求與adnroid sdk HttpGet方法和實際工作沒有問題,如果我切換在asyncTask與代碼谷歌日曆之一,錯誤出現..後,我改變了清單,它工作 – Cata 2012-02-22 17:00:33
OMG,這真的工作。我有同樣的問題,然後我刪除了android:targetSdkVersion屬性。現在應用程序加載正常。 – curiousguy 2012-10-23 18:45:35