Compare commits

...

4 Commits

@ -48,12 +48,12 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
public class GTaskManager { public class GTaskManager {// 该类用于管理 GTasks
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();// TAG 用于打印日志
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;
@ -87,7 +87,7 @@ public class GTaskManager {
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<String, TaskList>();
@ -99,19 +99,19 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>();
} }
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() { // 单例模式
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
} }
return mInstance; return mInstance;
} }
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) { // 设置 activity
// used for getting authtoken // used for getting authtoken
mActivity = activity; mActivity = activity;
} }
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) { // 同步
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
@ -127,25 +127,25 @@ public class GTaskManager {
mGidToNid.clear(); mGidToNid.clear();
mNidToGid.clear(); mNidToGid.clear();
try { try { // try catch 语句
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); client.resetUpdateArray();
// login google task // login google task
if (!mCancelled) { if (!mCancelled) {// 如果没有取消
if (!client.login(mActivity)) { if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed"); throw new NetworkFailureException("login google task failed");
} }
} }
// get the task list from google // get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));// 发布进度
initGTaskList(); initGTaskList();
// do content sync work // do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));// 发布进度
syncContent(); syncContent();
} catch (NetworkFailureException e) { } catch (NetworkFailureException e) {// 捕获异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR; return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) { } catch (ActionFailureException e) {
@ -155,7 +155,7 @@ public class GTaskManager {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} finally { } finally {// finally 语句
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -165,25 +165,25 @@ public class GTaskManager {
mSyncing = false; mSyncing = false;
} }
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;// 返回状态
} }
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {// 初始化 GTasks
if (mCancelled) if (mCancelled)
return; return;
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();// 获取 GTasks 客户端
try { try {
JSONArray jsTaskLists = client.getTaskLists(); JSONArray jsTaskLists = client.getTaskLists();// 获取 GTasks 列表
// init meta list first // init meta list first
mMetaList = null; mMetaList = null;// 初始化 meta 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 if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {// 如果是 meta 文件夹
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object); mMetaList.setContentByRemoteJSON(object);
@ -204,6 +204,7 @@ public class GTaskManager {
} }
// create meta list if not existed // create meta list if not existed
// 创建 meta list
if (mMetaList == null) { if (mMetaList == null) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -212,6 +213,7 @@ public class GTaskManager {
} }
// init task list // init task list
// 初始化 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);
@ -240,14 +242,14 @@ 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("initGTaskList: handing JSONObject failed");
} }
} }
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {// 同步内容
int syncType; int syncType;
Cursor c = null; Cursor c = null;
String gid; String gid;
@ -255,12 +257,12 @@ public class GTaskManager {
mLocalDeleteIdMap.clear(); mLocalDeleteIdMap.clear();
if (mCancelled) { if (mCancelled) {// 如果取消
return; return;
} }
// for local deleted note // for local deleted note
try { 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)
@ -290,16 +292,16 @@ public class GTaskManager {
syncFolder(); syncFolder();
// for note existing in database // for note existing in database
try { 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) {// 如果 c 不为空
while (c.moveToNext()) { while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) {// 如果 node 不为空
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
@ -319,7 +321,7 @@ public class GTaskManager {
Log.w(TAG, "failed to query existing note in database"); Log.w(TAG, "failed to query existing note in database");
} }
} finally { } finally { // finally 语句
if (c != null) { if (c != null) {
c.close(); c.close();
c = null; c = null;
@ -327,6 +329,7 @@ public class GTaskManager {
} }
// go through remaining items // go through remaining items
// for note not existing in database
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();
@ -351,7 +354,7 @@ public class GTaskManager {
} }
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {// 同步文件夹
Cursor c = null; Cursor c = null;
String gid; String gid;
Node node; Node node;
@ -362,26 +365,28 @@ public class GTaskManager {
} }
// for root folder // for root folder
try { try {// try 语句
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,// 通过id查询
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext();
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);// 获取gtask_id
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); // for system folder, only
// update remote name if
// necessary
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 // 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);
} 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 root folder"); Log.w(TAG, "failed to query root folder");// 查询根文件夹失败
} }
} finally { } finally {
if (c != null) { if (c != null) {
@ -392,24 +397,27 @@ public class GTaskManager {
// for call-note folder // 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=?)",// 通过id查询
new String[] { new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER) String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null); }, null);
if (c != null) { if (c != null) { // 如果 c 不为空
if (c.moveToNext()) { if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN); gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid); node = mGTaskHashMap.get(gid);
if (node != null) { if (node != null) {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);// for system folder,
// only update
// remote name if
// necessary
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 // for system folder, only update remote name if
// necessary // 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);
} }
@ -522,29 +530,29 @@ public class GTaskManager {
} }
} }
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException { // 添加本地节点
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote; SqlNote sqlNote; // sql笔记
if (node instanceof TaskList) { if (node instanceof TaskList) {
if (node.getName().equals( if (node.getName().equals(// 根目录
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
} else if (node.getName().equals( } else if (node.getName().equals(// 回收站
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { // 通话记录
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else { } else {// 其他文件夹
sqlNote = new SqlNote(mContext); sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setParentId(Notes.ID_ROOT_FOLDER); sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
} }
} else { } else {// 其他节点
sqlNote = new SqlNote(mContext); sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent(); JSONObject js = node.getLocalJSONFromContent();
try { try {
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {// 备注
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) { if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID); long id = note.getLong(NoteColumns.ID);
@ -555,7 +563,7 @@ public class GTaskManager {
} }
} }
if (js.has(GTaskStringUtils.META_HEAD_DATA)) { if (js.has(GTaskStringUtils.META_HEAD_DATA)) {// 数据
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.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);
@ -570,18 +578,18 @@ public class GTaskManager {
} }
} }
} catch (JSONException e) { } catch (JSONException e) {// json异常
Log.w(TAG, e.toString()); Log.w(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
sqlNote.setContent(js); sqlNote.setContent(js);// 设置内容
Long parentId = mGidToNid.get(((Task) node).getParent().getGid()); Long parentId = mGidToNid.get(((Task) node).getParent().getGid());// 获取父节点
if (parentId == null) { if (parentId == null) {// 父节点为空
Log.e(TAG, "cannot find task's parent id locally"); Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node"); throw new ActionFailureException("cannot add local node");
} }
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());// 设置父节点
} }
// create the local node // create the local node
@ -596,17 +604,17 @@ public class GTaskManager {
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {// 更新本地节点
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote; SqlNote sqlNote;// sql笔记
// update the note locally // update the note locally
sqlNote = new SqlNote(mContext, c); sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());// 设置内容
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())// 获取父节点
: new Long(Notes.ID_ROOT_FOLDER); : new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) { if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally"); Log.e(TAG, "cannot find task's parent id locally");
@ -616,10 +624,10 @@ public class GTaskManager {
sqlNote.commit(true); sqlNote.commit(true);
// update meta info // update meta info
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);// 更新远程元数据
} }
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {// 添加远程节点
if (mCancelled) { if (mCancelled) {
return; return;
} }
@ -628,7 +636,7 @@ public class GTaskManager {
Node n; Node n;
// update remotely // update remotely
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {// 笔记类型
Task task = new Task(); Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent()); task.setContentByLocalJSON(sqlNote.getContent());
@ -644,7 +652,7 @@ public class GTaskManager {
// add meta // add meta
updateRemoteMeta(task.getGid(), sqlNote); updateRemoteMeta(task.getGid(), sqlNote);
} else { } else {// 文件夹类型
TaskList tasklist = null; TaskList tasklist = null;
// we need to skip folder if it has already existed // we need to skip folder if it has already existed
@ -656,8 +664,8 @@ public class GTaskManager {
else else
folderName += sqlNote.getSnippet(); folderName += sqlNote.getSnippet();
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();
String gid = entry.getKey(); String gid = entry.getKey();
TaskList list = entry.getValue(); TaskList list = entry.getValue();
@ -672,7 +680,7 @@ public class GTaskManager {
} }
// no match we can add now // no match we can add now
if (tasklist == null) { if (tasklist == null) {// 任务列表为空
tasklist = new TaskList(); tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent()); tasklist.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().createTaskList(tasklist); GTaskClient.getInstance().createTaskList(tasklist);
@ -682,7 +690,7 @@ public class GTaskManager {
} }
// update local note // update local note
sqlNote.setGtaskId(n.getGid()); sqlNote.setGtaskId(n.getGid());// 设置gid
sqlNote.commit(false); sqlNote.commit(false);
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
@ -692,7 +700,7 @@ public class GTaskManager {
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {// 更新远程节点
if (mCancelled) { if (mCancelled) {
return; return;
} }
@ -730,7 +738,7 @@ public class GTaskManager {
sqlNote.commit(true); sqlNote.commit(true);
} }
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {// 更新远程元数据
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) { if (metaData != null) {
@ -746,7 +754,7 @@ public class GTaskManager {
} }
} }
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {// 刷新本地同步id
if (mCancelled) { if (mCancelled) {
return; return;
} }
@ -758,12 +766,12 @@ public class GTaskManager {
initGTaskList(); initGTaskList();
Cursor c = null; Cursor c = null;
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)
}, NoteColumns.TYPE + " DESC"); }, NoteColumns.TYPE + " DESC");
if (c != null) { if (c != null) {// 如果游标不为空
while (c.moveToNext()) { while (c.moveToNext()) {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN); String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid); Node node = mGTaskHashMap.get(gid);
@ -773,7 +781,7 @@ public class GTaskManager {
values.put(NoteColumns.SYNC_ID, node.getLastModified()); values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null); c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else { } else { // if we can't find the node, it means the node is deleted remotely
Log.e(TAG, "something is missed"); Log.e(TAG, "something is missed");
throw new ActionFailureException( throw new ActionFailureException(
"some local items don't have gid after sync"); "some local items don't have gid after sync");
@ -792,9 +800,10 @@ public class GTaskManager {
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} } // 获取同步账户
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} } // 取消同步
} }

@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.ui; package net.micode.notes.ui; //该类所在的包名
import android.content.Context; import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
@ -29,25 +29,30 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
// FoldersListAdapter 类的定义,扩展了 CursorAdapter 类。
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
// 定义数据库查询的投影和列的索引
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1; public static final int NAME_COLUMN = 1;
// FoldersListAdapter 类的构造函数,它调用父类的构造函数。
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
//CursorAdapter 类的一个方法的实现,用于创建新的列表项视图。
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context); return new FolderListItem(context);
} }
// CursorAdapter 类的一个方法的实现,用于将数据绑定到列表项视图上。
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {
@ -57,12 +62,15 @@ public class FoldersListAdapter extends CursorAdapter {
} }
} }
// 自定义方法,用于获取指定位置的文件夹名称
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
// FoldersListAdapter 类的一个内部类,用于表示列表项视图。它扩展了 LinearLayout 类,并维护了一个 TextView 来显示文件夹名称。
// bind() 方法用于将数据绑定到列表项视图上
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
private TextView mName; private TextView mName;

@ -74,7 +74,7 @@ import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
private class HeadViewHolder { private class HeadViewHolder { // 头部视图的持有者
public TextView tvModified; public TextView tvModified;
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
@ -85,7 +85,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static { static { // 背景选择器按钮的映射
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED);
sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);
@ -94,7 +94,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static { // 背景选择器选择的映射
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select);
sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select);
@ -103,7 +103,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static { static { // 字体大小按钮的映射
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);
sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM);
@ -111,54 +111,54 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {// 字体选择器选择的映射
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
} }
private static final String TAG = "NoteEditActivity"; private static final String TAG = "NoteEditActivity";// 标签
private HeadViewHolder mNoteHeaderHolder; private HeadViewHolder mNoteHeaderHolder;// 头部视图的持有者
private View mHeadViewPanel; private View mHeadViewPanel;// 头部视图面板
private View mNoteBgColorSelector; private View mNoteBgColorSelector;// 笔记背景颜色选择器
private View mFontSizeSelector; private View mFontSizeSelector;// 字体大小选择器
private EditText mNoteEditor; private EditText mNoteEditor;// 笔记编辑器
private View mNoteEditorPanel; private View mNoteEditorPanel;// 笔记编辑器面板
private WorkingNote mWorkingNote; private WorkingNote mWorkingNote;// 工作笔记
private SharedPreferences mSharedPrefs; private SharedPreferences mSharedPrefs;// 共享首选项
private int mFontSizeId; private int mFontSizeId;// 字体大小ID
private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; private static final String PREFERENCE_FONT_SIZE = "pref_font_size";// 字体大小首选项
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;// 快捷方式图标标题的最大长度
public static final String TAG_CHECKED = String.valueOf('\u221A'); public static final String TAG_CHECKED = String.valueOf('\u221A');// 标签已选中
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); public static final String TAG_UNCHECKED = String.valueOf('\u25A1');// 标签未选中
private LinearLayout mEditTextList; private LinearLayout mEditTextList;// 编辑文本列表
private String mUserQuery; private String mUserQuery;// 用户查询
private Pattern mPattern; private Pattern mPattern;// 模式
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {// 创建
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);// 调用超类的方法
this.setContentView(R.layout.note_edit); this.setContentView(R.layout.note_edit);// 设置布局
if (savedInstanceState == null && !initActivityState(getIntent())) { if (savedInstanceState == null && !initActivityState(getIntent())) {// 如果保存的实例状态为空且初始化活动状态失败
finish(); finish();
return; return;
} }
initResources(); initResources();// 初始化资源
} }
/** /**
@ -166,7 +166,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* user load this activity, we should restore the former state * user load this activity, we should restore the former state
*/ */
@Override @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { protected void onRestoreInstanceState(Bundle savedInstanceState) {//
super.onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);

@ -37,7 +37,7 @@ import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class NoteEditText extends EditText { public class NoteEditText extends EditText {//继承自EditText
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText";
private int mIndex; private int mIndex;
private int mSelectionStartBeforeDelete; private int mSelectionStartBeforeDelete;
@ -56,51 +56,51 @@ public class NoteEditText extends EditText {
/** /**
* Call by the {@link NoteEditActivity} to delete or add edit text * Call by the {@link NoteEditActivity} to delete or add edit text
*/ */
public interface OnTextViewChangeListener { public interface OnTextViewChangeListener {//接口
/** /**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null * and the text is null
*/ */
void onEditTextDelete(int index, String text); void onEditTextDelete(int index, String text);//删除当前的edittext
/** /**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen * happen
*/ */
void onEditTextEnter(int index, String text); void onEditTextEnter(int index, String text);//在当前的edittext后面添加edittext
/** /**
* Hide or show item option when text change * Hide or show item option when text change
*/ */
void onTextChange(int index, boolean hasText); void onTextChange(int index, boolean hasText);//隐藏或显示item选项
} }
private OnTextViewChangeListener mOnTextViewChangeListener; private OnTextViewChangeListener mOnTextViewChangeListener;//接口对象
public NoteEditText(Context context) { public NoteEditText(Context context) {//构造函数
super(context, null); super(context, null);
mIndex = 0; mIndex = 0;
} }
public void setIndex(int index) { public void setIndex(int index) {
mIndex = index; mIndex = index;
} }//设置index
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {//设置接口对象
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
public NoteEditText(Context context, AttributeSet attrs) { public NoteEditText(Context context, AttributeSet attrs) {//构造函数
super(context, attrs, android.R.attr.editTextStyle); super(context, attrs, android.R.attr.editTextStyle);
} }
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { public NoteEditText(Context context, AttributeSet attrs, int defStyle) {//构造函数
super(context, attrs, defStyle); super(context, attrs, defStyle);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
@Override @Override
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {//触摸事件
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
@ -122,7 +122,7 @@ public class NoteEditText extends EditText {
} }
@Override @Override
public boolean onKeyDown(int keyCode, KeyEvent event) { public boolean onKeyDown(int keyCode, KeyEvent event) {//按键事件
switch (keyCode) { switch (keyCode) {
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
@ -139,7 +139,7 @@ public class NoteEditText extends EditText {
} }
@Override @Override
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {//按键事件
switch(keyCode) { switch(keyCode) {
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
@ -168,7 +168,7 @@ public class NoteEditText extends EditText {
} }
@Override @Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {//焦点改变事件
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
if (!focused && TextUtils.isEmpty(getText())) { if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false); mOnTextViewChangeListener.onTextChange(mIndex, false);
@ -180,7 +180,7 @@ public class NoteEditText extends EditText {
} }
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onCreateContextMenu(ContextMenu menu) {//创建上下文菜单
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {
int selStart = getSelectionStart(); int selStart = getSelectionStart();
int selEnd = getSelectionEnd(); int selEnd = getSelectionEnd();

@ -27,7 +27,7 @@ import net.micode.notes.tool.DataUtils;
public class NoteItemData { public class NoteItemData {
static final String [] PROJECTION = new String [] { static final String [] PROJECTION = new String [] {//投影
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
@ -76,7 +76,7 @@ public class NoteItemData {
private boolean mIsOneNoteFollowingFolder; private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder; private boolean mIsMultiNotesFollowingFolder;
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {//构造函数
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
@ -109,14 +109,14 @@ public class NoteItemData {
checkPostion(cursor); checkPostion(cursor);
} }
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {//检查位置
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false; mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false; mIsOneNoteFollowingFolder = false;
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {//如果是笔记并且不是第一个
int position = cursor.getPosition(); int position = cursor.getPosition();
if (cursor.moveToPrevious()) { if (cursor.moveToPrevious()) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
@ -136,89 +136,89 @@ public class NoteItemData {
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }//是否是一个文件夹
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;
} }//是否是多个文件夹
public boolean isLast() { public boolean isLast() {
return mIsLastItem; return mIsLastItem;
} }//是否是最后一个
public String getCallName() { public String getCallName() {
return mName; return mName;
} }//获取呼叫名字
public boolean isFirst() { public boolean isFirst() {
return mIsFirstItem; return mIsFirstItem;
} }//是否是第一个
public boolean isSingle() { public boolean isSingle() {
return mIsOnlyOneItem; return mIsOnlyOneItem;
} }//是否是单个
public long getId() { public long getId() {
return mId; return mId;
} }//获取id
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }//获取提醒日期
public long getCreatedDate() { public long getCreatedDate() {
return mCreatedDate; return mCreatedDate;
} }//获取创建日期
public boolean hasAttachment() { public boolean hasAttachment() {
return mHasAttachment; return mHasAttachment;
} }//是否有附件
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }//获取修改日期
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }//获取背景颜色id
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }//获取父id
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; return mNotesCount;
} }//获取笔记数量
public long getFolderId () { public long getFolderId () {
return mParentId; return mParentId;
} }//获取文件夹id
public int getType() { public int getType() {
return mType; return mType;
} }//获取类型
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }//获取小部件类型
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }//获取小部件id
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }//获取片段
public boolean hasAlert() { public boolean hasAlert() {
return (mAlertDate > 0); return (mAlertDate > 0);
} }//是否有提醒
public boolean isCallRecord() { public boolean isCallRecord() {//是否是呼叫记录
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
} }
public static int getNoteType(Cursor cursor) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }//获取笔记类型
} }

@ -78,7 +78,7 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashSet; import java.util.HashSet;
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { //用来显示所有的笔记
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int FOLDER_LIST_QUERY_TOKEN = 1;
@ -136,7 +136,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private final static int REQUEST_CODE_NEW_NODE = 103; private final static int REQUEST_CODE_NEW_NODE = 103;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {//创建
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.note_list); setContentView(R.layout.note_list);
initResources(); initResources();
@ -148,7 +148,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {//返回
if (resultCode == RESULT_OK if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
mNotesListAdapter.changeCursor(null); mNotesListAdapter.changeCursor(null);
@ -157,7 +157,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
private void setAppInfoFromRawRes() { private void setAppInfoFromRawRes() {//设置应用信息
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -204,12 +204,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
protected void onStart() { protected void onStart() {//开始
super.onStart(); super.onStart();
startAsyncNotesListQuery(); startAsyncNotesListQuery();
} }
private void initResources() { private void initResources() {//初始化资源
mContentResolver = this.getContentResolver(); mContentResolver = this.getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
@ -231,12 +231,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mModeCallBack = new ModeCallback(); mModeCallBack = new ModeCallback();
} }
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {//模式回调
private DropdownMenu mDropDownMenu; private DropdownMenu mDropDownMenu;
private ActionMode mActionMode; private ActionMode mActionMode;
private MenuItem mMoveMenu; private MenuItem mMoveMenu;
public boolean onCreateActionMode(ActionMode mode, Menu menu) { public boolean onCreateActionMode(ActionMode mode, Menu menu) {//创建
getMenuInflater().inflate(R.menu.note_list_options, menu); getMenuInflater().inflate(R.menu.note_list_options, menu);
menu.findItem(R.id.delete).setOnMenuItemClickListener(this); menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
mMoveMenu = menu.findItem(R.id.move); mMoveMenu = menu.findItem(R.id.move);
@ -269,7 +269,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
private void updateMenu() { private void updateMenu() {//更新菜单
int selectedCount = mNotesListAdapter.getSelectedCount(); int selectedCount = mNotesListAdapter.getSelectedCount();
// Update dropdown menu // Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount); String format = getResources().getString(R.string.menu_select_title, selectedCount);
@ -286,17 +286,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { public boolean onPrepareActionMode(ActionMode mode, Menu menu) {//准备
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { public boolean onActionItemClicked(ActionMode mode, MenuItem item) {//点击
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
public void onDestroyActionMode(ActionMode mode) { public void onDestroyActionMode(ActionMode mode) {//销毁
mNotesListAdapter.setChoiceMode(false); mNotesListAdapter.setChoiceMode(false);
mNotesListView.setLongClickable(true); mNotesListView.setLongClickable(true);
mAddNewNote.setVisibility(View.VISIBLE); mAddNewNote.setVisibility(View.VISIBLE);
@ -304,7 +304,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
public void finishActionMode() { public void finishActionMode() {
mActionMode.finish(); mActionMode.finish();
} }//结束
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) { boolean checked) {
@ -312,14 +312,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
updateMenu(); updateMenu();
} }
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {//菜单点击
if (mNotesListAdapter.getSelectedCount() == 0) { if (mNotesListAdapter.getSelectedCount() == 0) {
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
return true; return true;
} }
switch (item.getItemId()) { switch (item.getItemId()) {//项目
case R.id.delete: case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
@ -346,9 +346,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
private class NewNoteOnTouchListener implements OnTouchListener { private class NewNoteOnTouchListener implements OnTouchListener {//新的触摸事件
public boolean onTouch(View v, MotionEvent event) { public boolean onTouch(View v, MotionEvent event) {//触摸
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: { case MotionEvent.ACTION_DOWN: {
Display display = getWindowManager().getDefaultDisplay(); Display display = getWindowManager().getDefaultDisplay();
@ -386,7 +386,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
break; break;
} }
case MotionEvent.ACTION_MOVE: { case MotionEvent.ACTION_MOVE: { //移动
if (mDispatch) { if (mDispatch) {
mDispatchY += (int) event.getY() - mOriginY; mDispatchY += (int) event.getY() - mOriginY;
event.setLocation(event.getX(), mDispatchY); event.setLocation(event.getX(), mDispatchY);
@ -395,7 +395,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
break; break;
} }
default: { default: {
if (mDispatch) { if (mDispatch) {//分发
event.setLocation(event.getX(), mDispatchY); event.setLocation(event.getX(), mDispatchY);
mDispatch = false; mDispatch = false;
return mNotesListView.dispatchTouchEvent(event); return mNotesListView.dispatchTouchEvent(event);
@ -408,7 +408,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}; };
private void startAsyncNotesListQuery() { private void startAsyncNotesListQuery() {//开始异步笔记列表查询
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION; : NORMAL_SELECTION;
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
@ -417,7 +417,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
} }
private final class BackgroundQueryHandler extends AsyncQueryHandler { private final class BackgroundQueryHandler extends AsyncQueryHandler { //后台查询处理
public BackgroundQueryHandler(ContentResolver contentResolver) { public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver); super(contentResolver);
} }
@ -441,7 +441,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
private void showFolderListMenu(Cursor cursor) { private void showFolderListMenu(Cursor cursor) {//显示文件夹列表菜单
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder); builder.setTitle(R.string.menu_title_select_folder);
final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
@ -462,14 +462,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.show(); builder.show();
} }
private void createNewNote() { private void createNewNote() {//创建新的笔记
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
} }
private void batchDelete() { private void batchDelete() {//批量删除
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
@ -492,7 +492,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) { protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {//执行后
if (widgets != null) { if (widgets != null) {
for (AppWidgetAttribute widget : widgets) { for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
@ -506,7 +506,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute(); }.execute();
} }
private void deleteFolder(long folderId) { private void deleteFolder(long folderId) {//删除文件夹
if (folderId == Notes.ID_ROOT_FOLDER) { if (folderId == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Wrong folder id, should not happen " + folderId); Log.e(TAG, "Wrong folder id, should not happen " + folderId);
return; return;
@ -516,14 +516,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
ids.add(folderId); ids.add(folderId);
HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver, HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
folderId); folderId);
if (!isSyncMode()) { if (!isSyncMode()) {//如果不是同步模式
// if not synced, delete folder directly // if not synced, delete folder directly
DataUtils.batchDeleteNotes(mContentResolver, ids); DataUtils.batchDeleteNotes(mContentResolver, ids);
} else { } else {
// in sync mode, we'll move the deleted folder into the trash folder // in sync mode, we'll move the deleted folder into the trash folder
DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
} }
if (widgets != null) { if (widgets != null) {//如果小部件不为空
for (AppWidgetAttribute widget : widgets) { for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
@ -533,14 +533,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
private void openNode(NoteItemData data) { private void openNode(NoteItemData data) {//打开笔记
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, data.getId()); intent.putExtra(Intent.EXTRA_UID, data.getId());
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
} }
private void openFolder(NoteItemData data) { private void openFolder(NoteItemData data) {//打开文件夹
mCurrentFolderId = data.getId(); mCurrentFolderId = data.getId();
startAsyncNotesListQuery(); startAsyncNotesListQuery();
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
@ -557,7 +557,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mTitleBar.setVisibility(View.VISIBLE); mTitleBar.setVisibility(View.VISIBLE);
} }
public void onClick(View v) { public void onClick(View v) {//点击事件
switch (v.getId()) { switch (v.getId()) {
case R.id.btn_new_note: case R.id.btn_new_note:
createNewNote(); createNewNote();
@ -567,24 +567,24 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
private void showSoftInput() { private void showSoftInput() {//显示软键盘
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) { if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
} }
} }
private void hideSoftInput(View view) { private void hideSoftInput(View view) {//隐藏软键盘
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
} }
private void showCreateOrModifyFolderDialog(final boolean create) { private void showCreateOrModifyFolderDialog(final boolean create) {//显示创建或修改文件夹对话框
final AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
showSoftInput(); showSoftInput();
if (!create) { if (!create) {//如果不是创建
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
etName.setText(mFocusNoteDataItem.getSnippet()); etName.setText(mFocusNoteDataItem.getSnippet());
builder.setTitle(getString(R.string.menu_folder_change_name)); builder.setTitle(getString(R.string.menu_folder_change_name));
@ -604,19 +604,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
}); });
final Dialog dialog = builder.setView(view).show(); final Dialog dialog = builder.setView(view).show();//显示对话框
final Button positive = (Button)dialog.findViewById(android.R.id.button1); final Button positive = (Button)dialog.findViewById(android.R.id.button1); //获取确定按钮
positive.setOnClickListener(new OnClickListener() { positive.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
hideSoftInput(etName); hideSoftInput(etName);
String name = etName.getText().toString(); String name = etName.getText().toString();
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {//如果文件夹名字存在
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
Toast.LENGTH_LONG).show(); Toast.LENGTH_LONG).show();
etName.setSelection(0, etName.length()); etName.setSelection(0, etName.length());
return; return;
} }
if (!create) { if (!create) {//如果不是创建
if (!TextUtils.isEmpty(name)) { if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.SNIPPET, name);
@ -627,7 +627,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
String.valueOf(mFocusNoteDataItem.getId()) String.valueOf(mFocusNoteDataItem.getId())
}); });
} }
} else if (!TextUtils.isEmpty(name)) { } else if (!TextUtils.isEmpty(name)) { //如果是创建
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
@ -638,26 +638,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
if (TextUtils.isEmpty(etName.getText())) { if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false); positive.setEnabled(false);//如果名字为空,确定按钮不可用
} }
/** /**
* When the name edit text is null, disable the positive button * When the name edit text is null, disable the positive button
*/ */
etName.addTextChangedListener(new TextWatcher() { etName.addTextChangedListener(new TextWatcher() {//添加文本改变监听器
public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
public void onTextChanged(CharSequence s, int start, int before, int count) { public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.isEmpty(etName.getText())) { if (TextUtils.isEmpty(etName.getText())) {//如果名字为空
positive.setEnabled(false); positive.setEnabled(false);
} else { } else {
positive.setEnabled(true); positive.setEnabled(true);
} }
} }
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {//文本改变后
// TODO Auto-generated method stub // TODO Auto-generated method stub
} }
@ -665,7 +665,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
public void onBackPressed() { public void onBackPressed() { //返回键
switch (mState) { switch (mState) {
case SUB_FOLDER: case SUB_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
@ -688,7 +688,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
private void updateWidget(int appWidgetId, int appWidgetType) { private void updateWidget(int appWidgetId, int appWidgetType) {//更新小部件
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) { if (appWidgetType == Notes.TYPE_WIDGET_2X) {
intent.setClass(this, NoteWidgetProvider_2x.class); intent.setClass(this, NoteWidgetProvider_2x.class);
@ -707,7 +707,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {//文件夹上下文菜单监听器
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());
@ -719,7 +719,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}; };
@Override @Override
public void onContextMenuClosed(Menu menu) { public void onContextMenuClosed(Menu menu) {//上下文菜单关闭
if (mNotesListView != null) { if (mNotesListView != null) {
mNotesListView.setOnCreateContextMenuListener(null); mNotesListView.setOnCreateContextMenuListener(null);
} }
@ -727,7 +727,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
public boolean onContextItemSelected(MenuItem item) { public boolean onContextItemSelected(MenuItem item) {//上下文菜单项被选中
if (mFocusNoteDataItem == null) { if (mFocusNoteDataItem == null) {
Log.e(TAG, "The long click data item is null"); Log.e(TAG, "The long click data item is null");
return false; return false;
@ -737,7 +737,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
openFolder(mFocusNoteDataItem); openFolder(mFocusNoteDataItem);
break; break;
case MENU_FOLDER_DELETE: case MENU_FOLDER_DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);//弹出对话框
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setMessage(getString(R.string.alert_message_delete_folder));
@ -747,11 +747,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
deleteFolder(mFocusNoteDataItem.getId()); deleteFolder(mFocusNoteDataItem.getId());
} }
}); });
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);//取消
builder.show(); builder.show();
break; break;
case MENU_FOLDER_CHANGE_NAME: case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false); showCreateOrModifyFolderDialog(false);//显示创建或修改文件夹对话框
break; break;
default: default:
break; break;
@ -761,7 +761,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {//准备菜单
menu.clear(); menu.clear();
if (mState == ListEditState.NOTE_LIST) { if (mState == ListEditState.NOTE_LIST) {
getMenuInflater().inflate(R.menu.note_list, menu); getMenuInflater().inflate(R.menu.note_list, menu);
@ -779,7 +779,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {//菜单项被选中
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_new_folder: { case R.id.menu_new_folder: {
showCreateOrModifyFolderDialog(true); showCreateOrModifyFolderDialog(true);
@ -791,7 +791,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
case R.id.menu_sync: { case R.id.menu_sync: {
if (isSyncMode()) { if (isSyncMode()) {
if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { // start sync
GTaskSyncService.startSync(this); GTaskSyncService.startSync(this);
} else { } else {
GTaskSyncService.cancelSync(this); GTaskSyncService.cancelSync(this);
@ -801,15 +801,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
break; break;
} }
case R.id.menu_setting: { case R.id.menu_setting: {//设置
startPreferenceActivity(); startPreferenceActivity();
break; break;
} }
case R.id.menu_new_note: { case R.id.menu_new_note: {//新建便签
createNewNote(); createNewNote();
break; break;
} }
case R.id.menu_search: case R.id.menu_search://搜索
onSearchRequested(); onSearchRequested();
break; break;
default: default:
@ -819,12 +819,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {//搜索请求
startSearch(null, false, null /* appData */, false); startSearch(null, false, null /* appData */, false);
return true; return true;
} }
private void exportNoteToText() { private void exportNoteToText() {//导出便签到文本
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() { new AsyncTask<Void, Void, Integer>() {
@ -835,7 +835,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {//SD卡未挂载
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export)); .getString(R.string.failed_sdcard_export));
@ -843,7 +843,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
.getString(R.string.error_sdcard_unmounted)); .getString(R.string.error_sdcard_unmounted));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SUCCESS) { } else if (result == BackupUtils.STATE_SUCCESS) {//成功
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.success_sdcard_export)); .getString(R.string.success_sdcard_export));
@ -852,7 +852,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
.getExportedTextFileName(), backup.getExportedTextFileDir())); .getExportedTextFileName(), backup.getExportedTextFileDir()));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SYSTEM_ERROR) { } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {//系统错误
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export)); .getString(R.string.failed_sdcard_export));
@ -866,17 +866,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute(); }.execute();
} }
private boolean isSyncMode() { private boolean isSyncMode() {//是否同步模式
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
private void startPreferenceActivity() { private void startPreferenceActivity() {//启动首选项活动
Activity from = getParent() != null ? getParent() : this; Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class); Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1); from.startActivityIfNeeded(intent, -1);
} }
private class OnListItemClickListener implements OnItemClickListener { private class OnListItemClickListener implements OnItemClickListener {//列表项点击监听器
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
@ -890,8 +890,8 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return; return;
} }
switch (mState) { switch (mState) {//状态
case NOTE_LIST: case NOTE_LIST://便签列表
if (item.getType() == Notes.TYPE_FOLDER if (item.getType() == Notes.TYPE_FOLDER
|| item.getType() == Notes.TYPE_SYSTEM) { || item.getType() == Notes.TYPE_SYSTEM) {
openFolder(item); openFolder(item);
@ -901,8 +901,8 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
Log.e(TAG, "Wrong note type in NOTE_LIST"); Log.e(TAG, "Wrong note type in NOTE_LIST");
} }
break; break;
case SUB_FOLDER: case SUB_FOLDER://子文件夹
case CALL_RECORD_FOLDER: case CALL_RECORD_FOLDER://通话记录文件夹
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
openNode(item); openNode(item);
} else { } else {
@ -917,7 +917,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
private void startQueryDestinationFolders() { private void startQueryDestinationFolders() { //开始查询目标文件夹
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection: selection = (mState == ListEditState.NOTE_LIST) ? selection:
"(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
@ -935,7 +935,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
NoteColumns.MODIFIED_DATE + " DESC"); NoteColumns.MODIFIED_DATE + " DESC");
} }
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {//列表项长按监听器
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData(); mFocusNoteDataItem = ((NotesListItem) view).getItemData();
if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {

@ -31,19 +31,19 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter { // 该类扩展了 CursorAdapter 类
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
private Context mContext; private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex; private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount; private int mNotesCount;
private boolean mChoiceMode; private boolean mChoiceMode;
public static class AppWidgetAttribute { public static class AppWidgetAttribute { // 定义了一个静态内部类
public int widgetId; public int widgetId;
public int widgetType; public int widgetType;
}; };
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) { // 构造函数
super(context, null); super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context; mContext = context;
@ -51,12 +51,12 @@ public class NotesListAdapter extends CursorAdapter {
} }
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) { // 重写了 CursorAdapter 类的 newView() 方法
return new NotesListItem(context); return new NotesListItem(context);
} }
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {// 重写了 CursorAdapter 类的 bindView() 方法
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor); NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode, ((NotesListItem) view).bind(context, itemData, mChoiceMode,
@ -64,21 +64,21 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) { // 该方法用于设置选中的条目
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked);
notifyDataSetChanged(); notifyDataSetChanged();
} }
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }// 该方法用于判断是否处于多选模式
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {// 该方法用于设置多选模式
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
public void selectAll(boolean checked) { public void selectAll(boolean checked) {// 该方法用于设置是否全选
Cursor cursor = getCursor(); Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { if (cursor.moveToPosition(i)) {
@ -89,7 +89,7 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {// 该方法用于获取选中的条目的 id
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position) == true) {
@ -105,7 +105,7 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {// 该方法用于获取选中的条目的 widget
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position) == true) {
@ -128,12 +128,12 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
public int getSelectedCount() { public int getSelectedCount() {// 该方法用于获取选中的条目的数量
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
if (null == values) { if (null == values) {
return 0; return 0;
} }
Iterator<Boolean> iter = values.iterator(); Iterator<Boolean> iter = values.iterator();// 该方法用于获取迭代器
int count = 0; int count = 0;
while (iter.hasNext()) { while (iter.hasNext()) {
if (true == iter.next()) { if (true == iter.next()) {
@ -143,12 +143,12 @@ public class NotesListAdapter extends CursorAdapter {
return count; return count;
} }
public boolean isAllSelected() { public boolean isAllSelected() {// 该方法用于判断是否全选
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount);
} }
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {// 该方法用于判断是否选中
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
} }
@ -156,23 +156,23 @@ public class NotesListAdapter extends CursorAdapter {
} }
@Override @Override
protected void onContentChanged() { protected void onContentChanged() { // 重写了 CursorAdapter 类的 onContentChanged() 方法
super.onContentChanged(); super.onContentChanged();
calcNotesCount(); calcNotesCount();
} }
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {// 重写了 CursorAdapter 类的 changeCursor() 方法
super.changeCursor(cursor); super.changeCursor(cursor);
calcNotesCount(); calcNotesCount();
} }
private void calcNotesCount() { private void calcNotesCount() { // 该方法用于计算条目的数量
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i); Cursor c = (Cursor) getItem(i);
if (c != null) { if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {// 该方法用于获取条目的类型
mNotesCount++; mNotesCount++;
} }
} else { } else {

@ -30,7 +30,7 @@ import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout { // 继承自 LinearLayout 类
private ImageView mAlert; private ImageView mAlert;
private TextView mTitle; private TextView mTitle;
private TextView mTime; private TextView mTime;
@ -38,7 +38,7 @@ public class NotesListItem extends LinearLayout {
private NoteItemData mItemData; private NoteItemData mItemData;
private CheckBox mCheckBox; private CheckBox mCheckBox;
public NotesListItem(Context context) { public NotesListItem(Context context) { // 构造函数
super(context); super(context);
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
@ -48,7 +48,7 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
} }
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { // 绑定数据
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked); mCheckBox.setChecked(checked);
@ -57,14 +57,14 @@ public class NotesListItem extends LinearLayout {
} }
mItemData = data; mItemData = data;
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { // 如果是通话记录文件夹
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mTitle.setText(context.getString(R.string.call_record_folder_name) mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); + context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record); mAlert.setImageResource(R.drawable.call_record);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {// 如果是通话记录
mCallName.setVisibility(View.VISIBLE); mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName()); mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
@ -75,7 +75,7 @@ public class NotesListItem extends LinearLayout {
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} }
} else { } else { // 如果是笔记
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
@ -94,12 +94,12 @@ public class NotesListItem extends LinearLayout {
} }
} }
} }
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));// 设置时间
setBackground(data); setBackground(data);
} }
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {// 设置背景
int id = data.getBgColorId(); int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {

@ -48,20 +48,21 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity { // implements
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";// "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";// "pref_key_account_name";
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";// "pref_last_sync_time";
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";// "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";// "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";// "authorities";
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;// = (PreferenceCategory)
// findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
@ -70,17 +71,17 @@ public class NotesPreferenceActivity extends PreferenceActivity {
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) { //创建
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ /* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);//设置返回键
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);//获取PreferenceCategory
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);//添加广播
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
mOriAccounts = null; mOriAccounts = null;
@ -89,14 +90,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
@Override @Override
protected void onResume() { protected void onResume() {//恢复
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new // need to set sync account automatically if user has added a new
// account // account
if (mHasAddedAccount) { if (mHasAddedAccount) {//如果已经添加了账户
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {//如果原来的账户不为空并且账户数大于原来的账户数
for (Account accountNew : accounts) { for (Account accountNew : accounts) {
boolean found = false; boolean found = false;
for (Account accountOld : mOriAccounts) { for (Account accountOld : mOriAccounts) {
@ -117,21 +118,21 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {//销毁
if (mReceiver != null) { if (mReceiver != null) {
unregisterReceiver(mReceiver); unregisterReceiver(mReceiver);
} }
super.onDestroy(); super.onDestroy();
} }
private void loadAccountPreference() { private void loadAccountPreference() {//加载账户
mAccountCategory.removeAll(); mAccountCategory.removeAll();
Preference accountPref = new Preference(this); Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this); final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title)); accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary)); accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { //点击事件
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
@ -151,15 +152,15 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref); //添加账户
} }
private void loadSyncButton() { private void loadSyncButton() { //加载同步按钮
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state // set button state
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {//如果正在同步
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
@ -167,22 +168,22 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} else { } else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); syncButton.setText(getString(R.string.preferences_button_sync_immediately));//立即同步
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this); GTaskSyncService.startSync(NotesPreferenceActivity.this);
} }
}); });
} }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));//如果账户名不为空
// set last sync time // set last sync time
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {//如果正在同步
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
} else { } else {
long lastSyncTime = getLastSyncTime(this); long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) { if (lastSyncTime != 0) {//如果最后同步时间不为0
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format), DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime))); lastSyncTime)));
@ -193,13 +194,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
private void refreshUI() { private void refreshUI() {//刷新UI
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {//显示选择账户对话框
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);//创建对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
@ -216,7 +217,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mOriAccounts = accounts; mOriAccounts = accounts;
mHasAddedAccount = false; mHasAddedAccount = false;
if (accounts.length > 0) { if (accounts.length > 0) { //如果账户数大于0
CharSequence[] items = new CharSequence[accounts.length]; CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; final CharSequence[] itemMapping = items;
int checkedItem = -1; int checkedItem = -1;
@ -227,7 +228,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
items[index++] = account.name; items[index++] = account.name;
} }
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem, //设置单选按钮
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString()); setSyncAccount(itemMapping[which].toString());
@ -238,9 +239,9 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);//设置视图
final AlertDialog dialog = dialogBuilder.show(); final AlertDialog dialog = dialogBuilder.show(); //显示对话框
addAccountView.setOnClickListener(new View.OnClickListener() { addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mHasAddedAccount = true; mHasAddedAccount = true;
@ -254,7 +255,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
} }
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() { //显示更改账户确认对话框
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
@ -270,7 +271,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel) getString(R.string.preferences_menu_cancel)
}; };
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {//设置列表项
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (which == 0) { if (which == 0) {
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
@ -283,12 +284,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.show(); dialogBuilder.show();
} }
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {//获取谷歌账户
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
private void setSyncAccount(String account) { private void setSyncAccount(String account) {//设置同步账户
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
@ -318,7 +319,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
private void removeSyncAccount() { private void removeSyncAccount() {//移除同步账户
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
@ -330,7 +331,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit(); editor.commit();
// clean up local gtask related info // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {//新建线程
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); values.put(NoteColumns.GTASK_ID, "");
@ -340,13 +341,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start(); }).start();
} }
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {//获取同步账户名
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {//设置最后同步时间
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
@ -354,13 +355,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit(); editor.commit();
} }
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {//获取最后同步时间
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {//广播接收器
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
@ -374,7 +375,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {//选项菜单
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);

Loading…
Cancel
Save