信亚杰 gtask包remote包

xinyajie
XYJ 8 months ago committed by 13864042598
parent 51814cff35
commit 8dd7a9b830

@ -28,47 +28,53 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
// 该类继承自 AsyncTask用于在后台执行与 GTask 同步相关的任务,并在任务执行过程中更新进度、处理结果并显示通知
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 用于标识 GTask 同步通知的 ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 定义任务完成监听器接口
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete();
} }
// 上下文对象,用于获取系统服务和资源
private Context mContext; private Context mContext;
// 通知管理器,用于显示通知
private NotificationManager mNotifiManager; private NotificationManager mNotifiManager;
// GTask 管理器实例,用于执行同步操作
private GTaskManager mTaskManager; private GTaskManager mTaskManager;
// 任务完成监听器实例
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
// 构造函数,初始化相关成员变量
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
// 获取通知管理器服务
mNotifiManager = (NotificationManager) mContext mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE); .getSystemService(Context.NOTIFICATION_SERVICE);
// 获取 GTask 管理器单例实例
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
// 取消同步的方法,调用 GTask 管理器的取消同步方法
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
// 发布进度的方法,调用父类的 publishProgress 方法传递进度信息
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
} }
// 显示通知的私有方法,根据给定的 tickerId 和内容创建并显示通知
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
// 创建通知对象,设置图标、标题和时间
Notification notification = new Notification(R.drawable.notification, mContext Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); .getString(tickerId), System.currentTimeMillis());
// 设置通知默认的灯光效果
notification.defaults = Notification.DEFAULT_LIGHTS; notification.defaults = Notification.DEFAULT_LIGHTS;
// 设置通知自动取消
notification.flags = Notification.FLAG_AUTO_CANCEL; notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent; PendingIntent pendingIntent;
// 根据 tickerId 设置不同的点击意图
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); NotesPreferenceActivity.class), 0);
@ -77,32 +83,40 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); NotesListActivity.class), 0);
} }
// 设置通知的详细信息和点击意图
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent); pendingIntent);
// 显示通知
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
// 重写 doInBackground 方法,在后台线程执行同步任务
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
// 发布登录进度通知
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
// 调用 GTask 管理器的同步方法并返回结果
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
// 重写 onProgressUpdate 方法,在主线程更新进度通知
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
// 显示同步进度通知
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
// 如果上下文是 GTaskSyncService则发送广播传递进度信息
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
} }
// 重写 onPostExecute 方法,在主线程处理同步任务结果
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
// 根据不同的结果显示相应的通知
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); // 设置最后同步时间
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) { } 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) { } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
@ -111,6 +125,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled));
} }
// 如果有任务完成监听器,则在新线程中触发监听器的 onComplete 方法
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {

@ -59,37 +59,39 @@ import java.util.List;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
// 该类是与 Google TasksGTask进行交互的客户端类负责处理登录、任务和任务列表的创建、更新、移动、删除以及获取等操作
public class GTaskClient { public class GTaskClient {
// 日志标签,用于记录类的相关操作信息
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
// Google Tasks 的基础 URL
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/";
// 用于获取任务数据的 URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; 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"; private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 单例模式实例
private static GTaskClient mInstance = null; private static GTaskClient mInstance = null;
// HTTP 客户端实例,用于发送 HTTP 请求
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
// 当前使用的获取任务数据的 URL
private String mGetUrl; private String mGetUrl;
// 当前使用的提交任务操作的 URL
private String mPostUrl; private String mPostUrl;
// 客户端版本号
private long mClientVersion; private long mClientVersion;
// 登录状态
private boolean mLoggedin; private boolean mLoggedin;
// 上次登录时间
private long mLastLoginTime; private long mLastLoginTime;
// 操作 ID用于唯一标识每个操作
private int mActionId; private int mActionId;
// 同步的 Google 账户
private Account mAccount; private Account mAccount;
// 用于存储待提交的更新操作数组
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
// 私有构造函数,初始化成员变量
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -101,23 +103,21 @@ public class GTaskClient {
mAccount = null; mAccount = null;
mUpdateArray = null; mUpdateArray = null;
} }
// 单例模式获取实例的方法
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
} }
return mInstance; return mInstance;
} }
// 登录方法,根据账户状态和设置进行登录操作
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // 假设 cookie 在 5 分钟后过期,需要重新登录
// then we need to re-login
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// 账户切换后需要重新登录
// need to re-login after account switch
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
@ -130,13 +130,13 @@ public class GTaskClient {
} }
mLastLoginTime = System.currentTimeMillis(); mLastLoginTime = System.currentTimeMillis();
// 登录 Google 账户获取授权令牌
String authToken = loginGoogleAccount(activity, false); String authToken = loginGoogleAccount(activity, false);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false;
} }
// 如果账户不是 gmail.com 或 googlemail.com 结尾,使用自定义域名登录 GTask
// login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) { .endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -150,8 +150,8 @@ public class GTaskClient {
mLoggedin = true; mLoggedin = true;
} }
} }
// 使用 Google 官方 URL 登录 GTask
// try to login with google official url
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -159,21 +159,23 @@ public class GTaskClient {
return false; return false;
} }
} }
mLoggedin = true; mLoggedin = true;
return true; return true;
} }
// 登录 Google 账户的私有方法
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
// 获取账户管理器实例
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);
// 获取所有 Google 账户
Account[] accounts = accountManager.getAccountsByType("com.google"); Account[] accounts = accountManager.getAccountsByType("com.google");
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account");
return null; return null;
} }
// 获取同步账户名称
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null; Account account = null;
for (Account a : accounts) { for (Account a : accounts) {
@ -188,8 +190,7 @@ public class GTaskClient {
Log.e(TAG, "unable to get an account with the same name in the settings"); Log.e(TAG, "unable to get an account with the same name in the settings");
return null; return null;
} }
// 获取授权令牌
// get the token now
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
try { try {
@ -206,9 +207,10 @@ public class GTaskClient {
return authToken; return authToken;
} }
// 尝试登录 GTask 的私有方法
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// 如果登录失败,可能是授权令牌过期,重新获取令牌并再次尝试登录
// maybe the auth token is out of date, now let's invalidate the // maybe the auth token is out of date, now let's invalidate the
// token and try again // token and try again
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
@ -224,10 +226,11 @@ public class GTaskClient {
} }
return true; return true;
} }
// 登录 GTask 的私有方法,获取客户端版本号和设置 HTTP 客户端相关参数
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
// 设置 HTTP 请求参数
HttpParams httpParameters = new BasicHttpParams(); HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
@ -236,14 +239,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask // 登录 GTask
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the cookie now // 获取登录后的 cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -255,7 +258,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie");
} }
// get the client version // 获取客户端版本号
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -279,18 +282,18 @@ public class GTaskClient {
return true; return true;
} }
// 获取操作 ID 的方法,每次调用后自增
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++;
} }
// 创建用于提交任务操作的 HttpPost 对象的方法
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("AT", "1"); httpPost.setHeader("AT", "1");
return httpPost; return httpPost;
} }
// 从 HTTP 响应实体中获取响应内容的方法,处理不同的编码格式
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
@ -322,7 +325,7 @@ public class GTaskClient {
input.close(); input.close();
} }
} }
// 提交 POST 请求的方法,将 JSON 数据发送到 GTask 服务器并处理响应
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -336,7 +339,7 @@ public class GTaskClient {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
// execute the post // 执行 POST 请求
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString); return new JSONObject(jsString);
@ -359,21 +362,21 @@ public class GTaskClient {
throw new ActionFailureException("error occurs when posting request"); throw new ActionFailureException("error occurs when posting request");
} }
} }
// 创建任务的方法,将任务创建操作提交到 GTask 服务器
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list // 添加任务创建操作到操作列表
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // 提交请求并处理响应,设置任务的全局 ID
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -385,21 +388,21 @@ public class GTaskClient {
throw new ActionFailureException("create task: handing jsonobject failed"); throw new ActionFailureException("create task: handing jsonobject failed");
} }
} }
// 创建任务列表的方法,将任务列表创建操作提交到 GTask 服务器
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list // 添加任务列表创建操作到操作列表
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version // 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post // 提交请求并处理响应,设置任务列表的全局 ID
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -411,16 +414,16 @@ public class GTaskClient {
throw new ActionFailureException("create tasklist: handing jsonobject failed"); throw new ActionFailureException("create tasklist: handing jsonobject failed");
} }
} }
// 提交更新操作的方法,将存储的更新操作数组提交到 GTask 服务器
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// action_list // 设置操作列表
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version // 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost);
@ -432,11 +435,10 @@ public class GTaskClient {
} }
} }
} }
// 添加更新节点操作的方法,将节点更新操作添加到更新操作数组
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // 为避免更新项过多导致错误,设置最大更新项为 10
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) { if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate(); commitUpdate();
} }
@ -446,81 +448,98 @@ public class GTaskClient {
mUpdateArray.put(node.getUpdateAction(getActionId())); mUpdateArray.put(node.getUpdateAction(getActionId()));
} }
} }
// 移动任务的方法,将任务移动操作提交到 GTask 服务器
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
// 先提交之前可能存在的更新操作
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// action_list // 设置操作类型为移动任务
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作 ID
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
if (preParent == curParent && task.getPriorSibling() != null) { // 设置要移动的任务的 ID
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
// 如果源任务列表和目标任务列表相同且任务有前驱兄弟节点,则设置前驱兄弟节点 ID
if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and // put prioring_sibing_id only if moving within the tasklist and
// it is not the first one // it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
// 设置源任务列表 ID
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
// 设置目标父任务列表 ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
// 如果源任务列表和目标任务列表不同,则设置目标任务列表 ID
if (preParent != curParent) { if (preParent != curParent) {
// put the dest_list only if moving between tasklists // put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
// 将操作添加到操作列表
actionList.put(action); actionList.put(action);
// 将操作列表添加到提交的 JSON 对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 提交请求
postRequest(jsPost); postRequest(jsPost);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 如果 JSON 处理出现问题,抛出操作失败异常
throw new ActionFailureException("move task: handing jsonobject failed"); throw new ActionFailureException("move task: handing jsonobject failed");
} }
} }
// 删除节点的方法,接受要删除的节点作为参数,并可能抛出网络异常
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
// 先提交之前可能存在的更新操作
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list // 设置节点为已删除状态
node.setDeleted(true); node.setDeleted(true);
// 将节点的更新操作添加到操作列表
actionList.put(node.getUpdateAction(getActionId())); actionList.put(node.getUpdateAction(getActionId()));
// 将操作列表添加到提交的 JSON 对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 提交请求并删除后将更新数组置空
postRequest(jsPost); postRequest(jsPost);
mUpdateArray = null; mUpdateArray = null;
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 如果 JSON 处理出现问题,抛出操作失败异常
throw new ActionFailureException("delete node: handing jsonobject failed"); throw new ActionFailureException("delete node: handing jsonobject failed");
} }
} }
// 获取所有任务列表的方法,可能抛出网络异常
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
// 检查是否已登录,未登录则抛出异常
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
try { try {
// 创建 HTTP GET 请求
HttpGet httpGet = new HttpGet(mGetUrl); HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null; HttpResponse response = null;
// 执行请求
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the task list // 获取响应内容并解析出任务列表的 JSON 数组
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -535,50 +554,60 @@ public class GTaskClient {
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 如果 HTTP 协议出现问题,抛出网络异常
throw new NetworkFailureException("gettasklists: httpget failed"); throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 如果 I/O 出现问题,抛出网络异常
throw new NetworkFailureException("gettasklists: httpget failed"); throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 如果 JSON 解析出现问题,抛出操作失败异常
throw new ActionFailureException("get task lists: handing jasonobject failed"); throw new ActionFailureException("get task lists: handing jasonobject failed");
} }
} }
// 根据任务列表 ID 获取任务列表的方法,可能抛出网络异常
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
// 先提交之前可能存在的更新操作
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// action_list // 设置操作类型为获取所有任务
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 设置操作 ID
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); // 设置任务列表 ID
actionList.put(action); action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 设置不获取已删除任务
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
// client_version // 将操作添加到操作列表
actionList.put(action);
// 将操作列表添加到提交的 JSON 对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本号
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 提交请求并获取响应中的任务列表 JSON 数组
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
// 如果 JSON 处理出现问题,抛出操作失败异常
throw new ActionFailureException("get task list: handing jsonobject failed"); throw new ActionFailureException("get task list: handing jsonobject failed");
} }
} }
// 获取同步账户的方法
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount;
} }
// 重置更新数组的方法,将更新数组置空
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }

@ -47,10 +47,10 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
// GTaskManager类用于管理与Google Task的同步操作以及本地数据和远程数据的交互
public class GTaskManager { public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();
// 定义同步操作的各种状态码
public static final int STATE_SUCCESS = 0; public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1; public static final int STATE_NETWORK_ERROR = 1;
@ -60,33 +60,33 @@ public class GTaskManager {
public static final int STATE_SYNC_IN_PROGRESS = 3; public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4; public static final int STATE_SYNC_CANCELLED = 4;
// 单例模式确保只有一个GTaskManager实例
private static GTaskManager mInstance = null; private static GTaskManager mInstance = null;
// 用于获取认证令牌等操作的Activity
private Activity mActivity; private Activity mActivity;
// 应用上下文
private Context mContext; private Context mContext;
// 用于访问内容提供者的ContentResolver
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
// 表示是否正在同步
private boolean mSyncing; private boolean mSyncing;
// 表示同步是否已取消
private boolean mCancelled; private boolean mCancelled;
// 存储Google Task列表的哈希表键为任务列表的全局唯一标识符gid值为TaskList对象
private HashMap<String, TaskList> mGTaskListHashMap; private HashMap<String, TaskList> mGTaskListHashMap;
// 存储Google Task节点任务或任务列表的哈希表键为节点的gid值为Node对象
private HashMap<String, Node> mGTaskHashMap; private HashMap<String, Node> mGTaskHashMap;
// 存储元数据的哈希表键为相关的gid值为MetaData对象
private HashMap<String, MetaData> mMetaHashMap; private HashMap<String, MetaData> mMetaHashMap;
// 元数据列表
private TaskList mMetaList; private TaskList mMetaList;
// 存储本地已删除笔记的ID集合
private HashSet<Long> mLocalDeleteIdMap; private HashSet<Long> mLocalDeleteIdMap;
// 用于将Google Task的gid映射到本地笔记的ID
private HashMap<String, Long> mGidToNid; private HashMap<String, Long> mGidToNid;
// 用于将本地笔记的ID映射到Google Task的gid
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
// 私有构造函数,用于初始化各种数据结构和变量
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false;
mCancelled = false; mCancelled = false;
@ -98,21 +98,22 @@ public class GTaskManager {
mGidToNid = new HashMap<String, Long>(); mGidToNid = new HashMap<String, Long>();
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>();
} }
// 获取GTaskManager的单例实例
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
} }
return mInstance; return mInstance;
} }
// 设置Activity上下文主要用于获取认证令牌
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken // used for getting authtoken
mActivity = activity; mActivity = activity;
} }
// 执行同步操作的主要方法
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) { if (mSyncing) {
// 如果同步已经在进行中,记录日志并返回相应状态码
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
} }
@ -120,6 +121,7 @@ public class GTaskManager {
mContentResolver = mContext.getContentResolver(); mContentResolver = mContext.getContentResolver();
mSyncing = true; mSyncing = true;
mCancelled = false; mCancelled = false;
// 清除之前同步过程中存储的数据
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -131,24 +133,26 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); client.resetUpdateArray();
// login google task // 登录Google Task
if (!mCancelled) { if (!mCancelled) {
if (!client.login(mActivity)) { if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed"); throw new NetworkFailureException("login google task failed");
} }
} }
// get the task list from google // 获取Google Task列表并进行初始化
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); initGTaskList();
// do content sync work // 执行内容同步操作
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent(); syncContent();
} catch (NetworkFailureException e) { } catch (NetworkFailureException e) {
// 处理网络故障异常,记录日志并返回相应状态码
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR; return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) { } catch (ActionFailureException e) {
// 处理操作失败异常,记录日志并返回相应状态码
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} catch (Exception e) { } catch (Exception e) {
@ -156,6 +160,7 @@ public class GTaskManager {
e.printStackTrace(); e.printStackTrace();
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} finally { } finally {
// 无论同步是否成功,都清除相关数据并重置同步状态
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -164,7 +169,7 @@ public class GTaskManager {
mNidToGid.clear(); mNidToGid.clear();
mSyncing = false; mSyncing = false;
} }
// 初始化Google Task列表的方法
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
@ -173,21 +178,22 @@ public class GTaskManager {
return; return;
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
try { try {
// 从Google获取任务列表的JSON数组
JSONArray jsTaskLists = client.getTaskLists(); JSONArray jsTaskLists = client.getTaskLists();
// init meta list first // 初始化元数据列表
mMetaList = null; mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 查找元数据文件夹
if (name if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object); mMetaList.setContentByRemoteJSON(object);
// load meta data // 加载元数据
JSONArray jsMetas = client.getTaskList(gid); JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) { for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j); object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,7 +209,7 @@ public class GTaskManager {
} }
} }
// create meta list if not existed // 如果元数据列表不存在,则创建一个新的元数据列表
if (mMetaList == null) { if (mMetaList == null) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -211,12 +217,12 @@ public class GTaskManager {
GTaskClient.getInstance().createTaskList(mMetaList); GTaskClient.getInstance().createTaskList(mMetaList);
} }
// init task list // 初始化任务列表和任务
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 处理以特定前缀开头且不是元数据文件夹的任务列表
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) { + GTaskStringUtils.FOLDER_META)) {
@ -225,7 +231,7 @@ public class GTaskManager {
mGTaskListHashMap.put(gid, tasklist); mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist);
// load tasks // 加载任务列表中的任务
JSONArray jsTasks = client.getTaskList(gid); JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) { for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j); object = (JSONObject) jsTasks.getJSONObject(j);
@ -241,12 +247,13 @@ public class GTaskManager {
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
// 处理JSON解析异常记录日志、打印堆栈信息并抛出操作失败异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed"); throw new ActionFailureException("initGTaskList: handing JSONObject failed");
} }
} }
// 执行内容同步的方法
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType;
Cursor c = null; Cursor c = null;
@ -259,7 +266,7 @@ public class GTaskManager {
return; return;
} }
// for local deleted note // 处理本地已删除的笔记
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] { "(type<>? AND parent_id=?)", new String[] {
@ -286,10 +293,10 @@ public class GTaskManager {
} }
} }
// sync folder first // 同步文件夹
syncFolder(); syncFolder();
// for note existing in database // 处理数据库中存在的笔记
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -306,10 +313,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add // 本地新增
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete // 远程删除
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
@ -326,14 +333,14 @@ public class GTaskManager {
} }
} }
// go through remaining items // 处理剩余的未同步节点
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator(); Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next(); Map.Entry<String, Node> entry = iter.next();
node = entry.getValue(); node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
} }
// 检查同步是否取消,如果未取消则执行本地删除操作和提交更新操作
// mCancelled can be set by another thread, so we neet to check one by // mCancelled can be set by another thread, so we neet to check one by
// one // one
// clear local delete table // clear local delete table
@ -342,15 +349,14 @@ public class GTaskManager {
throw new ActionFailureException("failed to batch-delete local deleted notes"); throw new ActionFailureException("failed to batch-delete local deleted notes");
} }
} }
// 检查同步是否取消如果未取消则提交更新并刷新本地同步ID
// refresh local sync id
if (!mCancelled) { if (!mCancelled) {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId(); refreshLocalSyncId();
} }
} }
// 同步文件夹的方法
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null;
String gid; String gid;
@ -361,7 +367,7 @@ public class GTaskManager {
return; return;
} }
// for root folder // 处理根文件夹
try { try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -373,7 +379,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary // 对于系统文件夹,仅在必要时更新远程名称
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
@ -390,7 +396,7 @@ public class GTaskManager {
} }
} }
// for call-note folder // 处理通话记录文件夹
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
@ -404,8 +410,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if // 对于系统文件夹,仅在必要时更新远程名称
// necessary
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE)) + GTaskStringUtils.FOLDER_CALL_NOTE))
@ -424,7 +429,7 @@ public class GTaskManager {
} }
} }
// for local existing folders // 处理本地现有文件夹
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -441,10 +446,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add // 本地新增文件夹
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete // 远程删除文件夹
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
@ -460,7 +465,7 @@ public class GTaskManager {
} }
} }
// for remote add folders // 处理远程新增文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next();
@ -475,7 +480,7 @@ public class GTaskManager {
if (!mCancelled) if (!mCancelled)
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
} }
// 根据同步类型执行具体同步操作的方法
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -484,12 +489,15 @@ public class GTaskManager {
MetaData meta; MetaData meta;
switch (syncType) { switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL: case Node.SYNC_ACTION_ADD_LOCAL:
// 本地新增节点操作
addLocalNode(node); addLocalNode(node);
break; break;
case Node.SYNC_ACTION_ADD_REMOTE: case Node.SYNC_ACTION_ADD_REMOTE:
// 远程新增节点操作
addRemoteNode(node, c); addRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_DEL_LOCAL: case Node.SYNC_ACTION_DEL_LOCAL:
// 本地删除节点操作
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
if (meta != null) { if (meta != null) {
GTaskClient.getInstance().deleteNode(meta); GTaskClient.getInstance().deleteNode(meta);
@ -497,6 +505,7 @@ public class GTaskManager {
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
break; break;
case Node.SYNC_ACTION_DEL_REMOTE: case Node.SYNC_ACTION_DEL_REMOTE:
// 远程删除节点操作
meta = mMetaHashMap.get(node.getGid()); meta = mMetaHashMap.get(node.getGid());
if (meta != null) { if (meta != null) {
GTaskClient.getInstance().deleteNode(meta); GTaskClient.getInstance().deleteNode(meta);
@ -504,24 +513,28 @@ public class GTaskManager {
GTaskClient.getInstance().deleteNode(node); GTaskClient.getInstance().deleteNode(node);
break; break;
case Node.SYNC_ACTION_UPDATE_LOCAL: case Node.SYNC_ACTION_UPDATE_LOCAL:
// 本地更新节点操作
updateLocalNode(node, c); updateLocalNode(node, c);
break; break;
case Node.SYNC_ACTION_UPDATE_REMOTE: case Node.SYNC_ACTION_UPDATE_REMOTE:
// 远程更新节点操作
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_UPDATE_CONFLICT: case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea // 处理更新冲突,目前简单地使用本地更新
// right now just use local update simply // 可能合并双方修改会是更好的做法,但目前仅做简单处理
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_NONE: case Node.SYNC_ACTION_NONE:
// 无需同步操作
break; break;
case Node.SYNC_ACTION_ERROR: case Node.SYNC_ACTION_ERROR:
default: default:
// 未知同步操作类型,抛出异常
throw new ActionFailureException("unkown sync action type"); throw new ActionFailureException("unkown sync action type");
} }
} }
// 本地新增节点的具体实现方法
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -549,7 +562,7 @@ public class GTaskManager {
if (note.has(NoteColumns.ID)) { if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID); long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) { if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one // 如果本地数据库中已存在该笔记ID则移除该ID重新生成新的笔记
note.remove(NoteColumns.ID); note.remove(NoteColumns.ID);
} }
} }
@ -562,8 +575,7 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create // 如果本地数据库中已存在该数据ID则移除该ID重新生成新的数据
// a new one
data.remove(DataColumns.ID); data.remove(DataColumns.ID);
} }
} }
@ -584,25 +596,25 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
} }
// create the local node // 创建本地节点
sqlNote.setGtaskId(node.getGid()); sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false); sqlNote.commit(false);
// update gid-nid mapping // 更新gid - nid映射
mGidToNid.put(node.getGid(), sqlNote.getId()); mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid()); mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta // 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
// 本地更新节点的具体实现方法
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote; SqlNote sqlNote;
// update the note locally // 更新本地笔记
sqlNote = new SqlNote(mContext, c); sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());
@ -615,10 +627,10 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true); sqlNote.commit(true);
// update meta info // 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
// 远程新增节点的具体实现方法
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -627,7 +639,7 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
Node n; Node n;
// update remotely // 远程更新操作
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = new Task(); Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent()); task.setContentByLocalJSON(sqlNote.getContent());
@ -642,12 +654,12 @@ public class GTaskManager {
GTaskClient.getInstance().createTask(task); GTaskClient.getInstance().createTask(task);
n = (Node) task; n = (Node) task;
// add meta // 添加元数据
updateRemoteMeta(task.getGid(), sqlNote); updateRemoteMeta(task.getGid(), sqlNote);
} else { } else {
TaskList tasklist = null; TaskList tasklist = null;
// we need to skip folder if it has already existed // 检查文件夹是否已存在如果存在则获取对应的TaskList对象
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT; folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -671,7 +683,7 @@ public class GTaskManager {
} }
} }
// no match we can add now // 如果未找到匹配的文件夹则创建新的TaskList对象
if (tasklist == null) { if (tasklist == null) {
tasklist = new TaskList(); tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent()); tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -681,17 +693,17 @@ public class GTaskManager {
n = (Node) tasklist; n = (Node) tasklist;
} }
// update local note // 更新本地笔记
sqlNote.setGtaskId(n.getGid()); sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false); sqlNote.commit(false);
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
// gid-id mapping // 更新gid - id映射
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
// 远程更新节点的具体实现方法
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -699,11 +711,11 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely // 远程更新节点内容
node.setContentByLocalJSON(sqlNote.getContent()); node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node); GTaskClient.getInstance().addUpdateNode(node);
// update meta // 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary // move task if necessary
@ -725,11 +737,11 @@ public class GTaskManager {
} }
} }
// clear local modified flag // 清除本地修改标志
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
} }
// 更新远程元数据的方法
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
@ -745,13 +757,13 @@ public class GTaskManager {
} }
} }
} }
// 刷新本地同步ID的方法
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
// get the latest gtask list // 重新获取最新的Google Task列表清除之前的数据缓存
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -789,11 +801,11 @@ public class GTaskManager {
} }
} }
} }
// 获取同步账户名称的方法
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }
// 取消同步操作的方法
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} }

@ -22,70 +22,89 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
// GTaskSyncService类是一个Android服务用于管理Google Task的同步任务
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
// 定义用于表示同步操作类型的字符串常量
public final static String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
// 表示开始同步的操作类型值
public final static int ACTION_START_SYNC = 0; public final static int ACTION_START_SYNC = 0;
// 表示取消同步的操作类型值
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_CANCEL_SYNC = 1;
// 表示无效操作类型的默认值
public final static int ACTION_INVALID = 2; public final static int ACTION_INVALID = 2;
// 定义用于广播同步服务相关信息的动作名称
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
// 用于在广播中表示是否正在同步的键
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
// 用于在广播中表示同步进度消息的键
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// 存储当前正在执行的同步任务实例初始化为null
private static GTaskASyncTask mSyncTask = null; private static GTaskASyncTask mSyncTask = null;
// 存储同步进度消息,初始化为空字符串
private static String mSyncProgress = ""; private static String mSyncProgress = "";
// 启动同步任务的方法
private void startSync() { private void startSync() {
// 如果当前没有正在执行的同步任务
if (mSyncTask == null) { if (mSyncTask == null) {
// 创建一个新的GTaskASyncTask实例并传入当前服务实例和一个完成监听器
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
// 当同步任务完成时调用的方法
public void onComplete() { public void onComplete() {
// 将当前同步任务实例设置为null表示任务已完成
mSyncTask = null; mSyncTask = null;
// 发送一个空消息的广播
sendBroadcast(""); sendBroadcast("");
// 停止当前服务
stopSelf(); stopSelf();
} }
}); });
// 发送一个空消息的广播,可能用于通知相关组件同步任务即将开始
sendBroadcast(""); sendBroadcast("");
// 执行同步任务
mSyncTask.execute(); mSyncTask.execute();
} }
} }
// 取消同步任务的方法
private void cancelSync() { private void cancelSync() {
// 如果当前有正在执行的同步任务
if (mSyncTask != null) { if (mSyncTask != null) {
// 调用同步任务的取消同步方法
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
// 服务创建时调用的方法将同步任务实例设置为null
@Override @Override
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
// 服务接收到启动命令时调用的方法
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
// 获取启动意图中的额外数据
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
// 如果额外数据不为空且包含同步操作类型键
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
// 根据操作类型值执行相应操作
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC: case ACTION_START_SYNC:
// 启动同步任务
startSync(); startSync();
break; break;
case ACTION_CANCEL_SYNC: case ACTION_CANCEL_SYNC:
// 取消同步任务
cancelSync(); cancelSync();
break; break;
default: default:
break; break;
} }
// 返回粘性服务标志,表示服务在被异常终止后会尝试重新启动
return START_STICKY; return START_STICKY;
} }
// 如果不满足上述条件则调用父类的onStartCommand方法
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
// 系统内存不足时调用的方法,如果有正在执行的同步任务则取消它
@Override @Override
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) {
@ -93,35 +112,47 @@ public class GTaskSyncService extends Service {
} }
} }
// 服务绑定方法返回null表示不支持绑定操作
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
// 发送广播的方法,用于向感兴趣的组件发送同步服务的相关信息
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
// 更新同步进度消息
mSyncProgress = msg; mSyncProgress = msg;
// 创建一个意图,指定广播动作名称
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
// 将是否正在同步的状态添加到意图的额外数据中
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
// 将同步进度消息添加到意图的额外数据中
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
// 发送广播
sendBroadcast(intent); sendBroadcast(intent);
} }
// 静态方法用于启动同步任务在Activity中调用
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
// 设置同步任务的Activity上下文
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
// 创建一个启动当前服务的意图,并指定操作类型为开始同步
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
// 启动服务
activity.startService(intent); activity.startService(intent);
} }
// 静态方法用于取消同步任务在Context中调用
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
// 创建一个启动当前服务的意图,并指定操作类型为取消同步
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
// 启动服务
context.startService(intent); context.startService(intent);
} }
// 静态方法,用于检查是否正在进行同步任务
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
// 静态方法,用于获取同步进度消息
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }

Loading…
Cancel
Save