zhangqing 3 weeks ago
parent 14c079710e
commit 8b31f5f248

@ -27,183 +27,112 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* GTaskASyncTask
* AsyncTaskGoogle Tasks
*
*
* AsyncTask
* Void -
* String - 使
* Integer -
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
/**
* ID
* Google Tasks
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 同步通知的ID确保唯一性
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
/**
*
*
*/
// 同步完成回调接口
public interface OnCompleteListener {
/**
*
*/
void onComplete();
void onComplete(); // 同步完成时调用
}
// 上下文对象
private Context mContext;
// 通知管理器,用于显示同步进度通知
private NotificationManager mNotifiManager;
// Google Tasks管理器执行实际的同步操作
private GTaskManager mTaskManager;
// 同步完成监听器
private OnCompleteListener mOnCompleteListener;
private Context mContext; // 上下文对象
private NotificationManager mNotifiManager; // 通知管理器
private GTaskManager mTaskManager; // 任务管理器
private OnCompleteListener mOnCompleteListener; // 完成监听器
/**
*
*
* @param context
* @param listener
*/
// 构造函数
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
// 获取通知管理器服务
mContext = context; // 保存上下文
mOnCompleteListener = listener; // 保存完成监听器
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
// 获取Google Tasks管理器单例
mTaskManager = GTaskManager.getInstance();
.getSystemService(Context.NOTIFICATION_SERVICE); // 获取通知管理器服务
mTaskManager = GTaskManager.getInstance(); // 获取任务管理器单例
}
/**
*
* GTaskManagercancelSync
*/
// 取消同步操作
public void cancelSync() {
mTaskManager.cancelSync();
mTaskManager.cancelSync(); // 委托给任务管理器取消同步
}
/**
*
* publishProgress
*
* @param message
*/
// 发布同步进度
public void publishProgess(String message) {
publishProgress(new String[] {
message
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; // 点击后自动取消
.getString(tickerId), System.currentTimeMillis()); // 设置图标、文本和时间戳
notification.defaults = Notification.DEFAULT_LIGHTS; // 设置默认灯光效果
notification.flags = Notification.FLAG_AUTO_CANCEL; // 设置点击后自动取消
PendingIntent pendingIntent;
// 根据通知类型设置不同的点击意图
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);
// 设置通知的详细信息
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent); // 设置标题、内容和点击意图
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); // 显示通知
}
/**
*
* AsyncTask线
*
* @param unused 使
* @return
*/
// 后台执行同步任务
@Override
protected Integer doInBackground(Void... unused) {
// 发布登录进度消息
// 发布登录进度
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
// 执行同步操作,将当前异步任务作为进度更新回调
return mTaskManager.sync(mContext, this);
.getSyncAccountName(mContext))); // 显示正在登录指定账户的进度
return mTaskManager.sync(mContext, this); // 执行同步操作并返回结果状态
}
/**
*
* UI线
*
* @param progress
*/
// 更新同步进度
@Override
protected void onProgressUpdate(String... progress) {
// 显示同步进行中的通知
showNotification(R.string.ticker_syncing, progress[0]);
// 如果上下文是GTaskSyncService发送广播通知进度
showNotification(R.string.ticker_syncing, progress[0]); // 显示同步中的通知
if (mContext instanceof GTaskSyncService) {
// 如果上下文是同步服务,发送广播通知进度
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
/**
*
* UI线
*
* @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());
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));
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));
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));
.getString(R.string.error_sync_cancelled)); // 显示取消通知
}
// 调用同步完成监听器
// 通知监听器同步已完成
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
// 在新线程中执行完成回调避免阻塞UI线程
mOnCompleteListener.onComplete();
mOnCompleteListener.onComplete(); // 在新线程中调用完成回调
}
}).start();
}

@ -60,698 +60,534 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* GTaskClient
* Google Tasks APIGoogle Tasks
* 使
*/
public class GTaskClient {
// 日志标签
private static final String TAG = GTaskClient.class.getSimpleName();
private static final String TAG = GTaskClient.class.getSimpleName(); // 日志标签
// Google Tasks基础URL用于普通访问
// Google Tasks API URL常量
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// Google Tasks获取数据的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// Google Tasks提交数据的URL
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;
// 提交数据的URL可能根据账户域名变化
private String mPostUrl;
// 客户端版本号(从服务器获取)
private long mClientVersion;
// 登录状态标志
private boolean mLoggedin;
// 最后登录时间戳
private long mLastLoginTime;
// 动作ID计数器用于标识每个请求
private int mActionId;
// 当前同步的Google账户
private Account mAccount;
// 待提交的更新数组(批量更新用)
private JSONArray mUpdateArray;
/**
*
*
*/
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; // 单例实例
// HTTP客户端和相关参数
private DefaultHttpClient mHttpClient; // HTTP客户端实例
private String mGetUrl; // 动态生成的GET URL
private String mPostUrl; // 动态生成的POST URL
private long mClientVersion; // 客户端版本号,从服务器获取
private boolean mLoggedin; // 登录状态标志
private long mLastLoginTime; // 上次登录时间
private int mActionId; // 操作ID计数器用于生成唯一的操作ID
private Account mAccount; // 当前登录的Google账户
private JSONArray mUpdateArray; // 批量更新操作的JSON数组
private GTaskClient() {
// 初始化所有成员变量
mHttpClient = null;
mGetUrl = GTASK_GET_URL; // 默认获取URL
mPostUrl = GTASK_POST_URL; // 默认提交URL
mClientVersion = -1; // 未获取版本号
mLoggedin = false; // 未登录状态
mLastLoginTime = 0; // 最后登录时间为0
mActionId = 1; // 动作ID从1开始
mAccount = null; // 未设置账户
mUpdateArray = null; // 无待提交更新
mGetUrl = GTASK_GET_URL; // 默认GET URL
mPostUrl = GTASK_POST_URL; // 默认POST URL
mClientVersion = -1; // 未初始化的版本号
mLoggedin = false; // 初始状态为未登录
mLastLoginTime = 0; // 初始登录时间为0
mActionId = 1; // 操作ID从1开始
mAccount = null; // 初始账户为空
mUpdateArray = null; // 初始更新数组为空
}
/**
* GTaskClient
*
* @return GTaskClient
*/
// 获取单例实例
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
mInstance = new GTaskClient(); // 第一次调用时创建实例
}
return mInstance;
}
/**
* Google Tasks
* GoogleTasks
*
* @param activity
* @return
*/
// 登录方法,返回登录是否成功
public boolean login(Activity activity) {
// 假设Cookie在5分钟后过期需要重新登录
final long interval = 1000 * 60 * 5; // 5分钟
// 检查Cookie是否过期假设5分钟后过期
final long interval = 1000 * 60 * 5; // 5分钟的毫秒数
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; // 超过5分钟标记为未登录
mLoggedin = false; // 如果超过5分钟标记为未登录
}
// 切换账户后需要重新登录
// 检查账户是否切换,需要重新登录
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false; // 账户不匹配,标记为未登录
mLoggedin = false; // 账户已切换,需要重新登录
}
// 如果已经登录,直接返回成功
if (mLoggedin) {
Log.d(TAG, "already logged in");
Log.d(TAG, "already logged in"); // 已经登录,直接返回
return true;
}
// 记录当前时间为最后登录时间
mLastLoginTime = System.currentTimeMillis();
// 获取Google账户认证令牌
String authToken = loginGoogleAccount(activity, false);
mLastLoginTime = System.currentTimeMillis(); // 更新最后登录时间
String authToken = loginGoogleAccount(activity, false); // 获取Google账户授权令牌
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false; // 获取认证令牌失败
Log.e(TAG, "login google account failed"); // 获取授权令牌失败
return false;
}
// 如果账户不是gmail.com或googlemail.com使用自定义域名登录
// 如果不是gmail.com或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);
url.append(suffix + "/");
mGetUrl = url.toString() + "ig"; // 设置自定义获取URL
mPostUrl = url.toString() + "r/ig"; // 设置自定义提交URL
// 尝试使用自定义域名登录
if (tryToLoginGtask(activity, authToken)) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); // 构建自定义域名URL
int index = mAccount.name.indexOf('@') + 1; // 找到@符号位置
String suffix = mAccount.name.substring(index); // 提取域名后缀
url.append(suffix + "/"); // 添加域名后缀
mGetUrl = url.toString() + "ig"; // 设置自定义GET URL
mPostUrl = url.toString() + "r/ig"; // 设置自定义POST URL
if (tryToLoginGtask(activity, authToken)) { // 尝试使用自定义域名登录
mLoggedin = true; // 登录成功
}
}
// 如果自定义域名登录失败或不是自定义域名尝试使用官方URL登录
// 如果自定义域名登录失败,尝试使用Google官方URL登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; // 恢复默认获取URL
mPostUrl = GTASK_POST_URL; // 恢复默认提交URL
if (!tryToLoginGtask(activity, authToken)) {
mGetUrl = GTASK_GET_URL; // 重置为默认GET URL
mPostUrl = GTASK_POST_URL; // 重置为默认POST URL
if (!tryToLoginGtask(activity, authToken)) { // 尝试使用官方URL登录
return false; // 登录失败
}
}
mLoggedin = true; // 标记为已登录
return true; // 登录成功
return true; // 登录成功
}
/**
* Google
*
* @param activity
* @param invalidateToken 使
* @return null
*/
// 登录Google账户并获取授权令牌
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账户
if (accounts.length == 0) {
Log.e(TAG, "there is no available google account");
return null; // 没有可用的Google账户
Log.e(TAG, "there is no available google account"); // 没有可用的Google账户
return null;
}
// 从设置中获取同步账户名称
// 获取设置中配置的同步账户名
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null;
// 查找与设置中名称匹配的账户
for (Account a : accounts) {
if (a.name.equals(accountName)) {
if (a.name.equals(accountName)) { // 查找匹配的账户
account = a;
break;
}
}
if (account != null) {
mAccount = account; // 设置当前账户
} else {
Log.e(TAG, "unable to get an account with the same name in the settings");
return null; // 找不到匹配的账户
Log.e(TAG, "unable to get an account with the same name in the settings"); // 未找到匹配账户
return null;
}
// 获取认证令牌
// 获取授权令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
"goanna_mobile", null, activity, null, null); // 请求授权令牌
try {
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
// 如果需要使令牌失效
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
// 重新获取新令牌
return loginGoogleAccount(activity, false);
Bundle authTokenBundle = accountManagerFuture.getResult(); // 获取结果
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); // 提取授权令牌
if (invalidateToken) { // 如果需要使令牌失效
accountManager.invalidateAuthToken("com.google", authToken); // 使当前令牌失效
loginGoogleAccount(activity, false); // 重新获取令牌
}
} catch (Exception e) {
Log.e(TAG, "get auth token failed");
authToken = null; // 获取令牌失败
Log.e(TAG, "get auth token failed"); // 获取授权令牌失败
authToken = null;
}
return authToken;
return authToken; // 返回授权令牌
}
/**
* Google Tasks
*
* @param activity
* @param authToken
* @return
*/
// 尝试登录Google Tasks
private boolean tryToLoginGtask(Activity activity, String authToken) {
// 第一次尝试登录
if (!loginGtask(authToken)) {
// 令牌可能已过期,使令牌失效并重新获取
authToken = loginGoogleAccount(activity, true);
if (!loginGtask(authToken)) { // 第一次登录尝试
// 授权令牌可能已过期,尝试重新获取令牌并登录
authToken = loginGoogleAccount(activity, true); // 重新获取授权令牌
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false; // 重新获取令牌失败
Log.e(TAG, "login google account failed"); // 重新获取令牌失败
return false;
}
// 使用新令牌再次尝试登录
if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed");
return false; // 再次登录失败
if (!loginGtask(authToken)) { // 使用新令牌再次尝试登录
Log.e(TAG, "login gtask failed"); // 登录失败
return false;
}
}
return true; // 登录成功
}
/**
* Google Tasks
* HTTPCookie
*
* @param authToken
* @return
*/
// 实际的Google Tasks登录逻辑
private boolean loginGtask(String authToken) {
// 设置HTTP连接参数
int timeoutConnection = 10000; // 连接超时10秒
int timeoutSocket = 15000; // 套接字超时15秒
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// 创建HTTP客户端
mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
int timeoutConnection = 10000; // 连接超时时间10秒
int timeoutSocket = 15000; // Socket超时时间15秒
HttpParams httpParameters = new BasicHttpParams(); // 创建HTTP参数
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 设置Socket超时
mHttpClient = new DefaultHttpClient(httpParameters); // 创建HTTP客户端
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); // 创建Cookie存储
mHttpClient.setCookieStore(localBasicCookieStore); // 设置Cookie存储
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // 禁用Expect-Continue
// 登录Google Tasks
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
String loginUrl = mGetUrl + "?auth=" + authToken; // 构建登录URL
HttpGet httpGet = new HttpGet(loginUrl); // 创建GET请求
HttpResponse response = null;
response = mHttpClient.execute(httpGet); // 执行GET请求
response = mHttpClient.execute(httpGet); // 执行HTTP请求
// 检查是否获取到认证Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
// 检查Cookie中是否包含认证信息
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); // 获取所有Cookie
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
if (cookie.getName().contains("GTL")) {
hasAuthCookie = true; // 找到认证Cookie
if (cookie.getName().contains("GTL")) { // 查找包含"GTL"的CookieGoogle Tasks认证
hasAuthCookie = true;
}
}
if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie");
Log.w(TAG, "it seems that there is no auth cookie"); // 警告未找到认证Cookie
}
// 从响应中解析客户端版本号
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
// 从响应中提取客户端版本号
String resString = getResponseContent(response.getEntity()); // 获取响应内容
String jsBegin = "_setup("; // JavaScript响应开始标记
String jsEnd = ")}</script>"; // JavaScript响应结束标记
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 (begin != -1 && end != -1 && begin < end) { // 确保找到有效位置
jsString = resString.substring(begin + jsBegin.length(), end); // 提取JavaScript字符串
}
JSONObject js = new JSONObject(jsString);
JSONObject js = new JSONObject(jsString); // 解析为JSON对象
mClientVersion = js.getLong("v"); // 获取客户端版本号
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON解析异常
e.printStackTrace();
return false; // JSON解析失败
return false;
} catch (Exception e) {
// 捕获所有异常
Log.e(TAG, "httpget gtask_url failed");
return false; // HTTP请求失败
// 捕获所有其他异常
Log.e(TAG, "httpget gtask_url failed"); // HTTP GET请求失败
return false;
}
return true; // 登录成功
}
/**
* ID
* ID
*
* @return ID
*/
// 获取下一个操作ID
private int getActionId() {
return mActionId++;
return mActionId++; // 返回当前操作ID并递增
}
/**
* HTTP POST
*
*
* @return HttpPost
*/
// 创建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"); // 认证令牌头
HttpPost httpPost = new HttpPost(mPostUrl); // 创建POST请求
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); // 设置内容类型
httpPost.setHeader("AT", "1"); // 设置AT头部认证令牌
return httpPost;
}
/**
* HTTP
* GZIPDeflate
*
* @param entity HTTP
* @return
* @throws IOException
*/
// 从HTTP实体获取响应内容支持GZIP和Deflate压缩
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding);
contentEncoding = entity.getContentEncoding().getValue(); // 获取内容编码
Log.d(TAG, "encoding: " + contentEncoding); // 记录编码类型
}
InputStream input = entity.getContent();
// 根据压缩格式创建相应的输入流
InputStream input = entity.getContent(); // 获取输入流
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent()); // GZIP解压
input = new GZIPInputStream(entity.getContent()); // 如果是GZIP编码使用GZIP输入流
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater); // Deflate解压
Inflater inflater = new Inflater(true); // 创建Inflater对象
input = new InflaterInputStream(entity.getContent(), inflater); // 使用Inflater输入流
}
try {
// 读取响应内容
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
InputStreamReader isr = new InputStreamReader(input); // 创建输入流读取器
BufferedReader br = new BufferedReader(isr); // 创建缓冲读取器
StringBuilder sb = new StringBuilder(); // 创建字符串构建器
while (true) {
String buff = br.readLine();
String buff = br.readLine(); // 读取一行
if (buff == null) {
return sb.toString(); // 读取完成
return sb.toString(); // 读取完成,返回内容
}
sb = sb.append(buff);
sb = sb.append(buff); // 添加到字符串构建器
}
} finally {
input.close(); // 确保关闭输入流
}
}
/**
* POSTGoogle Tasks
*
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
// 发送POST请求到Google Tasks API
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
// 检查登录状态
if (!mLoggedin) {
Log.e(TAG, "please login first");
Log.e(TAG, "please login first"); // 未登录错误
throw new ActionFailureException("not logged in");
}
HttpPost httpPost = createHttpPost();
HttpPost httpPost = createHttpPost(); // 创建POST请求
try {
// 准备请求参数
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString())); // JSON数据作为参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); // 创建参数列表
list.add(new BasicNameValuePair("r", js.toString())); // 添加JSON参数
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); // 创建URL编码实体
httpPost.setEntity(entity); // 设置请求实体
// 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString); // 解析响应为JSON对象
HttpResponse response = mHttpClient.execute(httpPost); // 执行请求
String jsString = getResponseContent(response.getEntity()); // 获取响应内容
return new JSONObject(jsString); // 解析为JSON对象并返回
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // HTTP协议异常
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // IO异常
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON解析异常
e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // 其他异常
e.printStackTrace();
throw new ActionFailureException("error occurs when posting request");
}
}
/**
* Google Tasks
*
* @param task
* @throws NetworkFailureException
*/
// 创建任务
public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); // 先提交所有待更新
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); // 创建操作列表
// 构建动作列表
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 添加创建任务的操作
actionList.put(task.getCreateAction(getActionId())); // 获取任务的创建操作
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求
JSONObject jsResponse = postRequest(jsPost);
// 从响应中提取新任务的ID
JSONObject jsResponse = postRequest(jsPost); // 发送POST请求
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 获取结果数组的第一个元素
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务的GID
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed");
}
}
/**
* Google Tasks
*
* @param tasklist
* @throws NetworkFailureException
*/
// 创建任务列表
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); // 先提交所有待更新
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); // 创建操作列表
// 构建动作列表
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 添加创建任务列表的操作
actionList.put(tasklist.getCreateAction(getActionId())); // 获取任务列表的创建操作
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求
JSONObject jsResponse = postRequest(jsPost);
// 从响应中提取新任务列表的ID
JSONObject jsResponse = postRequest(jsPost); // 发送POST请求
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 获取结果数组的第一个元素
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务列表的GID
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed");
}
}
/**
*
*
*
* @throws NetworkFailureException
*/
// 提交批量更新
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
if (mUpdateArray != null) { // 如果有待提交的更新
try {
JSONObject jsPost = new JSONObject();
JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
// 添加作列表
// 添加作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求
postRequest(jsPost);
postRequest(jsPost); // 发送请求
mUpdateArray = null; // 清空更新数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed");
}
}
}
/**
*
*
*
* @param node
* @throws NetworkFailureException
*/
// 添加节点到更新数组
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// 更新项过多时自动提交最多10项
// 如果更新数组过大超过10个先提交当前更新
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
commitUpdate(); // 提交当前更新
}
// 初始化更新数组(如果为空)
if (mUpdateArray == null)
if (mUpdateArray == null) // 如果更新数组为空,创建新数组
mUpdateArray = new JSONArray();
// 添加更新动作
mUpdateArray.put(node.getUpdateAction(getActionId()));
mUpdateArray.put(node.getUpdateAction(getActionId())); // 添加节点的更新操作
}
}
/**
*
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
// 移动任务
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate(); // 先提交所有待更新
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
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());
// 在同一任务列表内移动时设置前兄弟节点ID
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); // 设置操作类型为移动
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作ID
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); // 设置任务ID
if (preParent == curParent && task.getPriorSibling() != null) {
// 如果是在同一个任务列表中移动且任务不是第一个设置前一个兄弟节点的ID
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());
// 在不同任务列表间移动时设置目标列表ID
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); // 设置源列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); // 设置目标父节点ID
if (preParent != curParent) {
// 如果是在不同任务列表之间移动设置目标列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
actionList.put(action); // 将操作添加到操作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 添加操作列表到请求
// 添加客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求
postRequest(jsPost);
postRequest(jsPost); // 发送请求
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed");
}
}
/**
*
*
* @param node
* @throws NetworkFailureException
*/
// 删除节点
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); // 先提交所有待更新
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
JSONArray actionList = new JSONArray(); // 创建操作列表
// 设置节点为删除状态
node.setDeleted(true);
// 构建更新动作
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 添加删除操作
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);
postRequest(jsPost); // 发送请求
mUpdateArray = null; // 清空更新数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON处理异常
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");
Log.e(TAG, "please login first"); // 未登录错误
throw new ActionFailureException("not logged in");
}
try {
HttpGet httpGet = new HttpGet(mGetUrl);
HttpGet httpGet = new HttpGet(mGetUrl); // 创建GET请求
HttpResponse response = null;
response = mHttpClient.execute(httpGet); // 执行GET请求
// 解析响应内容
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
response = mHttpClient.execute(httpGet); // 执行请求
// 从响应中提取任务列表数据
String resString = getResponseContent(response.getEntity()); // 获取响应内容
String jsBegin = "_setup("; // JavaScript响应开始标记
String jsEnd = ")}</script>"; // JavaScript响应结束标记
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 (begin != -1 && end != -1 && begin < end) { // 确保找到有效位置
jsString = resString.substring(begin + jsBegin.length(), end); // 提取JavaScript字符串
}
JSONObject js = new JSONObject(jsString);
// 提取任务列表数组
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
JSONObject js = new JSONObject(jsString); // 解析为JSON对象
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); // 返回任务列表数组
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // HTTP协议异常
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // IO异常
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON解析异常
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed");
}
}
/**
*
*
* @param listGid Google ID
* @return JSON
* @throws NetworkFailureException
*/
// 获取特定任务列表的所有任务
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); // 先提交所有待更新
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
JSONObject jsPost = new JSONObject(); // 创建POST请求JSON
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);
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); // 设置操作类型为获取所有
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作ID
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); // 设置任务列表ID
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);
JSONObject jsResponse = postRequest(jsPost); // 发送请求
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); // 返回任务数组
} catch (JSONException e) {
Log.e(TAG, e.toString());
Log.e(TAG, e.toString()); // JSON处理异常
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed");
}
}
/**
*
*
* @return Google
*/
// 获取当前同步账户
public Account getSyncAccount() {
return mAccount;
}
/**
*
*
*/
// 重置更新数组
public void resetUpdateArray() {
mUpdateArray = null;
}

Loading…
Cancel
Save