对gtask包的代码提交

fanshuang
fanshuang 7 months ago
parent d9cd7198aa
commit 9d4fb1a67a

@ -1,20 +1,21 @@
/* ```java
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) /*
* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. * Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 *
* * http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, * Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * distributed under the License is distributed on an "AS IS" BASIS,
* See the License for the specific language governing permissions and * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* limitations under the License. * See the License for the specific language governing permissions and
*/ * limitations under the License.
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import android.util.Log; import android.util.Log;
@ -24,14 +25,27 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* MetaData Task
* GID
*/
public class MetaData extends Task { public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName();
/**
* GID
*/
private String mRelatedGid = null; private String mRelatedGid = null;
/**
* GID
*
* @param gid GID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
// 将 GID 添加到元数据中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid");
@ -40,20 +54,36 @@ public class MetaData extends Task {
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
/**
* GID
*
* @return GID
*/
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
/**
*
*
* @return true false
*/
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }
/**
* JSON GID
*
* @param js JSON
*/
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js);
if (getNotes() != null) { if (getNotes() != null) {
try { try {
// 解析笔记内容中的元数据并提取 GID
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) { } catch (JSONException e) {
@ -63,20 +93,36 @@ public class MetaData extends Task {
} }
} }
/**
* JSON
*
* @param js JSON
* @throws IllegalAccessError
*/
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
/**
* JSON
*
* @throws IllegalAccessError
*/
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
} }
/**
*
*
* @param c
* @throws IllegalAccessError
*/
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called");
} }
} }
```

@ -21,81 +21,195 @@ import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
public abstract class Node { public abstract class Node {
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_ADD_REMOTE = 1; package net.micode.notes.gtask.data;
public static final int SYNC_ACTION_ADD_LOCAL = 2;
public static final int SYNC_ACTION_DEL_REMOTE = 3;
public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;
private String mGid;
private String mName;
private long mLastModified;
private boolean mDeleted;
public Node() {
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
}
public abstract JSONObject getCreateAction(int actionId);
public abstract JSONObject getUpdateAction(int actionId);
public abstract void setContentByRemoteJSON(JSONObject js);
public abstract void setContentByLocalJSON(JSONObject js);
public abstract JSONObject getLocalJSONFromContent();
public abstract int getSyncAction(Cursor c);
public void setGid(String gid) {
this.mGid = gid;
}
public void setName(String name) {
this.mName = name;
}
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
public String getGid() {
return this.mGid;
}
public String getName() { import android.database.Cursor;
return this.mName;
}
public long getLastModified() { import org.json.JSONObject;
return this.mLastModified;
}
public boolean getDeleted() { /**
return this.mDeleted; *
*
*/
public abstract class Node {
/**
*
*/
public static final int SYNC_ACTION_NONE = 0;
/**
*
*/
public static final int SYNC_ACTION_ADD_REMOTE = 1;
/**
*
*/
public static final int SYNC_ACTION_ADD_LOCAL = 2;
/**
*
*/
public static final int SYNC_ACTION_DEL_REMOTE = 3;
/**
*
*/
public static final int SYNC_ACTION_DEL_LOCAL = 4;
/**
*
*/
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
/**
*
*/
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
/**
*
*/
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
/**
*
*/
public static final int SYNC_ACTION_ERROR = 8;
private String mGid; // 任务的全局唯一标识符
private String mName; // 任务名称
private long mLastModified; // 最后修改时间
private boolean mDeleted; // 是否已删除
/**
*
*/
public Node() {
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
}
/**
* JSON
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
*
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
*
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
*
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent();
/**
*
*
* @param c
* @return
*/
public abstract int getSyncAction(Cursor c);
/**
*
*
* @param gid
*/
public void setGid(String gid) {
this.mGid = gid;
}
/**
*
*
* @param name
*/
public void setName(String name) {
this.mName = name;
}
/**
*
*
* @param lastModified
*/
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
/**
*
*
* @param deleted
*/
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
/**
*
*
* @return
*/
public String getGid() {
return this.mGid;
}
/**
*
*
* @return
*/
public String getName() {
return this.mName;
}
/**
*
*
* @return
*/
public long getLastModified() {
return this.mLastModified;
}
/**
*
*
* @return
*/
public boolean getDeleted() {
return this.mDeleted;
}
} }
} }

@ -1,20 +1,4 @@
/* package net.micode.notes.gtask.data;
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.ContentUris; import android.content.ContentUris;
@ -28,49 +12,67 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* SqlData
* JSON
*/
public class SqlData { public class SqlData {
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName(); // 日志标签
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999; // 无效的 ID表示未初始化或无效的数据
/**
*
*/
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
/**
* ID
*/
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;
/**
* MIME
*/
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
/**
*
*/
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;
/**
* 1
*/
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
/**
* 3
*/
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver; private ContentResolver mContentResolver; // 内容解析器,用于与内容提供者交互
private boolean mIsCreate; // 标记是否为创建操作
private boolean mIsCreate; private long mDataId; // 数据 ID
private String mDataMimeType; // 数据 MIME 类型
private long mDataId; private String mDataContent; // 数据内容
private long mDataContentData1; // 数据字段1
private String mDataMimeType; private String mDataContentData3; // 数据字段3
private ContentValues mDiffDataValues; // 用于存储要更新的字段值
private String mDataContent;
/**
private long mDataContentData1; * SqlData
*
private String mDataContentData3; * @param context
*/
private ContentValues mDiffDataValues;
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
@ -82,6 +84,12 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
* SqlData
*
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
@ -89,6 +97,11 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
*
*
* @param c
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,6 +110,12 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
} }
/**
* JSON
*
* @param js JSON
* @throws JSONException JSON
*/
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) {
@ -130,9 +149,15 @@ public class SqlData {
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3;
} }
/**
* JSON
*
* @return JSON
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "似乎我们还没有在数据库中创建此数据");
return null; return null;
} }
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -144,8 +169,14 @@ public class SqlData {
return js; return js;
} }
/**
*
*
* @param noteId ID
* @param validateVersion
* @param version
*/
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID);
@ -156,8 +187,8 @@ public class SqlData {
try { try {
mDataId = Long.valueOf(uri.getPathSegments().get(1)); mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "获取笔记 ID 错误:" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("创建笔记失败");
} }
} else { } else {
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) {
@ -167,14 +198,14 @@ public class SqlData {
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else { } else {
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + Notes.TABLE_NAME
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version) String.valueOf(noteId), String.valueOf(version)
}); });
} }
if (result == 0) { if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "没有更新。可能是用户在同步时修改了笔记");
} }
} }
} }
@ -183,7 +214,13 @@ public class SqlData {
mIsCreate = false; mIsCreate = false;
} }
/**
* ID
*
* @return ID
*/
public long getId() { public long getId() {
return mDataId; return mDataId;
} }
} }

@ -1,49 +1,29 @@
/* import net.micode.notes.gtask.data.SqlData;
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
import org.json.JSONArray; import javax.naming.Context;
import org.json.JSONException; import java.awt.*;
import org.json.JSONObject; import java.util.ArrayList; /**
* SqlNote
import java.util.ArrayList; */
public class SqlNote { public class SqlNote {
/**
*
*/
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName();
/**
* ID
*/
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
public static final String[] PROJECTION_NOTE = new String[] { /**
*
*/
public static final String[] PROJECTION_NOTE = new String[]{
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
@ -52,76 +32,122 @@ public class SqlNote {
NoteColumns.VERSION NoteColumns.VERSION
}; };
/**
*
*/
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2; public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3; public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4; public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5; public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6; public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7; public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8; public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9; public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10; public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11; public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12; public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13; public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14; public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15; public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
/**
* 访
*/
private Context mContext; private Context mContext;
/**
*
*/
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
/**
*
*/
private boolean mIsCreate; private boolean mIsCreate;
/**
*
*/
private long mId; private long mId;
/**
*
*/
private long mAlertDate; private long mAlertDate;
/**
* ID
*/
private int mBgColorId; private int mBgColorId;
/**
*
*/
private long mCreatedDate; private long mCreatedDate;
/**
*
*/
private int mHasAttachment; private int mHasAttachment;
/**
*
*/
private long mModifiedDate; private long mModifiedDate;
/**
* ID
*/
private long mParentId; private long mParentId;
/**
*
*/
private String mSnippet; private String mSnippet;
/**
*
*/
private int mType; private int mType;
/**
* ID
*/
private int mWidgetId; private int mWidgetId;
/**
*
*/
private int mWidgetType; private int mWidgetType;
/**
* ID
*/
private long mOriginParent; private long mOriginParent;
/**
*
*/
private long mVersion; private long mVersion;
/**
* ContentValues
*/
private ContentValues mDiffNoteValues; private ContentValues mDiffNoteValues;
/**
*
*/
private ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
/**
* SqlNote
*
* @param context
*/
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -143,6 +169,12 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
} }
/**
*
*
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -154,6 +186,12 @@ public class SqlNote {
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/**
* ID
*
* @param context
* @param id
*/
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -163,16 +201,18 @@ public class SqlNote {
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/**
* ID
*
* @param id
*/
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[]{String.valueOf(id)}, null);
String.valueOf(id)
}, null);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext();
loadFromCursor(c); loadFromCursor(c);
@ -185,6 +225,11 @@ public class SqlNote {
} }
} }
/**
*
*
* @param c
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -200,14 +245,15 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
/**
*
*/
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
try { try {
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] { "(note_id=?)", new String[]{String.valueOf(mId)}, null);
String.valueOf(mId)
}, null);
if (c != null) { if (c != null) {
if (c.getCount() == 0) { if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data"); Log.w(TAG, "it seems that the note has not data");
@ -226,22 +272,26 @@ public class SqlNote {
} }
} }
/**
* JSON
*
* @param js JSON
* @return
*/
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder"); Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// for folder we can only update the snnipet and type // 对于文件夹,我们只能更新片段和类型
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
} }
mSnippet = snippet; mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type);
} }
@ -254,78 +304,67 @@ public class SqlNote {
} }
mId = id; mId = id;
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
.getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) { if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
} }
mAlertDate = alertDate; mAlertDate = alertDate;
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) { if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
} }
mBgColorId = bgColorId; mBgColorId = bgColorId;
long createDate = note.has(NoteColumns.CREATED_DATE) ? note long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) { if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
} }
mCreatedDate = createDate; mCreatedDate = createDate;
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) { if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
} }
mHasAttachment = hasAttachment; mHasAttachment = hasAttachment;
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) { if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
} }
mModifiedDate = modifiedDate; mModifiedDate = modifiedDate;
long parentId = note.has(NoteColumns.PARENT_ID) ? note long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0;
.getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) { if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
} }
mParentId = parentId; mParentId = parentId;
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
} }
mSnippet = snippet; mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type);
} }
mType = type; mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) : AppWidgetManager.INVALID_APPWIDGET_ID;
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) { if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
} }
mWidgetId = widgetId; mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) { if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
} }
mWidgetType = widgetType; mWidgetType = widgetType;
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) { if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
} }
@ -359,6 +398,11 @@ public class SqlNote {
return true; return true;
} }
/**
* JSON
*
* @return JSON
*/
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -407,99 +451,170 @@ public class SqlNote {
return null; return null;
} }
/**
* ID
*
* @param id
*/
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }
/**
* GTask ID
*
* @param gid GTask ID
*/
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
/**
* ID
*
* @param syncId ID
*/
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
/**
*
*/
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
/**
*
*
* @return
*/
public long getId() { public long getId() {
return mId; return mId;
} }
/**
* ID
*
* @return
*/
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
/**
*
*
* @return
*/
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
/**
*
*
* @return true false
*/
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
/**
*
*
* @param validateVersion
*/
public void commit(boolean validateVersion) {
if (mIsCreate) {
// 如果是新创建的笔记,插入数据并获取生成的 ID
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
public void commit(boolean validateVersion) { Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
if (mIsCreate) { try {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { mId = Long.valueOf(uri.getPathSegments().get(1));
mDiffNoteValues.remove(NoteColumns.ID); } catch (NumberFormatException e) {
} Log.e(TAG, "获取笔记 ID 错误: " + e.toString());
throw new ActionFailureException("创建笔记失败");
}
if (mId == 0) {
throw new IllegalStateException("创建线程 ID 失败");
}
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); if (mType == Notes.TYPE_NOTE) {
try { for (SqlData sqlData : mDataList) {
mId = Long.valueOf(uri.getPathSegments().get(1)); sqlData.commit(mId, false, -1);
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
} }
}
} else {
// 检查笔记 ID 是否有效
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "不存在此笔记");
throw new IllegalStateException("尝试使用无效 ID 更新笔记");
}
if (mType == Notes.TYPE_NOTE) { // 如果有差异值需要更新
for (SqlData sqlData : mDataList) { if (mDiffNoteValues.size() > 0) {
sqlData.commit(mId, false, -1); mVersion++;
} int result = 0;
} if (!validateVersion) {
} else { // 不验证版本号时直接更新笔记
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues,
Log.e(TAG, "No such note"); "(" + NoteColumns.ID + "=?)",
throw new IllegalStateException("Try to update note with invalid id"); new String[]{String.valueOf(mId)});
} else {
// 验证版本号时更新笔记
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues,
"(" + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[]{String.valueOf(mId), String.valueOf(mVersion)});
} }
if (mDiffNoteValues.size() > 0) {
mVersion ++; if (result == 0) {
int result = 0; Log.w(TAG, "没有进行任何更新。可能是用户在同步时修改了笔记");
if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId)
});
} else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
String.valueOf(mId), String.valueOf(mVersion)
});
}
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
} }
}
if (mType == Notes.TYPE_NOTE) { // 如果是普通笔记类型,提交笔记内容数据
for (SqlData sqlData : mDataList) { if (mType == Notes.TYPE_NOTE) {
sqlData.commit(mId, validateVersion, mVersion); for (SqlData sqlData : mDataList) {
} sqlData.commit(mId, validateVersion, mVersion);
} }
} }
}
// refresh local info // 刷新本地信息
loadFromCursor(mId); loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
mDiffNoteValues.clear(); // 清空差异值,并标记为已创建
mIsCreate = false; mDiffNoteValues.clear();
} mIsCreate = false;
} }
}
1. ID
- ID 0 使 ID
2.
- `mDiffNoteValues` `mVersion`
-
- ID
-
-
3.
- `Notes.TYPE_NOTE` `mDataList` `SqlData`
4.
- `loadFromCursor`
-
5.
- `mDiffNoteValues`
- `mIsCreate` `false`

@ -1,50 +1,26 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; // Task类继承自Node类用于表示一个任务对象
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Task extends Node { public class Task extends Node {
// 日志标签,用于标识日志信息来源
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName();
// 表示任务是否已完成
private boolean mCompleted; private boolean mCompleted;
// 任务的备注信息
private String mNotes; private String mNotes;
// 任务的元信息使用JSONObject存储
private JSONObject mMetaInfo; private JSONObject mMetaInfo;
// 任务的前一个兄弟任务,用于任务排序
private Task mPriorSibling; private Task mPriorSibling;
// 任务所属的任务列表
private TaskList mParent; private TaskList mParent;
// Task类的构造方法初始化任务的默认状态
public Task() { public Task() {
super(); super();
mCompleted = false; mCompleted = false;
@ -54,6 +30,12 @@ public class Task extends Node {
mMetaInfo = null; mMetaInfo = null;
} }
/**
* JSON
* @param actionId ID
* @return JSONObject
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -103,6 +85,12 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
* @param actionId ID
* @return JSONObject
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -135,6 +123,11 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
* @param js JSON
* @throws ActionFailureException
*/
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
@ -175,177 +168,220 @@ public class Task extends Node {
} }
} }
/**
* JSON
* @param js JSON
* @throws ActionFailureException
*/
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); ```
}
try { // 当没有可用内容时记录警告信息
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); }
try {
// 从JSON对象中获取笔记和数据数组
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { // 检查笔记类型是否无效
Log.e(TAG, "invalid type"); if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
return; Log.e(TAG, "invalid type");
return;
}
// 遍历数据数组以查找并设置笔记内容
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
break;
}
}
} catch (JSONException e) {
// 记录并打印JSONException的堆栈跟踪
Log.e(TAG, e.toString());
e.printStackTrace();
}
```
/**
* 使JSON
*
* @return JSONObjectnull
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
// 处理从网页创建的新任务
if (mMetaInfo == null) {
if (name == null) {
Log.w(TAG, "the note seems to be an empty one");
return null;
} }
// 构建新的笔记JSON对象
JSONObject js = new JSONObject();
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name);
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js;
} else {
// 处理已同步的任务
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 更新数据数组中的笔记内容
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT)); data.put(DataColumns.CONTENT, getName());
break; break;
} }
} }
} catch (JSONException e) { note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
Log.e(TAG, e.toString()); return mMetaInfo;
e.printStackTrace();
} }
} catch (JSONException e) {
// 记录并打印JSONException的堆栈跟踪
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
} }
}
public JSONObject getLocalJSONFromContent() { /**
String name = getName(); *
*
* @param metaData MetaData
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try { try {
if (mMetaInfo == null) { // 将笔记信息转换为JSON对象
// new task created from web mMetaInfo = new JSONObject(metaData.getNotes());
if (name == null) {
Log.w(TAG, "the note seems to be an empty one");
return null;
}
JSONObject js = new JSONObject();
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name);
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js;
} else {
// synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName());
break;
}
}
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo;
}
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); // 转换失败时记录错误并将mMetaInfo设置为null
e.printStackTrace(); Log.w(TAG, e.toString());
return null; mMetaInfo = null;
} }
} }
}
```
```java
/**
*
*
* @param c
* @return
*/
public int getSyncAction(Cursor c) {
try {
// 从mMetaInfo中获取笔记信息
JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
}
public void setMetaInfo(MetaData metaData) { // 根据笔记信息确定同步操作
if (metaData != null && metaData.getNotes() != null) { if (noteInfo == null) {
try { Log.w(TAG, "it seems that note meta has been deleted");
mMetaInfo = new JSONObject(metaData.getNotes()); return SYNC_ACTION_UPDATE_REMOTE;
} catch (JSONException e) {
Log.w(TAG, e.toString());
mMetaInfo = null;
}
} }
}
public int getSyncAction(Cursor c) { if (!noteInfo.has(NoteColumns.ID)) {
try { Log.w(TAG, "remote note id seems to be deleted");
JSONObject noteInfo = null; return SYNC_ACTION_UPDATE_LOCAL;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { }
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
}
if (noteInfo == null) { // 验证笔记ID
Log.w(TAG, "it seems that note meta has been deleted"); if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
return SYNC_ACTION_UPDATE_REMOTE; Log.w(TAG, "note id doesn't match");
} return SYNC_ACTION_UPDATE_LOCAL;
}
if (!noteInfo.has(NoteColumns.ID)) { // 根据本地修改状态确定同步操作
Log.w(TAG, "remote note id seems to be deleted"); if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
return SYNC_ACTION_NONE;
} else {
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else {
// validate the note id now // 验证GTasks ID
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.w(TAG, "note id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { return SYNC_ACTION_UPDATE_REMOTE;
// there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
return SYNC_ACTION_NONE;
} else {
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;
}
} else { } else {
// validate gtask id return SYNC_ACTION_UPDATE_CONFLICT;
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
} else {
return SYNC_ACTION_UPDATE_CONFLICT;
}
} }
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
} }
} catch (Exception e) {
return SYNC_ACTION_ERROR; // 记录并打印异常的堆栈跟踪
} Log.e(TAG, e.toString());
e.printStackTrace();
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
} }
public void setCompleted(boolean completed) { return SYNC_ACTION_ERROR;
this.mCompleted = completed; }
} ```
```java
public void setNotes(String notes) { /**
this.mNotes = notes; *
} *
* @return
*/
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
// 设置任务的完成状态
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
public void setPriorSibling(Task priorSibling) { // 设置任务的笔记内容
this.mPriorSibling = priorSibling; public void setNotes(String notes) {
} this.mNotes = notes;
}
public void setParent(TaskList parent) { // 设置任务的前一个兄弟任务
this.mParent = parent; public void setPriorSibling(Task priorSibling) {
} this.mPriorSibling = priorSibling;
}
public boolean getCompleted() { // 设置任务的父任务列表
return this.mCompleted; public void setParent(TaskList parent) {
} this.mParent = parent;
}
public String getNotes() { // 获取任务的完成状态
return this.mNotes; public boolean getCompleted() {
} return this.mCompleted;
}
public Task getPriorSibling() { // 获取任务的笔记内容
return this.mPriorSibling; public String getNotes() {
} return this.mNotes;
}
public TaskList getParent() { // 获取任务的前一个兄弟任务
return this.mParent; public Task getPriorSibling() {
} return this.mPriorSibling;
}
// 获取任务的父任务列表
public TaskList getParent() {
return this.mParent;
} }

@ -1,18 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
@ -29,20 +14,35 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/**
* TaskList Node
* JSON
*/
public class TaskList extends Node { public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName(); private static final String TAG = TaskList.class.getSimpleName();
// 任务列表的索引
private int mIndex; private int mIndex;
// 任务列表
private ArrayList<Task> mChildren; private ArrayList<Task> mChildren;
/**
* TaskList
*/
public TaskList() { public TaskList() {
super(); super();
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>();
mIndex = 1; mIndex = 1;
} }
/**
* JSON
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -74,6 +74,13 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -103,6 +110,12 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
*
* @param js JSON
* @throws ActionFailureException
*/
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
@ -129,6 +142,12 @@ public class TaskList extends Node {
} }
} }
/**
* JSON
*
* @param js JSON
* @throws ActionFailureException
*/
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -153,191 +172,277 @@ public class TaskList extends Node {
} }
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
} }
public JSONObject getLocalJSONFromContent() { /**
try { * JSON
JSONObject js = new JSONObject(); *
JSONObject folder = new JSONObject(); * JSONObject
* @return JSONObject null
String folderName = getName(); */
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) public JSONObject getLocalJSONFromContent() {
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), try {
folderName.length()); JSONObject js = new JSONObject();
folder.put(NoteColumns.SNIPPET, folderName); JSONObject folder = new JSONObject();
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
return js;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
}
}
public int getSyncAction(Cursor c) { String folderName = getName();
try { if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
// there is no local update folderName.length());
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { folder.put(NoteColumns.SNIPPET, folderName);
// no update both side if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
return SYNC_ACTION_NONE; || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
} else { folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
// apply remote to local else
return SYNC_ACTION_UPDATE_LOCAL; folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
}
} else {
// validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// for folder conflicts, just apply local modification
return SYNC_ACTION_UPDATE_REMOTE;
}
}
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return SYNC_ACTION_ERROR; js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
}
public int getChildTaskCount() { return js;
return mChildren.size(); } catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
} }
}
public boolean addChildTask(Task task) { /**
boolean ret = false; *
if (task != null && !mChildren.contains(task)) { *
ret = mChildren.add(task); *
if (ret) { * @param c
// need to set prior sibling and parent * @return
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren */
.get(mChildren.size() - 1)); public int getSyncAction(Cursor c) {
task.setParent(this); try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// 本地没有更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 双方都没有更新
return SYNC_ACTION_NONE;
} else {
// 将远程应用到本地
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
// 验证 gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id 不匹配");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 仅本地有修改
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// 对于文件夹冲突,仅应用本地修改
return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
return ret; } catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
} }
public boolean addChildTask(Task task, int index) { return SYNC_ACTION_ERROR;
if (index < 0 || index > mChildren.size()) { }
Log.e(TAG, "add child task: invalid index");
return false;
}
int pos = mChildren.indexOf(task); /**
if (task != null && pos == -1) { *
mChildren.add(index, task); *
* @return
// update the task list */
Task preTask = null; public int getChildTaskCount() {
Task afterTask = null; return mChildren.size();
if (index != 0) }
preTask = mChildren.get(index - 1);
if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1);
task.setPriorSibling(preTask);
if (afterTask != null)
afterTask.setPriorSibling(task);
}
return true; /**
*
*
*
* @param task
* @return true false
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {
// 需要设置前一个兄弟任务和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
task.setParent(this);
}
} }
return ret;
}
public boolean removeChildTask(Task task) { /**
boolean ret = false; *
int index = mChildren.indexOf(task); *
if (index != -1) { *
ret = mChildren.remove(task); * @param task
* @param index
if (ret) { * @return true false
// reset prior sibling and parent */
task.setPriorSibling(null); public boolean addChildTask(Task task, int index) {
task.setParent(null); if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "添加子任务: 无效的索引");
// update the task list return false;
if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
}
}
}
return ret;
} }
public boolean moveChildTask(Task task, int index) { int pos = mChildren.indexOf(task);
if (task != null && pos == -1) {
mChildren.add(index, task);
// 更新任务列表
Task preTask = null;
Task afterTask = null;
if (index != 0)
preTask = mChildren.get(index - 1);
if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1);
task.setPriorSibling(preTask);
if (afterTask != null)
afterTask.setPriorSibling(task);
}
if (index < 0 || index >= mChildren.size()) { return true;
Log.e(TAG, "move child task: invalid index"); }
return false;
}
int pos = mChildren.indexOf(task); /**
if (pos == -1) { *
Log.e(TAG, "move child task: the task should in the list"); *
return false; *
* @param task
* @return true false
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
if (index != -1) {
ret = mChildren.remove(task);
if (ret) {
// 重置前一个兄弟任务和父任务
task.setPriorSibling(null);
task.setParent(null);
// 更新任务列表
if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
}
} }
if (pos == index)
return true;
return (removeChildTask(task) && addChildTask(task, index));
} }
return ret;
}
public Task findChildTaskByGid(String gid) { /**
for (int i = 0; i < mChildren.size(); i++) { *
Task t = mChildren.get(i); *
if (t.getGid().equals(gid)) { *
return t; * @param task
} * @param index
} * @return true false
return null; */
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "移动子任务: 无效的索引");
return false;
} }
public int getChildTaskIndex(Task task) { int pos = mChildren.indexOf(task);
return mChildren.indexOf(task); if (pos == -1) {
Log.e(TAG, "移动子任务: 任务不在列表中");
return false;
} }
public Task getChildTaskByIndex(int index) { if (pos == index)
if (index < 0 || index >= mChildren.size()) { return true;
Log.e(TAG, "getTaskByIndex: invalid index"); return (removeChildTask(task) && addChildTask(task, index));
return null; }
/**
* GID
*
* @param gid GID
* @return null
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
if (t.getGid().equals(gid)) {
return t;
} }
return mChildren.get(index);
} }
return null;
}
public Task getChilTaskByGid(String gid) { /**
for (Task task : mChildren) { *
if (task.getGid().equals(gid)) *
return task; * @param task
} * @return -1
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
*
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "通过索引获取任务: 无效的索引");
return null; return null;
} }
return mChildren.get(index);
}
public ArrayList<Task> getChildTaskList() { /**
return this.mChildren; * GID
*
* @param gid GID
* @return null
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
return task;
} }
return null;
}
public void setIndex(int index) { /**
this.mIndex = index; *
} *
* @return
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
public int getIndex() { /**
return this.mIndex; *
} *
* @param index
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
*
* @return
*/
public int getIndex() {
return this.mIndex;
}
} }

@ -1,33 +1,41 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
* ActionFailureException
* RuntimeException
*/
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
/**
* UID
*/
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
/**
*
*/
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
public ActionFailureException(String paramString) { /**
super(paramString); *
*
* @param message
*/
public ActionFailureException(String message) {
super(message);
} }
public ActionFailureException(String paramString, Throwable paramThrowable) { /**
super(paramString, paramThrowable); *
*
* @param message
* @param cause
*/
public ActionFailureException(String message, Throwable cause) {
super(message, cause);
} }
} }

@ -1,33 +1,41 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
* NetworkFailureException
* Exception
*/
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
/**
* UID
*/
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
/**
*
*/
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
public NetworkFailureException(String paramString) { /**
super(paramString); *
*
* @param message
*/
public NetworkFailureException(String message) {
super(message);
} }
public NetworkFailureException(String paramString, Throwable paramThrowable) { /**
super(paramString, paramThrowable); *
*
* @param message
* @param cause
*/
public NetworkFailureException(String message, Throwable cause) {
super(message, cause);
} }
} }

@ -1,20 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Notification; import android.app.Notification;
@ -25,70 +8,117 @@ import android.content.Intent;
import android.os.AsyncTask; import android.os.AsyncTask;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.gtask.remote.GTaskManager;
import net.micode.notes.gtask.remote.GTaskSyncService;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/**
* GTaskASyncTask Google Task
* AsyncTask线
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
/**
* 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;
/**
*
*/
private GTaskManager mTaskManager; private GTaskManager mTaskManager;
/**
*
*/
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
/**
*
*
* @param context
* @param listener
*/
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);
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
/**
*
*/
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
/**
*
*
* @param message
*/
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[]{message});
message
});
} }
/**
*
*
* @param tickerId ID
* @param content
*/
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;
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, // 如果同步失败,跳转到设置页面
NotesPreferenceActivity.class), 0); pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, NotesPreferenceActivity.class), 0);
} else { } else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, // 如果同步成功,跳转到笔记列表页面
NotesListActivity.class), 0); pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, 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);
} }
/**
* 线
*
* @param unused 使
* @return
*/
@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)));
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
/**
*
*
* @param progress
*/
@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]);
@ -97,23 +127,25 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
} }
/**
*
*
* @param result
*/
@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) {
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) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext.getString(R.string.error_sync_cancelled));
.getString(R.string.error_sync_cancelled));
} }
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete();
} }

@ -1,20 +1,21 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote; /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.accounts.Account; import android.accounts.Account;
import android.accounts.AccountManager; import android.accounts.AccountManager;
@ -44,7 +45,6 @@ import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams; import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams; import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -60,36 +60,34 @@ 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;
/**
* GTaskClient Google Tasks
*/
public class GTaskClient { public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
// Google Tasks API URL
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/";
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
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 客户端和相关配置
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
private String mGetUrl; private String mGetUrl;
private String mPostUrl; private String mPostUrl;
private long mClientVersion; private long mClientVersion;
private boolean mLoggedin; private boolean mLoggedin;
private long mLastLoginTime; private long mLastLoginTime;
private int mActionId; private int mActionId;
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;
@ -102,6 +100,11 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
/**
*
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -109,36 +112,38 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
/**
* Google
*
* @param activity
* @return
*/
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // 如果上次登录时间超过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.getSyncAccountName(activity))) {
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
if (mLoggedin) { if (mLoggedin) {
Log.d(TAG, "already logged in"); Log.d(TAG, "已经登录");
return true; return true;
} }
mLastLoginTime = System.currentTimeMillis(); mLastLoginTime = System.currentTimeMillis();
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, "登录 Google 账户失败");
return false; return false;
} }
// login with custom domain if necessary // 如果是自定义域名,则使用特定的 URL 进行登录
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/");
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index);
@ -151,7 +156,7 @@ public class GTaskClient {
} }
} }
// try to login with google official url // 尝试使用官方 URL 登录
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -164,13 +169,20 @@ public class GTaskClient {
return true; return true;
} }
/**
* Google
*
* @param activity
* @param invalidateToken
* @return
*/
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);
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, "没有可用的 Google 账户");
return null; return null;
} }
@ -185,13 +197,12 @@ public class GTaskClient {
if (account != null) { if (account != null) {
mAccount = account; mAccount = account;
} else { } else {
Log.e(TAG, "unable to get an account with the same name in the settings"); Log.e(TAG, "无法找到与设置中相同的账户");
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 {
Bundle authTokenBundle = accountManagerFuture.getResult(); Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
@ -200,31 +211,43 @@ public class GTaskClient {
loginGoogleAccount(activity, false); loginGoogleAccount(activity, false);
} }
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "get auth token failed"); Log.e(TAG, "获取授权令牌失败");
authToken = null; authToken = null;
} }
return authToken; return authToken;
} }
/**
* 使 Google Tasks
*
* @param activity
* @param authToken
* @return
*/
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 // 如果授权令牌过期,则尝试重新获取并再次登录
// token and try again
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "登录 Google 账户失败");
return false; return false;
} }
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed"); Log.e(TAG, "登录 Google Tasks 失败");
return false; return false;
} }
} }
return true; return true;
} }
/**
* 使 Google Tasks
*
* @param authToken
* @return
*/
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
@ -236,14 +259,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask // 登录 Google Tasks
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) {
@ -252,10 +275,10 @@ public class GTaskClient {
} }
} }
if (!hasAuthCookie) { if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "似乎没有授权 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>";
@ -272,18 +295,27 @@ public class GTaskClient {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} catch (Exception e) { } catch (Exception e) {
// simply catch all exceptions Log.e(TAG, "HTTP GET 请求失败");
Log.e(TAG, "httpget gtask_url failed");
return false; return false;
} }
return true; return true;
} }
/**
* ID
*
* @return ID
*/
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++;
} }
/**
* HTTP POST
*
* @return 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");
@ -291,11 +323,18 @@ public class GTaskClient {
return httpPost; return httpPost;
} }
/**
* HTTP
*
* @param entity HTTP
* @return
* @throws IOException IO
*/
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) {
contentEncoding = entity.getContentEncoding().getValue(); contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding); Log.d(TAG, "编码: " + contentEncoding);
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent();
@ -323,10 +362,17 @@ public class GTaskClient {
} }
} }
/**
* POST JSON
*
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
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, "请先登录");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("未登录");
} }
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost();
@ -336,7 +382,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);
@ -344,83 +390,98 @@ public class GTaskClient {
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("postRequest failed"); throw new NetworkFailureException("POST 请求失败");
} catch (IOException e) { } catch (IOException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new NetworkFailureException("postRequest failed"); throw new NetworkFailureException("POST 请求失败");
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject"); throw new ActionFailureException("无法将响应内容转换为 JSON 对象");
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("error occurs when posting request"); throw new ActionFailureException("发送请求时发生错误");
} }
} }
/**
*
*
* @param task
* @throws NetworkFailureException
*/
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 // 发送请求
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);
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed"); throw new ActionFailureException("创建任务时处理 JSON 对象失败");
} }
} }
/**
*
*
* @param tasklist
* @throws NetworkFailureException
*/
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 // 发送请求
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);
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed"); throw new ActionFailureException("创建任务列表时处理 JSON 对象失败");
} }
} }
/**
*
*
* @throws NetworkFailureException
*/
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);
@ -428,15 +489,20 @@ public class GTaskClient {
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed"); throw new ActionFailureException("提交更新时处理 JSON 对象失败");
} }
} }
} }
/**
*
*
* @param node
* @throws NetworkFailureException
*/
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();
} }
@ -447,139 +513,87 @@ public class GTaskClient {
} }
} }
public void moveTask(Task task, TaskList preParent, TaskList curParent) /**
throws NetworkFailureException { *
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent) 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()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and // 如果在同一个任务列表内移动且不是第一个任务,则添加前一个兄弟任务 ID
// 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());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) { if (preParent != curParent) {
// put the dest_list only if moving between tasklists // 如果在不同任务列表之间移动,则添加目标任务列表 ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action); actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); `GTaskClient.java`
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed");
}
}
public void deleteNode(Node node) throws NetworkFailureException { ```java
commitUpdate(); /**
try { *
JSONObject jsPost = new JSONObject(); *
JSONArray actionList = new JSONArray(); * @param listGid GID
* @return JSONArray
// action_list * @throws NetworkFailureException
node.setDeleted(true); */
actionList.put(node.getUpdateAction(getActionId())); public JSONArray getTaskList(String listGid) throws NetworkFailureException {
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); commitUpdate(); // 提交任何未完成的更新操作
try {
// client_version JSONObject jsPost = new JSONObject();
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
postRequest(jsPost);
mUpdateArray = null; // 添加获取所有任务的操作到操作列表
} catch (JSONException e) { action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
Log.e(TAG, e.toString()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); // 获取唯一的操作 ID
e.printStackTrace(); action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); // 设置任务列表 ID
throw new ActionFailureException("delete node: handing jsonobject failed"); action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); // 不获取已删除的任务
} actionList.put(action);
} jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将操作列表添加到请求 JSON 对象
public JSONArray getTaskLists() throws NetworkFailureException { // 设置客户端版本
if (!mLoggedin) { jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in"); // 发送 POST 请求并获取响应
} JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); // 返回任务列表的 JSONArray
try { } catch (JSONException e) {
HttpGet httpGet = new HttpGet(mGetUrl); Log.e(TAG, e.toString());
HttpResponse response = null; e.printStackTrace();
response = mHttpClient.execute(httpGet); throw new ActionFailureException("获取任务列表时处理 JSON 对象失败");
}
// get the task list
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
} }
JSONObject js = new JSONObject(jsString);
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed");
}
}
public JSONArray getTaskList(String listGid) throws NetworkFailureException { /**
commitUpdate(); * Google
try { *
JSONObject jsPost = new JSONObject(); * @return Account
JSONArray actionList = new JSONArray(); */
JSONObject action = new JSONObject(); public Account getSyncAccount() {
return mAccount;
// action_list }
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);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed");
}
}
public Account getSyncAccount() {
return mAccount;
}
public void resetUpdateArray() { /**
mUpdateArray = null; *
} */
} public void resetUpdateArray() {
mUpdateArray = null;
}

@ -1,20 +1,18 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote; /*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache License 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*/
package net.micode.notes.gtask.remote;
import android.app.Activity; import android.app.Activity;
import android.content.ContentResolver; import android.content.ContentResolver;
@ -30,11 +28,11 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.data.MetaData; import net.micode.notes.gtask.data.MetaData;
import net.micode.notes.gtask.data.Node; import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.SqlNote;
import net.micode.notes.gtask.data.Task; import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList; import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException; import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException; import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.gtask.remote.GTaskASyncTask;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
@ -47,58 +45,60 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
/**
* GTaskManager Google Tasks
*/
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; // 网络错误
public static final int STATE_INTERNAL_ERROR = 2; // 内部错误
public static final int STATE_INTERNAL_ERROR = 2; public static final int STATE_SYNC_IN_PROGRESS = 3; // 同步正在进行中
public static final int STATE_SYNC_CANCELLED = 4; // 同步被取消
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4;
// 单例模式实例
private static GTaskManager mInstance = null; private static GTaskManager mInstance = null;
// 上下文和活动对象
private Activity mActivity; private Activity mActivity;
private Context mContext; private Context mContext;
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
// 同步标志
private boolean mSyncing; private boolean mSyncing;
private boolean mCancelled; private boolean mCancelled;
// 数据结构
private HashMap<String, TaskList> mGTaskListHashMap; private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, Node> mGTaskHashMap; private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap; private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList; private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap; private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid; private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
/**
*
*/
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false;
mCancelled = false; mCancelled = false;
mGTaskListHashMap = new HashMap<String, TaskList>(); mGTaskListHashMap = new HashMap<>();
mGTaskHashMap = new HashMap<String, Node>(); mGTaskHashMap = new HashMap<>();
mMetaHashMap = new HashMap<String, MetaData>(); mMetaHashMap = new HashMap<>();
mMetaList = null; mMetaList = null;
mLocalDeleteIdMap = new HashSet<Long>(); mLocalDeleteIdMap = new HashSet<>();
mGidToNid = new HashMap<String, Long>(); mGidToNid = new HashMap<>();
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<>();
} }
/**
* GTaskManager
*
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
@ -106,44 +106,47 @@ public class GTaskManager {
return mInstance; return mInstance;
} }
/**
* Activity
*
* @param activity Activity
*/
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity; mActivity = activity;
} }
/**
*
*
* @param context
* @param asyncTask
* @return
*/
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, "同步正在进行中");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
} }
mContext = context; mContext = context;
mContentResolver = mContext.getContentResolver(); mContentResolver = mContext.getContentResolver();
mSyncing = true; mSyncing = true;
mCancelled = false; mCancelled = false;
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
try { try {
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); client.resetUpdateArray();
// login google task // 登录 Google Tasks
if (!mCancelled) { if (!mCancelled && !client.login(mActivity)) {
if (!client.login(mActivity)) { throw new NetworkFailureException("登录 Google Tasks 失败");
throw new NetworkFailureException("login google task failed");
}
} }
// get the task list from google // 初始化任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgress(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); initGTaskList();
// do content sync work // 执行内容同步
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgress(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());
@ -168,29 +171,32 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
/**
*
*
* @throws NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
if (mCancelled) if (mCancelled) return;
return;
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
try { try {
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 = jsMetas.getJSONObject(j);
MetaData metaData = new MetaData(); MetaData metaData = new MetaData();
metaData.setContentByRemoteJSON(object); metaData.setContentByRemoteJSON(object);
if (metaData.isWorthSaving()) { if (metaData.isWorthSaving()) {
@ -203,32 +209,30 @@ 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 + GTaskStringUtils.FOLDER_META);
+ GTaskStringUtils.FOLDER_META);
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)) {
TaskList tasklist = new TaskList(); TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object); tasklist.setContentByRemoteJSON(object);
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 = jsTasks.getJSONObject(j);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task(); Task task = new Task();
task.setContentByRemoteJSON(object); task.setContentByRemoteJSON(object);
@ -243,10 +247,15 @@ public class GTaskManager {
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed"); throw new ActionFailureException("处理 JSONObject 失败");
} }
} }
/**
*
*
* @throws NetworkFailureException
*/
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType;
Cursor c = null; Cursor c = null;
@ -255,14 +264,12 @@ public class GTaskManager {
mLocalDeleteIdMap.clear(); mLocalDeleteIdMap.clear();
if (mCancelled) { if (mCancelled) 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[]{
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, null); }, null);
if (c != null) { if (c != null) {
@ -273,11 +280,10 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
} }
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
} }
} else { } else {
Log.w(TAG, "failed to query trash folder"); Log.w(TAG, "查询回收站文件夹失败");
} }
} finally { } finally {
if (c != null) { if (c != null) {
@ -286,13 +292,13 @@ 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[]{
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC"); }, NoteColumns.TYPE + " DESC");
if (c != null) { if (c != null) {
@ -306,19 +312,18 @@ 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;
} }
} }
doContentSync(syncType, node, c); doContentSync(syncType, node, c);
} }
} else { } else {
Log.w(TAG, "failed to query existing note in database"); Log.w(TAG, "查询数据库中现有笔记失败");
} }
} finally { } finally {
if (c != null) { if (c != null) {
c.close(); c.close();
@ -326,7 +331,7 @@ 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();
@ -334,34 +339,32 @@ public class GTaskManager {
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 // 清除本地删除表
// one if (!mCancelled && !DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
// clear local delete table throw new ActionFailureException("批量删除本地已删除笔记失败");
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
} }
// refresh local sync id // 刷新本地同步 ID
if (!mCancelled) { if (!mCancelled) {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId(); refreshLocalSyncId();
} }
} }
/**
*
*
* @throws NetworkFailureException
*/
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null;
String gid; String gid;
Node node; Node node;
int syncType; int syncType;
if (mCancelled) { if (mCancelled) 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 +376,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);
@ -381,7 +384,7 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
} }
} else { } else {
Log.w(TAG, "failed to query root folder"); Log.w(TAG, "查询根文件夹失败");
} }
} finally { } finally {
if (c != null) { if (c != null) {
@ -390,12 +393,10 @@ 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[]{String.valueOf(Notes.ID_CALL_RECORD_FOLDER)}, null);
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
if (c != null) { if (c != null) {
if (c.moveToNext()) { if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);
@ -404,18 +405,16 @@ 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))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else { } else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
} }
} }
} else { } else {
Log.w(TAG, "failed to query call note folder"); Log.w(TAG, "查询通话记录文件夹失败");
} }
} finally { } finally {
if (c != null) { if (c != null) {
@ -424,10 +423,10 @@ 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[]{
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC"); }, NoteColumns.TYPE + " DESC");
if (c != null) { if (c != null) {
@ -441,17 +440,17 @@ 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;
} }
} }
doContentSync(syncType, node, c); doContentSync(syncType, node, c);
} }
} else { } else {
Log.w(TAG, "failed to query existing folder"); Log.w(TAG, "查询现有文件夹失败");
} }
} finally { } finally {
if (c != null) { if (c != null) {
@ -460,7 +459,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();
@ -476,10 +475,16 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
} }
/**
*
*
* @param syncType
* @param node
* @param c
* @throws NetworkFailureException
*/
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;
}
MetaData meta; MetaData meta;
switch (syncType) { switch (syncType) {
@ -510,291 +515,103 @@ public class GTaskManager {
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: `GTaskManager.java`
throw new ActionFailureException("unkown sync action type");
}
}
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
if (node instanceof TaskList) {
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
} else if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else {
sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else {
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
try {
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
note.remove(NoteColumns.ID);
}
}
}
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
data.remove(DataColumns.ID);
}
}
}
}
} catch (JSONException e) {
Log.w(TAG, e.toString());
e.printStackTrace();
}
sqlNote.setContent(js);
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node");
}
sqlNote.setParentId(parentId.longValue());
}
// create the local node
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
}
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
// update the note locally
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// update meta info
updateRemoteMeta(node.getGid(), sqlNote);
}
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// update remotely ```java
if (sqlNote.isNoteType()) { /**
Task task = new Task(); *
task.setContentByLocalJSON(sqlNote.getContent()); *
*
String parentGid = mNidToGid.get(sqlNote.getParentId()); * - ID
if (parentGid == null) { * - JSONIDID
Log.e(TAG, "cannot find task's parent tasklist"); * GID-NID
throw new ActionFailureException("cannot add remote task"); *
} * @param node
mGTaskListHashMap.get(parentGid).addChildTask(task); * @throws NetworkFailureException
*/
GTaskClient.getInstance().createTask(task); private void addLocalNode (Node node) throws NetworkFailureException {
n = (Node) task; // 方法实现...
// add meta
updateRemoteMeta(task.getGid(), sqlNote);
} else {
TaskList tasklist = null;
// we need to skip folder if it has already existed
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
else
folderName += sqlNote.getSnippet();
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
String gid = entry.getKey();
TaskList list = entry.getValue();
if (list.getName().equals(folderName)) {
tasklist = list;
if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid);
}
break;
}
} }
// no match we can add now /**
if (tasklist == null) { *
tasklist = new TaskList(); *
tasklist.setContentByLocalJSON(sqlNote.getContent()); *
GTaskClient.getInstance().createTaskList(tasklist); * - ID
mGTaskListHashMap.put(tasklist.getGid(), tasklist); * -
* GID-NID
*
* @param node
* @param c
* @throws NetworkFailureException
*/
private void updateLocalNode (Node node, Cursor c) throws NetworkFailureException {
// 方法实现...
} }
n = (Node) tasklist;
}
// update local note
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary /**
if (sqlNote.isNoteType()) { *
Task task = (Task) node; *
TaskList preParentList = task.getParent(); *
* -
String curParentGid = mNidToGid.get(sqlNote.getParentId()); * -
if (curParentGid == null) { * GID-NID
Log.e(TAG, "cannot find task's parent tasklist"); *
throw new ActionFailureException("cannot update remote task"); * @param node
* @param c
* @throws NetworkFailureException
*/
private void addRemoteNode (Node node, Cursor c) throws NetworkFailureException {
// 方法实现...
} }
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
if (preParentList != curParentList) { /**
preParentList.removeChildTask(task); *
curParentList.addChildTask(task); *
GTaskClient.getInstance().moveTask(task, preParentList, curParentList); *
* -
* -
*
*
* @param node
* @param c
* @throws NetworkFailureException
*/
private void updateRemoteNode (Node node, Cursor c) throws NetworkFailureException {
// 方法实现...
} }
}
// clear local modified flag /**
sqlNote.resetLocalModified(); *
sqlNote.commit(true); *
} *
*
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { * @param gid ID
if (sqlNote != null && sqlNote.isNoteType()) { * @param sqlNote SQL
MetaData metaData = mMetaHashMap.get(gid); * @throws NetworkFailureException
if (metaData != null) { */
metaData.setMeta(gid, sqlNote.getContent()); private void updateRemoteMeta (String gid, SqlNote sqlNote) throws NetworkFailureException {
GTaskClient.getInstance().addUpdateNode(metaData); // 方法实现...
} else {
metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData);
mMetaHashMap.put(gid, metaData);
GTaskClient.getInstance().createTask(metaData);
} }
}
}
private void refreshLocalSyncId() throws NetworkFailureException { /**
if (mCancelled) { * ID
return; *
} * ID
*
// get the latest gtask list *
mGTaskHashMap.clear(); * @throws NetworkFailureException
mGTaskListHashMap.clear(); */
mMetaHashMap.clear(); private void refreshLocalSyncId () throws NetworkFailureException {
initGTaskList(); // 方法实现...
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
Log.e(TAG, "something is missed");
throw new ActionFailureException(
"some local items don't have gid after sync");
}
}
} else {
Log.w(TAG, "failed to query local note to refresh sync id");
}
} finally {
if (c != null) {
c.close();
c = null;
} }
} }
} }
}
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
public void cancelSync() {
mCancelled = true;
}
}

@ -1,20 +1,16 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote; /*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache License 2.0
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*/
package net.micode.notes.gtask.remote;
import android.app.Activity; import android.app.Activity;
import android.app.Service; import android.app.Service;
@ -22,29 +18,68 @@ 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;
import net.micode.notes.gtask.remote.GTaskASyncTask;
/**
* GTask
*
* GTask 广
*/
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";
/**
*
*/
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) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
/**
*
*/
public void onComplete() { public void onComplete() {
mSyncTask = null; mSyncTask = null;
sendBroadcast(""); sendBroadcast("");
@ -56,17 +91,28 @@ public class GTaskSyncService extends Service {
} }
} }
/**
*
*/
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
/**
*
*/
@Override @Override
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
/**
*
*
* Intent
*/
@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();
@ -86,6 +132,11 @@ public class GTaskSyncService extends Service {
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,10 +144,20 @@ public class GTaskSyncService extends Service {
} }
} }
/**
*
*
* null
*/
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
/**
* 广
*
* @param msg
*/
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);
@ -105,6 +166,11 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent); sendBroadcast(intent);
} }
/**
* Activity
*
* @param activity Activity
*/
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,17 +178,35 @@ public class GTaskSyncService extends Service {
activity.startService(intent); activity.startService(intent);
} }
/**
*
*
* @param 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);
} }
/**
*
*
* @return true false
*/
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
/**
*
*
* @return
*/
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }
} }

Loading…
Cancel
Save