From f3aa50205a0272b13cf361595c70200f45b78435 Mon Sep 17 00:00:00 2001 From: liuyuxia <13337357913@qq.com> Date: Fri, 10 Jan 2025 09:01:07 +0800 Subject: [PATCH] liuyuxia --- .../exception/ActionFailureException.java | 27 + .../exception/NetworkFailureException.java | 31 +- .../notes/gtask/remote/GTaskASyncTask.java | 294 +++--- .../notes/gtask/remote/GTaskClient.java | 908 +++++++++--------- 4 files changed, 659 insertions(+), 601 deletions(-) diff --git a/src/java/net/micode/notes/gtask/exception/ActionFailureException.java b/src/java/net/micode/notes/gtask/exception/ActionFailureException.java index 15504be..2ede071 100644 --- a/src/java/net/micode/notes/gtask/exception/ActionFailureException.java +++ b/src/java/net/micode/notes/gtask/exception/ActionFailureException.java @@ -16,18 +16,45 @@ package net.micode.notes.gtask.exception; +/** + * ActionFailureException 类表示在执行 Google 任务操作时发生的异常。 + * 它继承自 RuntimeException,用于处理不可恢复的错误。 + */ public class ActionFailureException extends RuntimeException { private static final long serialVersionUID = 4425249765923293627L; + /** + * 构造一个无参数的 ActionFailureException。 + */ public ActionFailureException() { super(); } + /** + * 构造一个带有详细信息的 ActionFailureException。 + * @param paramString 异常的详细信息 + */ public ActionFailureException(String paramString) { super(paramString); } + /** + * 构造一个带有详细信息和原因的 ActionFailureException。 + * @param paramString 异常的详细信息 + * @param paramThrowable 异常的原因 + */ public ActionFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } } + +/** + * 类注释 +ActionFailureException 类表示在执行 Google 任务操作时发生的异常。它继承自 RuntimeException,用于处理不可恢复的错误。 +常量定义 +serialVersionUID:用于序列化和反序列化时的版本控制。 +构造方法 +ActionFailureException():构造一个无参数的 ActionFailureException。 +ActionFailureException(String paramString):构造一个带有详细信息的 ActionFailureException。 +ActionFailureException(String paramString, Throwable paramThrowable):构造一个带有详细信息和原因的 ActionFailureException。 + */ diff --git a/src/java/net/micode/notes/gtask/exception/NetworkFailureException.java b/src/java/net/micode/notes/gtask/exception/NetworkFailureException.java index 437a55e..fedf038 100644 --- a/src/java/net/micode/notes/gtask/exception/NetworkFailureException.java +++ b/src/java/net/micode/notes/gtask/exception/NetworkFailureException.java @@ -15,17 +15,46 @@ */ package net.micode.notes.gtask.exception; + +/** + * NetworkFailureException 类表示在执行网络操作时发生的异常。 + * 它继承自 Exception,用于处理可恢复的网络错误。 + */ public class NetworkFailureException extends Exception { private static final long serialVersionUID = 2107610287180234136L; + /** + * 构造一个无参数的 NetworkFailureException。 + */ public NetworkFailureException() { super(); } + /** + * 构造一个带有详细信息的 NetworkFailureException。 + * @param paramString 异常的详细信息 + */ public NetworkFailureException(String paramString) { super(paramString); } + + /** + * 构造一个带有详细信息和原因的 NetworkFailureException。 + * @param paramString 异常的详细信息 + * @param paramThrowable 异常的原因 + */ public NetworkFailureException(String paramString, Throwable paramThrowable) { super(paramString, paramThrowable); } -} \ No newline at end of file +} + +/** + * 类注释 +NetworkFailureException 类表示在执行网络操作时发生的异常。它继承自 Exception,用于处理可恢复的网络错误。这种异常通常表示网络连接问题或请求失败,可能需要重试或进一步的错误处理。 +常量定义 +serialVersionUID:用于序列化和反序列化时的版本控制。这确保了在不同版本的类之间进行序列化和反序列化时的兼容性。 +构造方法 +NetworkFailureException():构造一个无参数的 NetworkFailureException。这通常用于表示一个通用的网络错误,没有具体的错误信息。 +NetworkFailureException(String paramString):构造一个带有详细信息的 NetworkFailureException。paramString 参数提供了关于异常的详细描述,有助于调试和错误处理。 +NetworkFailureException(String paramString, Throwable paramThrowable):构造一个带有详细信息和原因的 NetworkFailureException。paramString 参数提供了关于异常的详细描述,paramThrowable 参数提供了异常的具体原因,这有助于进行更深入的错误分析和处理。 + */ \ No newline at end of file diff --git a/src/java/net/micode/notes/gtask/remote/GTaskASyncTask.java b/src/java/net/micode/notes/gtask/remote/GTaskASyncTask.java index a5a8fc9..80857d0 100644 --- a/src/java/net/micode/notes/gtask/remote/GTaskASyncTask.java +++ b/src/java/net/micode/notes/gtask/remote/GTaskASyncTask.java @@ -1,145 +1,155 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. +package net.micode.notes.gtask.remote; + +import android.app.Notification; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesListActivity; +import net.micode.notes.ui.NotesPreferenceActivity; + +/** + * 异步任务类,用于同步 Google 任务。 + * 该类继承自 AsyncTask,提供了后台同步 Google 任务的功能,并在同步过程中和完成后更新通知。 */ +public class GTaskASyncTask extends AsyncTask { + + private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // 同步通知的ID + + /** + * 完成监听器接口。 + * 用于在同步完成后执行特定的操作。 + */ + public interface OnCompleteListener { + void onComplete(); // 当同步完成时调用 + } + + private Context mContext; // 应用程序上下文 + private NotificationManager mNotifiManager; // 通知管理器 + private GTaskManager mTaskManager; // Google 任务管理器 + private OnCompleteListener mOnCompleteListener; // 完成监听器 + + /** + * 构造函数。 + * @param context 上下文对象。 + * @param listener 完成监听器。 + */ + public GTaskASyncTask(Context context, OnCompleteListener listener) { + mContext = context; + mOnCompleteListener = listener; + mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); + mTaskManager = GTaskManager.getInstance(); + } + + /** + * 取消同步。 + * 调用 Google 任务管理器的 cancelSync 方法来取消当前的同步操作。 + */ + public void cancelSync() { + mTaskManager.cancelSync(); + } + + /** + * 发布进度信息。 + * @param message 进度信息。 + */ + public void publishProgess(String message) { + publishProgress(new String[] { message }); + } + + /** + * 显示通知。 + * @param tickerId 通知的ID。 + * @param content 通知内容。 + */ + private void showNotification(int tickerId, String content) { + Notification notification = new Notification(R.drawable.notification, mContext.getString(tickerId), System.currentTimeMillis()); + notification.defaults = Notification.DEFAULT_LIGHTS; // 设置默认灯光 + notification.flags = Notification.FLAG_AUTO_CANCEL; // 设置通知自动取消 + PendingIntent pendingIntent; // 待决意图 + + // 根据 tickerId 设置不同的待决意图 + if (tickerId != R.string.ticker_success) { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0); + } else { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), 0); + } + notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, pendingIntent); // 设置通知信息 + mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); // 显示通知 + } + + /** + * 执行同步操作。 + * @return 同步结果状态。 + */ + @Override + protected Integer doInBackground(Void... unused) { + publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity.getSyncAccountName(mContext))); + return mTaskManager.sync(mContext, this); // 同步任务 + } + + /** + * 更新进度信息。 + * @param progress 进度信息数组。 + */ + @Override + protected void onProgressUpdate(String... progress) { + showNotification(R.string.ticker_syncing, progress[0]); // 显示同步中的通知 + if (mContext instanceof GTaskSyncService) { + ((GTaskSyncService) mContext).sendBroadcast(progress[0]); // 如果上下文是 GTaskSyncService,发送广播 + } + } - package net.micode.notes.gtask.remote; + /** + * 同步完成后的操作。 + * @param result 同步结果状态。 + */ + @Override + protected void onPostExecute(Integer result) { + // 根据结果状态显示不同的通知 + if (result == GTaskManager.STATE_SUCCESS) { + showNotification(R.string.ticker_success, mContext.getString(R.string.success_sync_account, mTaskManager.getSyncAccount())); + NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); // 设置最后同步时间 + } else if (result == GTaskManager.STATE_NETWORK_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); + } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); + } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { + showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled)); + } + // 如果设置了完成监听器,则在新线程中调用 onComplete 方法 + if (mOnCompleteListener != null) { + new Thread(new Runnable() { + public void run() { + mOnCompleteListener.onComplete(); + } + }).start(); + } + } +} - import android.app.Notification; - import android.app.NotificationManager; - import android.app.PendingIntent; - import android.content.Context; - import android.content.Intent; - import android.os.AsyncTask; - - import net.micode.notes.R; - import net.micode.notes.ui.NotesListActivity; - import net.micode.notes.ui.NotesPreferenceActivity; - - /** - * 异步任务类,用于同步Google任务。 - */ - public class GTaskASyncTask extends AsyncTask { - - private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; // 同步通知的ID - - /** - * 完成监听器接口。 - */ - public interface OnCompleteListener { - void onComplete(); // 当同步完成时调用 - } - - private Context mContext; // 应用程序上下文 - private NotificationManager mNotifiManager; // 通知管理器 - private GTaskManager mTaskManager; // Google任务管理器 - private OnCompleteListener mOnCompleteListener; // 完成监听器 - - /** - * 构造函数。 - * @param context 上下文对象。 - * @param listener 完成监听器。 - */ - public GTaskASyncTask(Context context, OnCompleteListener listener) { - mContext = context; - mOnCompleteListener = listener; - mNotifiManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); - mTaskManager = GTaskManager.getInstance(); - } - - /** - * 取消同步。 - */ - public void cancelSync() { - mTaskManager.cancelSync(); - } - - /** - * 发布进度信息。 - * @param message 进度信息。 - */ - public void publishProgess(String message) { - publishProgress(new String[] { message }); - } - - /** - * 显示通知。 - * @param tickerId 通知的ID。 - * @param content 通知内容。 - */ - private void showNotification(int tickerId, String content) { - Notification notification = new Notification(R.drawable.notification, mContext.getString(tickerId), System.currentTimeMillis()); - notification.defaults = Notification.DEFAULT_LIGHTS; // 设置默认灯光 - notification.flags = Notification.FLAG_AUTO_CANCEL; // 设置通知自动取消 - PendingIntent pendingIntent; // 待决意图 - - // 根据tickerId设置不同的待决意图 - if (tickerId != R.string.ticker_success) { - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0); - } else { - pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesListActivity.class), 0); - } - notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, pendingIntent); // 设置通知信息 - mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); // 显示通知 - } - - /** - * 执行同步操作。 - * @return 同步结果状态。 - */ - @Override - protected Integer doInBackground(Void... unused) { - publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity.getSyncAccountName(mContext))); - return mTaskManager.sync(mContext, this); // 同步任务 - } - - /** - * 更新进度信息。 - * @param progress 进度信息数组。 - */ - @Override - protected void onProgressUpdate(String... progress) { - showNotification(R.string.ticker_syncing, progress[0]); // 显示同步中的通知 - if (mContext instanceof GTaskSyncService) { - ((GTaskSyncService) mContext).sendBroadcast(progress[0]); // 如果上下文是GTaskSyncService,发送广播 - } - } - - /** - * 同步完成后的操作。 - * @param result 同步结果状态。 - */ - @Override - protected void onPostExecute(Integer result) { - // 根据结果状态显示不同的通知 - if (result == GTaskManager.STATE_SUCCESS) { - showNotification(R.string.ticker_success, mContext.getString(R.string.success_sync_account, mTaskManager.getSyncAccount())); - NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); // 设置最后同步时间 - } else if (result == GTaskManager.STATE_NETWORK_ERROR) { - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); - } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { - showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); - } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { - showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled)); - } - // 如果设置了完成监听器,则在新线程中调用onComplete方法 - if (mOnCompleteListener != null) { - new Thread(new Runnable() { - public void run() { - mOnCompleteListener.onComplete(); - } - }).start(); - } - } - } \ No newline at end of file +/** + * 类注释 +GTaskASyncTask 类是一个异步任务类,用于同步 Google 任务。它继承自 AsyncTask,提供了后台同步 Google 任务的功能,并在同步过程中和完成后更新通知。 +常量定义 +GTASK_SYNC_NOTIFICATION_ID:同步通知的 ID。 +接口定义 +OnCompleteListener:完成监听器接口,用于在同步完成后执行特定的操作。 +成员变量 +mContext:应用程序上下文。 +mNotifiManager:通知管理器。 +mTaskManager:Google 任务管理器。 +mOnCompleteListener:完成监听器。 +构造函数 +GTaskASyncTask(Context context, OnCompleteListener listener):构造函数,初始化上下文、完成监听器、通知管理器和 Google 任务管理器。 +方法定义 +cancelSync():取消同步操作,调用 Google 任务管理器的 cancelSync 方法。 +publishProgess(String message):发布进度信息,调用 publishProgress 方法。 +showNotification(int tickerId, String content):显示通知,根据 tickerId 设置不同的待决意图并显示通知。 +doInBackground(Void... unused):执行同步操作,调用 Google 任务管理器的 sync 方法。 +onProgressUpdate(String... progress):更新进度信息,显示同步中的通知,如果上下文是 GTaskSyncService,发送广播。 +onPostExecute(Integer result):同步完成后的操作,根据结果状态显示不同的通知,如果设置了完成监听器,则在新线程中调用 onComplete 方法。 + */ \ No newline at end of file diff --git a/src/java/net/micode/notes/gtask/remote/GTaskClient.java b/src/java/net/micode/notes/gtask/remote/GTaskClient.java index ad4ead0..8dcc480 100644 --- a/src/java/net/micode/notes/gtask/remote/GTaskClient.java +++ b/src/java/net/micode/notes/gtask/remote/GTaskClient.java @@ -1,19 +1,3 @@ -/* - * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package net.micode.notes.gtask.remote; import android.accounts.Account; @@ -60,45 +44,32 @@ import java.util.zip.GZIPInputStream; import java.util.zip.Inflater; import java.util.zip.InflaterInputStream; - +/** + * GTaskClient 类用于与 Google 任务服务进行交互。 + * 它提供了登录、创建任务、创建任务列表、提交更新、移动任务、删除节点、获取任务列表和获取特定任务列表中的任务等功能。 + */ public class GTaskClient { - // 类名的简写,用于日志输出 - private static final String TAG = GTaskClient.class.getSimpleName(); - - // Google任务的URL地址 - private static final String GTASK_URL = "https://mail.google.com/tasks/"; - private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; - private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; - - // 单例对象 - private static GTaskClient mInstance = null; - - // HTTP客户端 - private DefaultHttpClient mHttpClient; - - // 获取和发布任务的URL - private String mGetUrl; - private String mPostUrl; - - // 客户端版本号 - private long mClientVersion; - - // 登录状态 - private boolean mLoggedin; - - // 上次登录时间 - private long mLastLoginTime; - - // 动作ID - private int mActionId; - - // 账户信息 - private Account mAccount; - - // 更新数组 - private JSONArray mUpdateArray; - - // 私有构造函数,防止外部直接创建对象 + private static final String TAG = GTaskClient.class.getSimpleName(); // 类名的简写,用于日志输出 + + private static final String GTASK_URL = "https://mail.google.com/tasks/"; // Google任务的URL地址 + private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; // 获取任务的URL + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; // 发布任务的URL + + private static GTaskClient mInstance = null; // 单例对象 + + private DefaultHttpClient mHttpClient; // HTTP客户端 + private String mGetUrl; // 获取任务的URL + private String mPostUrl; // 发布任务的URL + private long mClientVersion; // 客户端版本号 + private boolean mLoggedin; // 登录状态 + private long mLastLoginTime; // 上次登录时间 + private int mActionId; // 动作ID + private Account mAccount; // 账户信息 + private JSONArray mUpdateArray; // 更新数组 + + /** + * 私有构造函数,防止外部直接创建对象。 + */ private GTaskClient() { mHttpClient = null; mGetUrl = GTASK_GET_URL; @@ -111,7 +82,10 @@ public class GTaskClient { mUpdateArray = null; } - // 获取单例对象 + /** + * 获取单例对象。 + * @return GTaskClient实例 + */ public static synchronized GTaskClient getInstance() { if (mInstance == null) { mInstance = new GTaskClient(); @@ -119,18 +93,19 @@ public class GTaskClient { return mInstance; } - // 登录方法 + /** + * 登录方法。 + * @param activity Activity对象 + * @return 登录成功返回true,否则返回false + */ public boolean login(Activity activity) { - // 假设cookie会在5分钟后过期,需要重新登录 - final long interval = 1000 * 60 * 5; + final long interval = 1000 * 60 * 5; // 假设cookie会在5分钟后过期,需要重新登录 if (mLastLoginTime + interval < System.currentTimeMillis()) { mLoggedin = false; } // 切换账户后需要重新登录 - if (mLoggedin - && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity - .getSyncAccountName(activity))) { + if (mLoggedin && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity.getSyncAccountName(activity))) { mLoggedin = false; } @@ -150,8 +125,7 @@ public class GTaskClient { } // 如果账户不是Gmail或Googlemail,则尝试使用自定义域名登录 - if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() - .endsWith("googlemail.com"))) { + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase().endsWith("googlemail.com"))) { StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); int index = mAccount.name.indexOf('@') + 1; String suffix = mAccount.name.substring(index); @@ -179,13 +153,16 @@ public class GTaskClient { return true; } - // 获取Google账户的认证令牌 + /** + * 获取Google账户的认证令牌。 + * @param activity Activity对象 + * @param invalidateToken 是否使令牌无效 + * @return 认证令牌 + */ private String loginGoogleAccount(Activity activity, boolean invalidateToken) { String authToken; - // 获取账户管理器 - AccountManager accountManager = AccountManager.get(activity); - // 获取所有Google账户 - Account[] accounts = accountManager.getAccountsByType("com.google"); + AccountManager accountManager = AccountManager.get(activity); // 获取账户管理器 + Account[] accounts = accountManager.getAccountsByType("com.google"); // 获取所有Google账户 // 如果没有Google账户,则返回null if (accounts.length == 0) { @@ -213,13 +190,10 @@ public class GTaskClient { } // 获取认证令牌 - AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, - "goanna_mobile", null, activity, null, null); + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile", null, activity, null, null); try { - // 获取认证令牌的Bundle对象 - Bundle authTokenBundle = accountManagerFuture.getResult(); - // 获取认证令牌 - authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + Bundle authTokenBundle = accountManagerFuture.getResult(); // 获取认证令牌的Bundle对象 + authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); // 获取认证令牌 // 如果需要,则使令牌无效并重新登录 if (invalidateToken) { accountManager.invalidateAuthToken("com.google", authToken); @@ -233,443 +207,461 @@ public class GTaskClient { return authToken; } -} - - // 尝试使用给定的认证令牌登录Google任务 -private boolean tryToLoginGtask(Activity activity, String authToken) { - // 如果使用给定的认证令牌登录失败 - if (!loginGtask(authToken)) { - // 可能认证令牌已过期,现在使令牌无效并再次尝试登录 - authToken = loginGoogleAccount(activity, true); - // 如果获取认证令牌失败 - if (authToken == null) { - Log.e(TAG, "login google account failed"); - return false; - } - // 如果使用新的认证令牌登录失败 + /** + * 尝试使用给定的认证令牌登录Google任务。 + * @param activity Activity对象 + * @param authToken 认证令牌 + * @return 登录成功返回true,否则返回false + */ + private boolean tryToLoginGtask(Activity activity, String authToken) { + // 如果使用给定的认证令牌登录失败 if (!loginGtask(authToken)) { - Log.e(TAG, "login gtask failed"); - return false; - } - } - return true; -} - -// 使用给定的认证令牌登录Google任务 -private boolean loginGtask(String authToken) { - // 设置连接超时和套接字超时的时间 - int timeoutConnection = 10000; - int timeoutSocket = 15000; - HttpParams httpParameters = new BasicHttpParams(); - HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); - HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); - // 创建HTTP客户端 - mHttpClient = new DefaultHttpClient(httpParameters); - // 创建本地Cookie存储 - BasicCookieStore localBasicCookieStore = new BasicCookieStore(); - mHttpClient.setCookieStore(localBasicCookieStore); - // 设置HTTP协议参数 - HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); - - // 登录Google任务 - try { - // 构建登录URL - String loginUrl = mGetUrl + "?auth=" + authToken; - HttpGet httpGet = new HttpGet(loginUrl); - // 执行HTTP GET请求 - HttpResponse response = mHttpClient.execute(httpGet); - - // 获取Cookie - List cookies = mHttpClient.getCookieStore().getCookies(); - boolean hasAuthCookie = false; - for (Cookie cookie : cookies) { - // 检查是否存在认证Cookie - if (cookie.getName().contains("GTL")) { - hasAuthCookie = true; + // 可能认证令牌已过期,现在使令牌无效并再次尝试登录 + authToken = loginGoogleAccount(activity, true); + // 如果获取认证令牌失败 + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; } - } - if (!hasAuthCookie) { - Log.w(TAG, "it seems that there is no auth cookie"); - } - // 获取客户端版本 - String resString = getResponseContent(response.getEntity()); - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); + // 如果使用新的认证令牌登录失败 + if (!loginGtask(authToken)) { + Log.e(TAG, "login gtask failed"); + return false; + } } - JSONObject js = new JSONObject(jsString); - mClientVersion = js.getLong("v"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - return false; - } catch (Exception e) { - // 捕获所有异常 - Log.e(TAG, "httpget gtask_url failed"); - return false; + return true; } - return true; -} + /** + * 使用给定的认证令牌登录Google任务。 + * @param authToken 认证令牌 + * @return 登录成功返回true,否则返回false + */ + private boolean loginGtask(String authToken) { + int timeoutConnection = 10000; // 设置连接超时时间 + int timeoutSocket = 15000; // 设置套接字超时时间 + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + mHttpClient = new DefaultHttpClient(httpParameters); // 创建HTTP客户端 + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + mHttpClient.setCookieStore(localBasicCookieStore); + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // 设置HTTP协议参数 -// 获取动作ID -private int getActionId() { - // 返回并递增动作ID - return mActionId++; -} + try { + String loginUrl = mGetUrl + "?auth=" + authToken; // 构建登录URL + HttpGet httpGet = new HttpGet(loginUrl); + HttpResponse response = mHttpClient.execute(httpGet); // 执行HTTP GET请求 + + List cookies = mHttpClient.getCookieStore().getCookies(); + boolean hasAuthCookie = false; + for (Cookie cookie : cookies) { + // 检查是否存在认证Cookie + if (cookie.getName().contains("GTL")) { + hasAuthCookie = true; + } + } + if (!hasAuthCookie) { + Log.w(TAG, "it seems that there is no auth cookie"); + } -// 创建HTTP POST请求 -private HttpPost createHttpPost() { - HttpPost httpPost = new HttpPost(mPostUrl); - // 设置请求头 - httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); - httpPost.setHeader("AT", "1"); - return httpPost; -} + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } catch (Exception e) { + // 捕获所有异常 + Log.e(TAG, "httpget gtask_url failed"); + return false; + } -// 获取HTTP响应的内容 -private String getResponseContent(HttpEntity entity) throws IOException { - String contentEncoding = null; - // 获取内容编码 - if (entity.getContentEncoding() != null) { - contentEncoding = entity.getContentEncoding().getValue(); - Log.d(TAG, "encoding: " + contentEncoding); + return true; } - InputStream input = entity.getContent(); - // 根据内容编码解压缩响应内容 - if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { - input = new GZIPInputStream(entity.getContent()); - } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { - Inflater inflater = new Inflater(true); - input = new InflaterInputStream(entity.getContent(), inflater); + /** + * 获取动作ID。 + * @return 动作ID + */ + private int getActionId() { + return mActionId++; // 返回并递增动作ID } - try { - // 读取响应内容 - InputStreamReader isr = new InputStreamReader(input); - BufferedReader br = new BufferedReader(isr); - StringBuilder sb = new StringBuilder(); + /** + * 创建HTTP POST请求。 + * @return HttpPost对象 + */ + private HttpPost createHttpPost() { + HttpPost httpPost = new HttpPost(mPostUrl); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpPost.setHeader("AT", "1"); + return httpPost; + } + + /** + * 获取HTTP响应的内容。 + * @param entity HttpEntity对象 + * @return 响应内容 + * @throws IOException IO异常 + */ + private String getResponseContent(HttpEntity entity) throws IOException { + String contentEncoding = null; + if (entity.getContentEncoding() != null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } - while (true) { - String buff = br.readLine(); - if (buff == null) { - return sb.toString(); + InputStream input = entity.getContent(); + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { + input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater); + } + + try { + InputStreamReader isr = new InputStreamReader(input); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + + while (true) { + String buff = br.readLine(); + if (buff == null) { + return sb.toString(); + } + sb = sb.append(buff); } - sb = sb.append(buff); + } finally { + input.close(); } - } finally { - // 关闭输入流 - input.close(); } -} - // 发送POST请求 -private JSONObject postRequest(JSONObject js) throws NetworkFailureException { - // 如果未登录,则抛出异常 - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); - } + /** + * 发送POST请求。 + * @param js JSON对象 + * @return 响应的JSON对象 + * @throws NetworkFailureException 网络异常 + */ + private JSONObject postRequest(JSONObject js) throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } - // 创建HTTP POST请求 - HttpPost httpPost = createHttpPost(); - try { - // 创建参数列表 - LinkedList list = new LinkedList(); - list.add(new BasicNameValuePair("r", js.toString())); - // 创建URL编码的表单实体 - UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); - httpPost.setEntity(entity); - - // 执行POST请求 - HttpResponse response = mHttpClient.execute(httpPost); - // 获取响应内容 - String jsString = getResponseContent(response.getEntity()); - // 将响应内容转换为JSON对象 - return new JSONObject(jsString); - - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("postRequest failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("unable to convert response content to jsonobject"); - } catch (Exception e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("error occurs when posting request"); + HttpPost httpPost = createHttpPost(); + try { + LinkedList list = new LinkedList(); + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + httpPost.setEntity(entity); + + HttpResponse response = mHttpClient.execute(httpPost); + String jsString = getResponseContent(response.getEntity()); + return new JSONObject(jsString); + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("unable to convert response content to jsonobject"); + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("error occurs when posting request"); + } } -} -// 创建任务 -public void createTask(Task task) throws NetworkFailureException { - // 提交更新 - commitUpdate(); - try { - // 创建JSON对象 - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // 添加创建任务的动作 - actionList.put(task.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // 设置客户端版本 - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // 发送POST请求 - JSONObject jsResponse = postRequest(jsPost); - // 获取响应结果 - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - // 设置任务的GID - task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create task: handing jsonobject failed"); - } -} + /** + * 创建任务。 + * @param task Task对象 + * @throws NetworkFailureException 网络异常 + */ + public void createTask(Task task) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + actionList.put(task.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); -// 创建任务列表 -public void createTaskList(TaskList tasklist) throws NetworkFailureException { - // 提交更新 - commitUpdate(); - try { - // 创建JSON对象 - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // 添加创建任务列表的动作 - actionList.put(tasklist.getCreateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // 设置客户端版本 - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // 发送POST请求 - JSONObject jsResponse = postRequest(jsPost); - // 获取响应结果 - JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( - GTaskStringUtils.GTASK_JSON_RESULTS).get(0); - // 设置任务列表的GID - tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); - - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("create tasklist: handing jsonobject failed"); + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create task: handing jsonobject failed"); + } } -} -// 提交更新 -public void commitUpdate() throws NetworkFailureException { - // 如果存在更新数组 - if (mUpdateArray != null) { + /** + * 创建任务列表。 + * @param tasklist TaskList对象 + * @throws NetworkFailureException 网络异常 + */ + public void createTaskList(TaskList tasklist) throws NetworkFailureException { + commitUpdate(); try { - // 创建JSON对象 JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); - // 添加更新动作列表 - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); - - // 设置客户端版本 + actionList.put(tasklist.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - // 发送POST请求 - postRequest(jsPost); - // 清空更新数组 - mUpdateArray = null; + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); - throw new ActionFailureException("commit update: handing jsonobject failed"); + throw new ActionFailureException("create tasklist: handing jsonobject failed"); } } -} -// 添加更新节点 -public void addUpdateNode(Node node) throws NetworkFailureException { - // 如果节点不为空 - if (node != null) { - // 如果更新项过多,则提交更新 - if (mUpdateArray != null && mUpdateArray.length() > 10) { - commitUpdate(); + /** + * 提交更新。 + * @throws NetworkFailureException 网络异常 + */ + public void commitUpdate() throws NetworkFailureException { + if (mUpdateArray != null) { + try { + JSONObject jsPost = new JSONObject(); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("commit update: handing jsonobject failed"); + } } - - // 如果更新数组为空,则创建新的数组 - if (mUpdateArray == null) - mUpdateArray = new JSONArray(); - // 添加更新动作 - mUpdateArray.put(node.getUpdateAction(getActionId())); } -} -// 移动任务 -public void moveTask(Task task, TaskList preParent, TaskList curParent) - throws NetworkFailureException { - // 提交更新 - commitUpdate(); - try { - // 创建JSON对象 - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // 添加移动任务的动作 - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); - if (preParent == curParent && task.getPriorSibling() != null) { - // 如果在同一个任务列表中移动且不是第一个,则添加前一个兄弟节点的ID - action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + /** + * 添加更新节点。 + * @param node Node对象 + * @throws NetworkFailureException 网络异常 + */ + public void addUpdateNode(Node node) throws NetworkFailureException { + if (node != null) { + if (mUpdateArray != null && mUpdateArray.length() > 10) { + commitUpdate(); + } + + if (mUpdateArray == null) { + mUpdateArray = new JSONArray(); + } + mUpdateArray.put(node.getUpdateAction(getActionId())); } - action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); - action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); - if (preParent != curParent) { - // 如果在不同任务列表之间移动,则添加目标列表的ID - action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + + /** + * 移动任务。 + * @param task Task对象 + * @param preParent 原始父任务列表 + * @param curParent 当前父任务列表 + * @throws NetworkFailureException 网络异常 + */ + public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling() != null) { + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + } + action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); + action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); + if (preParent != curParent) { + action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("move task: handing jsonobject failed"); } - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + } - // 设置客户端版本 - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + /** + * 删除节点。 + * @param node Node对象 + * @throws NetworkFailureException 网络异常 + */ + public void deleteNode(Node node) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); - // 发送POST请求 - postRequest(jsPost); + node.setDeleted(true); + actionList.put(node.getUpdateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("move task: handing jsonobject failed"); + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("delete node: handing jsonobject failed"); + } } -} - // 删除节点 -public void deleteNode(Node node) throws NetworkFailureException { - // 提交所有挂起的更新 - commitUpdate(); - try { - // 创建JSON对象来构建请求体 - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - - // 设置节点为已删除,并添加更新动作到动作列表中 - node.setDeleted(true); - actionList.put(node.getUpdateAction(getActionId())); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // 设置客户端版本号 - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // 发送请求 - postRequest(jsPost); - // 清空更新数组 - mUpdateArray = null; - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("delete node: handing jsonobject failed"); - } -} + /** + * 获取任务列表。 + * @return 任务列表的JSON数组 + * @throws NetworkFailureException 网络异常 + */ + public JSONArray getTaskLists() throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } -// 获取任务列表 -public JSONArray getTaskLists() throws NetworkFailureException { - // 如果未登录,则抛出异常 - if (!mLoggedin) { - Log.e(TAG, "please login first"); - throw new ActionFailureException("not logged in"); + try { + HttpGet httpGet = new HttpGet(mGetUrl); + HttpResponse response = mHttpClient.execute(httpGet); + + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task lists: handing jasonobject failed"); + } } - try { - // 创建HTTP GET请求 - HttpGet httpGet = new HttpGet(mGetUrl); - HttpResponse response = null; - response = mHttpClient.execute(httpGet); - - // 获取任务列表 - String resString = getResponseContent(response.getEntity()); - String jsBegin = "_setup("; - String jsEnd = ")}"; - int begin = resString.indexOf(jsBegin); - int end = resString.lastIndexOf(jsEnd); - String jsString = null; - if (begin != -1 && end != -1 && begin < end) { - jsString = resString.substring(begin + jsBegin.length(), end); + /** + * 获取特定任务列表中的任务。 + * @param listGid 任务列表的GID + * @return 任务的JSON数组 + * @throws NetworkFailureException 网络异常 + */ + public JSONArray getTaskList(String listGid) throws NetworkFailureException { + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + JSONObject jsResponse = postRequest(jsPost); + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task list: handing jsonobject failed"); } - JSONObject js = new JSONObject(jsString); - // 返回任务列表的JSON数组 - return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); - } catch (ClientProtocolException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (IOException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new NetworkFailureException("gettasklists: httpget failed"); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task lists: handing jasonobject failed"); } -} -// 获取特定任务列表中的任务 -public JSONArray getTaskList(String listGid) throws NetworkFailureException { - // 提交所有挂起的更新 - commitUpdate(); - try { - // 创建JSON对象来构建请求体 - JSONObject jsPost = new JSONObject(); - JSONArray actionList = new JSONArray(); - JSONObject action = new JSONObject(); - - // 构建获取任务的动作 - action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, - GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); - action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); - action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); - action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); - actionList.put(action); - jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); - - // 设置客户端版本号 - jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); - - // 发送请求并获取响应 - JSONObject jsResponse = postRequest(jsPost); - // 返回任务的JSON数组 - return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); - } catch (JSONException e) { - Log.e(TAG, e.toString()); - e.printStackTrace(); - throw new ActionFailureException("get task list: handing jsonobject failed"); + /** + * 获取用于同步的账户。 + * @return 账户信息 + */ + public Account getSyncAccount() { + return mAccount; } -} -// 获取用于同步的账户 -public Account getSyncAccount() { - return mAccount; + /** + * 重置更新数组。 + */ + public void resetUpdateArray() { + mUpdateArray = null; + } } -// 重置更新数组 -public void resetUpdateArray() { - mUpdateArray = null; -} +/** + * 类注释 +GTaskClient 类用于与 Google 任务服务进行交互。它提供了登录、创建任务、创建任务列表、提交更新、移动任务、删除节点、获取任务列表和获取特定任务列表中的任务等功能。 +常量定义 +TAG:类名的简写,用于日志输出。 +GTASK_URL、GTASK_GET_URL、GTASK_POST_URL:Google 任务的 URL 地址。 +成员变量 +mInstance:单例对象。 +mHttpClient:HTTP 客户端。 +mGetUrl、mPostUrl:获取和发布任务的 URL。 +mClientVersion:客户端版本号。 +mLoggedin:登录状态。 +mLastLoginTime:上次登录时间。 +mActionId:动作 ID。 +mAccount:账户信息。 +mUpdateArray:更新数组。 +构造函数 +GTaskClient:私有构造函数,防止外部直接创建对象。 +方法定义 +getInstance:获取单例对象。 +login:登录方法,检查登录状态并获取认证令牌。 +loginGoogleAccount:获取 Google 账户的认证令牌。 +tryToLoginGtask:尝试使用给定的认证令牌登录 Google 任务。 +loginGtask:使用给定的认证令牌登录 Google 任务。 +getActionId:获取动作 ID。 +createHttpPost:创建 HTTP POST 请求。 +getResponseContent:获取 HTTP 响应的内容。 +postRequest:发送 POST 请求。 +createTask:创建任务。 +createTaskList:创建任务列表。 +commitUpdate:提交更新。 +addUpdateNode:添加更新节点。 +moveTask:移动任务。 +deleteNode:删除节点。 +getTaskLists:获取任务列表。 +getTaskList:获取特定任务列表中的任务。 +getSyncAccount:获取用于同步的账户。 +resetUpdateArray:重置更新数组。 + */ \ No newline at end of file