Merge pull request '小米便签代码精读注释' (#4) from dev into master

pull/11/head
mvpola2e5 2 years ago
commit 931a5c3bdb

@ -25,14 +25,14 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
public class MetaData extends Task { public class MetaData extends Task //创建一个继承成Task类的类
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName();//实现过程调用getSimpleName ()函数,得到类的简写名称存入字符串TAG中
private String mRelatedGid = null; private String mRelatedGid = null;
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {//获取相关联的Gid
try { try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);//将这对键值放入metaInfo这个jsonobject对象中
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid");
} }
@ -42,19 +42,19 @@ public class MetaData extends Task {
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }//判断当前数据是否为空,若为空则返回真即值得保存
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }//调用父类Task中的setContentByRemoteJSON ()函数使用远程json数据对象设置元数据内
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {//调用父类Task中的setContentByRemoteJSON ()函数使用远程json数据对象设置元数据内容
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js);
if (getNotes() != null) { if (getNotes() != null) {
try { try {
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());//trim():去掉字符串首尾的空格
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, "failed to get related gid"); Log.w(TAG, "failed to get related gid");
@ -64,18 +64,18 @@ public class MetaData extends Task {
} }
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {//使用本地json数据对象设置元数据内容一般不会用到若用到则抛出异常
// this function should not be called // this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {//从元数据内容中获取本地json对象抛出异常
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
} }
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {//获取同步动作状态
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called");
} }

@ -20,9 +20,9 @@ import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
public abstract class Node { public abstract class Node {//同步操作的基础数据类型,定义了相关指示同步操作的常量
public static final int SYNC_ACTION_NONE = 0; public static final int SYNC_ACTION_NONE = 0;
//定义了各种用于表征同步状态的常量,需要操作标识
public static final int SYNC_ACTION_ADD_REMOTE = 1; public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_LOCAL = 2; public static final int SYNC_ACTION_ADD_LOCAL = 2;
@ -40,22 +40,22 @@ public abstract class Node {
public static final int SYNC_ACTION_ERROR = 8; public static final int SYNC_ACTION_ERROR = 8;
private String mGid; private String mGid;
//记录最后一次修改时间
private String mName; private String mName;//bool类型表明表征是否被删除
private long mLastModified; private long mLastModified;
private boolean mDeleted; private boolean mDeleted;
public Node() { public Node() {//构造函数进行初始化界面没有名字为空最后一次修改时间为0没有修改表征是否删除。
mGid = null; mGid = null;
mName = ""; mName = "";
mLastModified = 0; mLastModified = 0;
mDeleted = false; mDeleted = false;
} }
//函数定义为一个抽象的函数在TaskList子类中得到了实现
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
//主要功能声明JSONObject对象抽象类获取初始行为参数为GTASK_JSON_ACTION_ID
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
@ -69,11 +69,11 @@ public abstract class Node {
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
//行到底部,都是一些赋值和返回值函数,即对构造函数中的对象进行赋值或者获取对象的具体内容。
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name;
} }
//设置删除标识
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified;
} }
@ -97,5 +97,5 @@ public abstract class Node {
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }
//获取删除标识
} }

@ -35,18 +35,18 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
public class SqlData { public class SqlData {//公开类, 数据库类
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName();
//调用getSimpleName ()函数来得到类的简写名称存入字符串TAG中
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {//新建一个字符串数组,集合了 interface DataColumns 中所有SF常量
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
//代码块与sqlNote中定义的常量是相类似的是一些列的序号
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;
//数据列的这一行表示的项的mime类型
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;
@ -56,24 +56,24 @@ public class SqlData {
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
//定义以下8个内部变量
private boolean mIsCreate; private boolean mIsCreate;
//判断是否直接用Content生成是为true否则为false
private long mDataId; private long mDataId;
private String mDataMimeType; private String mDataMimeType;
//数据mime类型
private String mDataContent; private String mDataContent;
//数据内容
private long mDataContentData1; private long mDataContentData1;
private String mDataContentData3; private String mDataContentData3;
private ContentValues mDiffDataValues; private ContentValues mDiffDataValues;
//contenvalues只能存储基本类型的数据像stringint之类的
public SqlData(Context context) { public SqlData(Context context) {//构造函数初始化数据参数类型为Context
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;//mIsCreate为TRUE是这种构造方式的标志
mDataId = INVALID_ID; mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE; mDataMimeType = DataConstants.NOTE;
mDataContent = ""; mDataContent = "";
@ -81,7 +81,7 @@ public class SqlData {
mDataContentData3 = ""; mDataContentData3 = "";
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
//第二种SqlData的构造方式通过cursor来获取数据
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
@ -89,7 +89,7 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {//构造函数,初始化数据,参数类型分别为 Context 和 Cursor
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
mDataContent = c.getString(DATA_CONTENT_COLUMN); mDataContent = c.getString(DATA_CONTENT_COLUMN);
@ -97,14 +97,14 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
} }
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {//设置用于共享的数据并提供异常抛出与处理机制其中很多if 条件语句的判断,某些条件下某些特定的操作
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId); mDiffDataValues.put(DataColumns.ID, dataId);
} }
mDataId = dataId; mDataId = dataId;
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)//如果传入的JSONObject对象有DataColumns.MIME_TYPE一项则设置dataMimeType为这个否则设为SqlData.java
: DataConstants.NOTE; : DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType); mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
@ -116,12 +116,12 @@ public class SqlData {
mDiffDataValues.put(DataColumns.CONTENT, dataContent); mDiffDataValues.put(DataColumns.CONTENT, dataContent);
} }
mDataContent = dataContent; mDataContent = dataContent;
//以原有数据文本类型为基础,修改共享数据文本类型
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) { if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
} }
mDataContentData1 = dataContentData1; mDataContentData1 = dataContentData1;//共享数据同步后共享1类型数据等于该1类型数据
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
@ -129,7 +129,7 @@ public class SqlData {
} }
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3;
} }
//获取共享数据内容及提供异常抛出与处理机制
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
@ -143,12 +143,12 @@ public class SqlData {
js.put(DataColumns.DATA3, mDataContentData3); js.put(DataColumns.DATA3, mDataContentData3);
return js; return js;
} }
//将当前数据提交到数据库
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
//commit 函数用于把当前所做的修改保存到数据库
if (mIsCreate) { if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID);//更新共享数据键为NOTE_ID值为noteId
} }
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
@ -162,28 +162,28 @@ public class SqlData {
} else { } else {
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) {
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {//如果版本还没确认则结果记录下的只是data的ID还有data内容
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else { } else {
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(//若版本号确认则对对应id进行更新
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] { + " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version) String.valueOf(noteId), String.valueOf(version)
}); });//更新不存在,可能是用户在同步时已更新
} }
if (result == 0) { if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }//如果更新不存在或许用户在同步时已经完成更新则报错c
} }
} }
mDiffDataValues.clear(); mDiffDataValues.clear();//回到初始化,清空,表示已经更新
mIsCreate = false; mIsCreate = false;
} }
public long getId() { public long getId() {
return mDataId; return mDataId;
} }//获取当前id
} }

@ -38,12 +38,12 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
public class SqlNote { public class SqlNote {//调用getSimpleName ()函数得到类的简写名称存入字符串TAG中
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName();
//语句调用getSimpleName()函数将类的简写名称存到字符串TAG中
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {//集合了interface NoteColumns中所有SF常量17个
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE, NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
@ -51,7 +51,7 @@ public class SqlNote {
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID, NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION NoteColumns.VERSION
}; };
//定义每列的属性:
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
@ -86,7 +86,7 @@ public class SqlNote {
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
private Context mContext; private Context mContext;//以下定义了17个内部变量其中12个可以由content获得5个需要初始化为0或者new
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
@ -121,59 +121,59 @@ public class SqlNote {
private ContentValues mDiffNoteValues; private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
//SqlNote第一种构造方法只通过上下文context构造
public SqlNote(Context context) { public SqlNote(Context context) {//构造函数参数只有context对所有的变量进行初始化
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;//对象不存在,是要新建的
mId = INVALID_ID; mId = INVALID_ID;//无效用户
mAlertDate = 0; mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context); mBgColorId = ResourceParser.getDefaultBgId(context);//系统默认背景
mCreatedDate = System.currentTimeMillis(); mCreatedDate = System.currentTimeMillis();//调用系统函数获取创建时间
mHasAttachment = 0; mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis(); mModifiedDate = System.currentTimeMillis();
mParentId = 0; mParentId = 0;
mSnippet = ""; mSnippet = "";
mType = Notes.TYPE_NOTE; mType = Notes.TYPE_NOTE;
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID; mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;//控件Id初始化
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;//控件类型初始化
mOriginParent = 0; mOriginParent = 0;
mVersion = 0; mVersion = 0;
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();//新建一个NoteValues值用来记录改变的values
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();// 新建一个data的列表
} }
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {//构造函数有context和一个数据库的cursor两个参数多数变量通过cursor指向的一条记录直接进行初始化
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
loadFromCursor(c); loadFromCursor(c);
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)//如果是note类型则调用下面的 loadDataContent()函数,加载数据内容
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {//构造函数,两个参数
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
loadFromCursor(id); loadFromCursor(id);//调用下面的 loadFromCursor函数通过ID从光标处加载数据
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)//如果是数据是便签类型,则加载数据内容
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
//通过id从cursor加载数据
private void loadFromCursor(long id) { private void loadFromCursor(long id) {//通过id从光标处加载数据
Cursor c = null; Cursor c = null;
try { try {//通过try避免异常
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
String.valueOf(id) String.valueOf(id)
}, null); }, null);//如果获取成功则cursor移动到下一条记录并加载该记录
if (c != null) { if (c != null) {//代码块:如果有内容就将移入文档,并再次等待光标的内容
c.moveToNext(); c.moveToNext();
loadFromCursor(c); loadFromCursor(c);
} else { } else {
@ -184,9 +184,9 @@ public class SqlNote {
c.close(); c.close();
} }
} }
//通过cursor从cursor处加载数据
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {//通过游标从光标处加载数据
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN);//直接从一条记录中的获得以下变量的初始值
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN); mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN); mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
@ -199,22 +199,22 @@ public class SqlNote {
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN); mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
//取ID对应content内容如果查询到该note的id确实有对应项即cursor有对应获取ID对应content内容
private void loadDataContent() { private void loadDataContent() {//通过content机制获取共享数据并加载到数据库当前游标处
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
try { try {//获取ID对应content内容
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,//获得该ID对应的数据内容
"(note_id=?)", new String[] { "(note_id=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
}, null); }, null);
if (c != null) { if (c != null) {//如果光标处无内容提示note无数据warning
if (c.getCount() == 0) { if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data"); Log.w(TAG, "it seems that the note has not data");
return; return;
} }
while (c.moveToNext()) { while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c); SqlData data = new SqlData(mContext, c);//将获取数据存入数据表
mDataList.add(data); mDataList.add(data);
} }
} else { } else {
@ -225,23 +225,23 @@ public class SqlNote {
c.close(); c.close();
} }
} }
//设置content共享信息
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {//设置通过content机制用于共享的数据信息
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {//不能设置系统文件
Log.w(TAG, "cannot set system folder"); Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {//文件夹只能更新摘要和类型
// for folder we can only update the snnipet and type // for folder we can only update the snnipet and type
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note//如果共享数据存在摘要,则将其赋给声明的 snippet变量否则变量为空
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {/
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
} }
mSnippet = snippet; mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE; : Notes.TYPE_NOTE;//以下操作都和上面对snippet的操作一样一起根据共享的数据设置SqlNote内容的上述17项
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type);
} }
@ -252,21 +252,21 @@ public class SqlNote {
if (mIsCreate || mId != id) { if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id); mDiffNoteValues.put(NoteColumns.ID, id);
} }
mId = id; mId = id;//将该ID覆盖原ID
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note//获取数据的提醒日期
.getLong(NoteColumns.ALERTED_DATE) : 0; .getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) { if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
} }
mAlertDate = alertDate; mAlertDate = alertDate;
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note//获取数据的背景颜色
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); .getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) { if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
} }
mBgColorId = bgColorId; mBgColorId = bgColorId;/
long createDate = note.has(NoteColumns.CREATED_DATE) ? note long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); .getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
@ -275,66 +275,66 @@ public class SqlNote {
} }
mCreatedDate = createDate; mCreatedDate = createDate;
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note//对附件操作
.getInt(NoteColumns.HAS_ATTACHMENT) : 0; .getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) { if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
} }
mHasAttachment = hasAttachment; mHasAttachment = hasAttachment;
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note//对最近修改日期操作
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); .getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) { if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
} }
mModifiedDate = modifiedDate; mModifiedDate = modifiedDate;//将该父节点ID覆盖原父节点ID
long parentId = note.has(NoteColumns.PARENT_ID) ? note long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0; .getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) { if (mIsCreate || mParentId != parentId) {//如果只是通过上下文对note进行数据库操作或者该文本片段与原文本片段不相同
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
} }
mParentId = parentId; mParentId = parentId;
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note//如果只是通过上下文对note进行数据库操作或者该文本片段与原文本片段不相同
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
} }
mSnippet = snippet; mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)//对类型操作
: Notes.TYPE_NOTE; : Notes.TYPE_NOTE;
if (mIsCreate || mType != type) { if (mIsCreate || mType != type) {//如果只是通过上下文对note进行数据库操作或者该文件类型与原文件类型不相同
mDiffNoteValues.put(NoteColumns.TYPE, type); mDiffNoteValues.put(NoteColumns.TYPE, type);
} }
mType = type; mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)//对控件操作
: AppWidgetManager.INVALID_APPWIDGET_ID; : AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) { if (mIsCreate || mWidgetId != widgetId) {//如果只是通过上下文对note进行数据库操作或者该小部件ID与原小部件ID不相同
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
} }
mWidgetId = widgetId; mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note//获取数据的小部件种类
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; .getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) { if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
} }
mWidgetType = widgetType; mWidgetType = widgetType;//将该小部件种类覆盖原小部件种类
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; .getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) { if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
} }
mOriginParent = originParent; mOriginParent = originParent;//将该原始父文件夹ID覆盖原原始父文件夹ID
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {//遍历 dataArray查找 id 为 dataId 的数据
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null; SqlData sqlData = null;
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {//该数据ID对应的数据如果存在将对应的数据存在数据库中
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) { for (SqlData temp : mDataList) {
if (dataId == temp.getId()) { if (dataId == temp.getId()) {
@ -348,10 +348,10 @@ public class SqlNote {
mDataList.add(sqlData); mDataList.add(sqlData);
} }
sqlData.setContent(data); sqlData.setContent(data);//最后为数据库数据进行设置
} }
} }
} catch (JSONException e) { } catch (JSONException e) {//出现JSONException时日志显示错误同时打印堆栈轨迹
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return false; return false;
@ -359,7 +359,7 @@ public class SqlNote {
return true; return true;
} }
public JSONObject getContent() { public JSONObject getContent() {//获取content机制提供的数据并加载到note中
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -368,7 +368,7 @@ public class SqlNote {
return null; return null;
} }
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();//新建变量note用于传输共享数据
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.ALERTED_DATE, mAlertDate);
@ -385,14 +385,14 @@ public class SqlNote {
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {//将note中的data全部存入JSONArray中
JSONObject data = sqlData.getContent(); JSONObject data = sqlData.getContent();
if (data != null) { if (data != null) {
dataArray.put(data); dataArray.put(data);
} }
} }
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {//folder类型或system类型
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.SNIPPET, mSnippet);
@ -400,14 +400,14 @@ public class SqlNote {
} }
return js; return js;
} catch (JSONException e) { } catch (JSONException e) {//捕获json类型异常显示错误打印堆栈痕迹
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
public void setParentId(long id) { public void setParentId(long id) {//给当前id设置父id
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }
@ -415,38 +415,38 @@ public class SqlNote {
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
//给当前id设置Gtaskid
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
//给当前id设置同步id
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
//初始化本地修改,即撤销所有当前修改
public long getId() { public long getId() {
return mId; return mId;
} }
//获取当前 id
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
//获得当前id的父id
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
//获取小片段即用于显示的部分便签内容
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
//判断是否为便签类型
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {//commit函数用于把当前造作所做的修改保存到数据库
if (mIsCreate) { if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID); mDiffNoteValues.remove(NoteColumns.ID);
} }
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);//内容解析器中插入该便签的uri
try { try {
mId = Long.valueOf(uri.getPathSegments().get(1)); mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
@ -463,9 +463,9 @@ public class SqlNote {
} }
} }
} else { } else {
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {//对无效id操作
Log.e(TAG, "No such note"); Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id"); throw new IllegalStateException("Try to update note with invalid id");//尝试以无效 id 更新 note
} }
if (mDiffNoteValues.size() > 0) { if (mDiffNoteValues.size() > 0) {
mVersion ++; mVersion ++;
@ -482,12 +482,12 @@ public class SqlNote {
String.valueOf(mId), String.valueOf(mVersion) String.valueOf(mId), String.valueOf(mVersion)
}); });
} }
if (result == 0) { if (result == 0) {//如果内容解析器没有更新,那么报错:没有更新,或许用户在同步时进行更新
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
} }
} }
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {//note 类型
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion); sqlData.commit(mId, validateVersion, mVersion);
} }
@ -495,11 +495,11 @@ public class SqlNote {
} }
// refresh local info // refresh local info
loadFromCursor(mId); loadFromCursor(mId);//通过 cursor 从当前 id 处加载数据
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
mDiffNoteValues.clear(); mDiffNoteValues.clear();
mIsCreate = false; mIsCreate = false;//改变数据库构造模式
} }
} }

@ -32,9 +32,9 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
public class Task extends Node { public class Task extends Node {//创建Task类继承父类Node
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName();
//调用 getSimpleName ()函数来得到类的简写名称并存入字符串TAG中
private boolean mCompleted; private boolean mCompleted;
private String mNotes; private String mNotes;
@ -45,16 +45,16 @@ public class Task extends Node {
private TaskList mParent; private TaskList mParent;
public Task() { public Task() {//Task类的构造函数对对象进行初始化
super(); super();
mCompleted = false; mCompleted = false;//接下来是对类的变量进行初始化
mNotes = null; mNotes = null;
mPriorSibling = null; mPriorSibling = null;
mParent = null; mParent = null;
mMetaInfo = null; mMetaInfo = null;
} }
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {//对操作号即actionId 进行一些操作的公用函数
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
@ -69,12 +69,12 @@ public class Task extends Node {
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// entity_delta // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();//创建实体数据并将name创建者id实体类型存入数据
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE, entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK); GTaskStringUtils.GTASK_JSON_TYPE_TASK);
if (getNotes() != null) { if (getNotes() != null) {//如果存在 notes ,则将其也放入 entity 中
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes()); entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
} }
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
@ -94,7 +94,7 @@ public class Task extends Node {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
} }
} catch (JSONException e) { } catch (JSONException e) {//抛出异常处理机制
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject"); throw new ActionFailureException("fail to generate task-create jsonobject");
@ -103,10 +103,10 @@ public class Task extends Node {
return js; return js;
} }
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {//接收更新action
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();//声明并初始化
try { try {//同样是使用try和catch进行异常处理操作
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
@ -126,7 +126,7 @@ public class Task extends Node {
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { } catch (JSONException e) {//获取异常类型和异常详细消息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject"); throw new ActionFailureException("fail to generate task-update jsonobject");
@ -175,22 +175,22 @@ public class Task extends Node {
} }
} }
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {//通过本地的json设置内容
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");//那么反馈给用户出错信息
} }
try { try {//否则进行try和catch的异常处理操作
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {//note 类型匹配失败
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type");//错误,无效类型
return; return;
} }
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {//遍历数据数组
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT)); setName(data.getString(DataColumns.CONTENT));
@ -204,7 +204,7 @@ public class Task extends Node {
} }
} }
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {//从content获取本地json
String name = getName(); String name = getName();
try { try {
if (mMetaInfo == null) { if (mMetaInfo == null) {
@ -214,7 +214,7 @@ public class Task extends Node {
return null; return null;
} }
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();//初始化四个指针
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
@ -224,12 +224,12 @@ public class Task extends Node {
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE); note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js; return js;
} else { } else {//否则将元数据同步至数据中
// synced task // synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName()); data.put(DataColumns.CONTENT, getName());
@ -247,8 +247,8 @@ public class Task extends Node {
} }
} }
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {//设置元数据信息
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) {//如果元数据存在且能够获取到文本信息
try { try {
mMetaInfo = new JSONObject(metaData.getNotes()); mMetaInfo = new JSONObject(metaData.getNotes());
} catch (JSONException e) { } catch (JSONException e) {
@ -258,32 +258,32 @@ public class Task extends Node {
} }
} }
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {//设置同步action
try { try {
JSONObject noteInfo = null; JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {//代码块元数据信息不为空并且元数据信息还含有“META_HEAD_NOTE”说明便签存在
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
} }
if (noteInfo == null) { if (noteInfo == null) {//云端便签 id 已被删除,不存在,返回更新本地数据的同步行为
Log.w(TAG, "it seems that note meta has been deleted"); Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
if (!noteInfo.has(NoteColumns.ID)) { if (!noteInfo.has(NoteColumns.ID)) {//匹配note的id
Log.w(TAG, "remote note id seems to be deleted"); Log.w(TAG, "remote note id seems to be deleted");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
// validate the note id now // validate the note id now
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {//代码块:信息不匹配
Log.w(TAG, "note id doesn't match"); Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {//判断有无同步
// there is no local update // there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {//最近一次修改的 id 匹配成功,返回无的同步行为
// no update both side // no update both side
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
@ -292,11 +292,11 @@ public class Task extends Node {
} }
} else { } else {
// validate gtask id // validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {//判断gtask的id与获取的id是否匹配
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {//本地id与云端id一致即更新云端
// local modification only // local modification only
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
@ -311,7 +311,7 @@ public class Task extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
public boolean isWorthSaving() { public boolean isWorthSaving() {//可以保存的情况
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0); || (getNotes() != null && getNotes().trim().length() > 0);
} }
@ -319,33 +319,33 @@ public class Task extends Node {
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }
//接下来跟上面差不多,返回实例相关变量
public void setNotes(String notes) { public void setNotes(String notes) {
this.mNotes = notes; this.mNotes = notes;
} }
//设定是note成员变量
public void setPriorSibling(Task priorSibling) { public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; this.mPriorSibling = priorSibling;
} }
//设置优先兄弟 task 的优先级
public void setParent(TaskList parent) { public void setParent(TaskList parent) {
this.mParent = parent; this.mParent = parent;
} }
//设置父节点列表
public boolean getCompleted() { public boolean getCompleted() {
return this.mCompleted; return this.mCompleted;
} }
//获取 task 是否修改完毕的记录
public String getNotes() { public String getNotes() {
return this.mNotes; return this.mNotes;
} }
//获取成员变量 mNotes 的信息
public Task getPriorSibling() { public Task getPriorSibling() {
return this.mPriorSibling; return this.mPriorSibling;
} }
//获取优先兄弟 task
public TaskList getParent() { public TaskList getParent() {
return this.mParent; return this.mParent;
} }
//获取父节点列表
} }

@ -30,20 +30,20 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
public class TaskList extends Node { public class TaskList extends Node {//创建继承 Node的任务表类
private static final String TAG = TaskList.class.getSimpleName(); private static final String TAG = TaskList.class.getSimpleName();
//调用getSimplename函数获取名字并赋值给TAG作为标记
private int mIndex; private int mIndex;
//当前Tasklist的指针
private ArrayList<Task> mChildren; private ArrayList<Task> mChildren;
//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList
public TaskList() { public TaskList() {//TaskList 的构造函数
super(); super();
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>();
mIndex = 1; mIndex = 1;
} }
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {//生成并返回一个包含了一定数据的JSONObject实体
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
@ -74,10 +74,11 @@ public class TaskList extends Node {
return js; return js;
} }
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {//参考net.micode.notes.gtask.data.Node#getUpdateAction(int)
JSONObject
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {//初始化 js 中的数据
// action_type // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
@ -94,34 +95,34 @@ public class TaskList extends Node {
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) { } catch (JSONException e) {//代码块:处理异常信息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject"); throw new ActionFailureException("fail to generate tasklist-update jsonobject");//生成更新任务列表的 JSONObject 失败,抛出异常
} }
return js; return js;
} }
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {//通过云端 JSON 数据设置实例化对象 js 的内容
if (js != null) { if (js != null) {//判断js对象是否为空如果为空即没有内容就不需要进行设置了
try { try {
// id // id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {//若 js 中存在 GTASK_JSON_NAME 信息
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {//若 js 中存在 GTASK_JSON_NAME 信息
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {//语句块对任务的name进行设置
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
} catch (JSONException e) { } catch (JSONException e) {//代码块:处理异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject"); throw new ActionFailureException("fail to get tasklist content from jsonobject");
@ -129,14 +130,14 @@ public class TaskList extends Node {
} }
} }
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {//通过本地 JSON 数据设置对象 js 内容
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
} }
try { try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
//NullPointerException这个异常出现在处理对象时对象不存在但又没有捕捉到进行处理的时候
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
@ -157,17 +158,17 @@ public class TaskList extends Node {
} }
} }
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {//通过 Content 机制获取本地 JSON 数据
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject();
String folderName = getName(); String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))//代码块:如果获取的文件夹名称是以[MIUI_Notes]开头,则文件夹名称应删掉前缀
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length()); folderName.length());
folder.put(NoteColumns.SNIPPET, folderName); folder.put(NoteColumns.SNIPPET, folderName);
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)//代码块这里与上一个函数setContentByRemoteJSON(JSONObject js)是一个逆过程可以参看上一个函数是如何构造出foldername的
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
else else
@ -183,7 +184,7 @@ public class TaskList extends Node {
} }
} }
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {//通过 cursor 获取同步信息
try { try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // there is no local update
@ -208,7 +209,7 @@ public class TaskList extends Node {
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
} catch (Exception e) { } catch (Exception e) {//获取异常类型和异常详细消息
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
} }
@ -218,9 +219,9 @@ public class TaskList extends Node {
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }//获得TaskList的大小即mChildren的大小mChildren 是TaskList 的一个实例
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {//在当前任务表末尾添加新的任务。
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task); ret = mChildren.add(task);
@ -234,13 +235,13 @@ public class TaskList extends Node {
return ret; return ret;
} }
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {//在当前任务表中的索引位置添加新的子任务
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) {//任务非空且任务表中不存在该任务
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index");
return false; return false;
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task);//获取要添加的任务在任务表中的位置
if (task != null && pos == -1) { if (task != null && pos == -1) {
mChildren.add(index, task); mChildren.add(index, task);
@ -252,7 +253,7 @@ public class TaskList extends Node {
if (index != mChildren.size() - 1) if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1); afterTask = mChildren.get(index + 1);
task.setPriorSibling(preTask); task.setPriorSibling(preTask);//使得三个任务前后连在一块
if (afterTask != null) if (afterTask != null)
afterTask.setPriorSibling(task); afterTask.setPriorSibling(task);
} }
@ -260,19 +261,19 @@ public class TaskList extends Node {
return true; return true;
} }
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {//删除TaskList中的一个Task
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task);
if (index != -1) { if (index != -1) {
ret = mChildren.remove(task); ret = mChildren.remove(task);
if (ret) { if (ret) {//如果删除成功,就要将该任务的优先兄弟任务和父任务设置为空
// reset prior sibling and parent // reset prior sibling and parent
task.setPriorSibling(null); task.setPriorSibling(null);
task.setParent(null); task.setParent(null);
// update the task list // update the task list
if (index != mChildren.size()) { if (index != mChildren.size()) {//代码块:删除成功后,要对任务列表进行更新
mChildren.get(index).setPriorSibling( mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1)); index == 0 ? null : mChildren.get(index - 1));
} }
@ -281,14 +282,14 @@ public class TaskList extends Node {
return ret; return ret;
} }
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {//将当前TaskList中含有的某个Task移到index位置
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {//代码块:首先判断移动的位置是不是合法的
Log.e(TAG, "move child task: invalid index"); Log.e(TAG, "move child task: invalid index");
return false; return false;
} }
int pos = mChildren.indexOf(task); int pos = mChildren.indexOf(task);//task不在列表中
if (pos == -1) { if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list"); Log.e(TAG, "move child task: the task should in the list");
return false; return false;
@ -299,7 +300,7 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
} }
public Task findChildTaskByGid(String gid) { public Task findChildTaskByGid(String gid) {//按gid寻找Task
for (int i = 0; i < mChildren.size(); i++) { for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i); Task t = mChildren.get(i);
if (t.getGid().equals(gid)) { if (t.getGid().equals(gid)) {
@ -311,16 +312,16 @@ public class TaskList extends Node {
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }//返回指定Task的index
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {//返回指定index的Task
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index");
return null; return null;
} }
return mChildren.get(index); return mChildren.get(index);
} }
//返回指定gid的任务task
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) { for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))
@ -331,13 +332,13 @@ public class TaskList extends Node {
public ArrayList<Task> getChildTaskList() { public ArrayList<Task> getChildTaskList() {
return this.mChildren; return this.mChildren;
} }//获取子任务列表
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index;
} }
//设置任务索引
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex;
} }
} }//获取任务索引

@ -14,20 +14,21 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;//小米便签行为异常处理
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
//serialVersionUID相当于java类的身份证。
//有版本控制的功能。
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
//如果一个类从另外一个类继承我们new这个子类的实例对象的时候这个子类对象里面会有一个父类对象。
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString);
} }
//由于本类是extends的Exception类所以super调用的是Exception的类本语句相当于ExceptionparamString
public ActionFailureException(String paramString, Throwable paramThrowable) { public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }//具有相同形参paramString和paramThrowable的构造方法来调用父类

@ -14,20 +14,21 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;//小米便签网络异常处理
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
//serialVersionUID相当于java类的身份证。主要用于版本控制。
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
//不带参数的构造函数super指向父类
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString)//调用父类具有相同形参paramString的构造方法相当于Exception(paramString) {
super(paramString); super(paramString);
} }
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }//带有两个参数的函数。
paramStringparamThrowable

@ -28,23 +28,29 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
//实现GTask的异步操作过程
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
//通过interface实现多个接口初始化异步的功能。
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete();
} }
//文本内容
private Context mContext; private Context mContext;
//实例化通知管理器
private NotificationManager mNotifiManager; private NotificationManager mNotifiManager;
//实例化任务管理器
private GTaskManager mTaskManager; private GTaskManager mTaskManager;
//实例化监听器
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
//GTaskASyncTask类的构造函数
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
@ -53,18 +59,22 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
//中断同步
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
//调用onProgressUpdate方法来更新进度条
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
} }
//向用户显示当前的同步状态
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent; PendingIntent pendingIntent;
// 如果同步失败那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); NotesPreferenceActivity.class), 0);
@ -87,6 +97,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
@Override @Override
//异步执行后台线程将要完成的任务
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
@ -94,6 +105,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
@Override @Override
//用于显示任务执行的进度
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
@ -102,7 +114,9 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
@Override @Override
//用于设置任务
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
//若同步成功,则显示成功并展示出同步的账户与最新同步时间,若同步出现网络错误,则显示相应错误
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));
@ -118,6 +132,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {
//执行完后调用然后返回主线程中
public void run() { public void run() {
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete();
} }

@ -61,17 +61,24 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
//实现GTask的登录并进行GTASK任务的创建创建任务列表从网络上获取任务和任务列表的内容
public class GTaskClient { public class GTaskClient {
//设置本类的TAG作用是日志的打印输出和标识此类。
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
//谷歌邮箱的URL
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/";
//传递URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
//传递的url
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
//后续使用的参数以及变量
private static GTaskClient mInstance = null; private static GTaskClient mInstance = null;
//网络地址客户端
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
private String mGetUrl; private String mGetUrl;
@ -90,6 +97,7 @@ public class GTaskClient {
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
//GTaskClient的构造函数
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -102,6 +110,7 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
//获取实例如果当前没有示例则新建一个登陆的Gtask如果有直接返回
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -109,6 +118,7 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
//用来实现登录操作的函数
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // we suppose that the cookie would expire after 5 minutes
// then we need to re-login // then we need to re-login
@ -164,6 +174,7 @@ public class GTaskClient {
return true; return true;
} }
//用以具体实现登录Google账号的方法方法返回账号令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);
@ -207,6 +218,7 @@ public class GTaskClient {
return authToken; return authToken;
} }
//判断令牌对于登陆gtask账号是否有效的函数
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the // maybe the auth token is out of date, now let's invalidate the
@ -225,6 +237,7 @@ public class GTaskClient {
return true; return true;
} }
//实现登录Gtask方法的函数
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
@ -280,10 +293,12 @@ public class GTaskClient {
return true; return true;
} }
//得到用户的ID返回并加1
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++;
} }
//创建一个httpPost对象用于向网络传输数据
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,6 +306,7 @@ public class GTaskClient {
return httpPost; return httpPost;
} }
//通过URL获取响应后返回的数据使用getContentEncoding()获取网络上的资源和数据,返回值就是获取到的资源
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
@ -323,6 +339,7 @@ public class GTaskClient {
} }
} }
//通过JSON发送请求,利用UrlEncodedFormEntity entity和httpPost.setEntity把js中的内容放置到httpPost中后将资源再次放入json后返回
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -360,6 +377,7 @@ public class GTaskClient {
} }
} }
//创建单个任务通过json获取TASK中的内容并创建对应的jsPost使用setGid方法设置task的new_id
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -386,6 +404,7 @@ public class GTaskClient {
} }
} }
//创建任务列表
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -412,6 +431,7 @@ public class GTaskClient {
} }
} }
//利用JSON提交更新数据
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
@ -433,6 +453,7 @@ public class GTaskClient {
} }
} }
//利用commitUpdate添加更新节点
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // too many update items may result in an error
@ -447,6 +468,7 @@ public class GTaskClient {
} }
} }
//移动任务
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
@ -486,6 +508,7 @@ public class GTaskClient {
} }
} }
//删除操作节点
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -509,6 +532,7 @@ public class GTaskClient {
} }
} }
//获取任务列表首先通过getURI在网上获取数据在截取所需部分内容返回
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -547,6 +571,7 @@ public class GTaskClient {
} }
} }
//获取任务列表
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -575,10 +600,12 @@ public class GTaskClient {
} }
} }
//获得同步账户
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount;
} }
//重置更新内容
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }

@ -47,10 +47,12 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
//声明GTask管理类封装了对GTask进行管理的一些方法
public class GTaskManager { public class GTaskManager {
//通过 getSimpleName()得到类的简写名称。然后赋值给TAG
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();
//进程状态用0、1、2、3、4分别表示成功、网络错误、内部错误、同步中、取消同步
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;
@ -61,6 +63,7 @@ public class GTaskManager {
public static final int STATE_SYNC_CANCELLED = 4; public static final int STATE_SYNC_CANCELLED = 4;
// private 定义一系列不可被外部的类访问的量
private static GTaskManager mInstance = null; private static GTaskManager mInstance = null;
private Activity mActivity; private Activity mActivity;
@ -87,6 +90,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;
@ -99,6 +103,7 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>();
} }
//获取一个实例通过GTaskManager()新建一个mInstance
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
@ -106,20 +111,25 @@ public class GTaskManager {
return mInstance; return mInstance;
} }
//setActivityContext()用于获取当前的操作并更新至GTask中
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken // used for getting authtoken
mActivity = activity; mActivity = activity;
} }
//同步的总控制,包括同步前设置环境,进行同步,处理异常,同步结束清空缓存
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
} }
mContext = context; mContext = context;
mContentResolver = mContext.getContentResolver(); mContentResolver = mContext.getContentResolver();
//初始化各种标志变量
mSyncing = true; mSyncing = true;
mCancelled = false; mCancelled = false;
//对各种结构进行清空
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -132,6 +142,7 @@ public class GTaskManager {
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");
@ -139,10 +150,12 @@ public class GTaskManager {
} }
// 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
//获取Google上的JSONtasklist转为本地TaskList
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) {
@ -168,6 +181,7 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
//初始化GTask列表将google上的JSONTaskList转为本地任务列表
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
if (mCancelled) if (mCancelled)
return; return;
@ -247,6 +261,7 @@ public class GTaskManager {
} }
} }
//选择同步操作的类型并做好相应准备 具体做法是对每一种情况都把所有的任务判断一次,一旦发现是该种情况,就立即执行任务,否则判断下个任务
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType;
Cursor c = null; Cursor c = null;
@ -260,6 +275,7 @@ public class GTaskManager {
} }
// for local deleted note // for local deleted note
//处理本地删除的note
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] { "(type<>? AND parent_id=?)", new String[] {
@ -290,6 +306,7 @@ public class GTaskManager {
syncFolder(); syncFolder();
// for note existing in database // for note existing in database
//对已经存在与数据库的节点进行同步
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -327,6 +344,7 @@ public class GTaskManager {
} }
// go through remaining items // go through remaining items
//访问保留的项目
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator(); Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next(); Map.Entry<String, Node> entry = iter.next();
@ -337,6 +355,7 @@ public class GTaskManager {
// mCancelled can be set by another thread, so we neet to check one by // mCancelled can be set by another thread, so we neet to check one by
// one // one
// clear local delete table // clear local delete table
//清除本地删除的表格
if (!mCancelled) { if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes"); throw new ActionFailureException("failed to batch-delete local deleted notes");
@ -351,6 +370,7 @@ public class GTaskManager {
} }
//对文件夹进行同步,具体操作与之前的同步操作一致
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null;
String gid; String gid;
@ -362,6 +382,7 @@ public class GTaskManager {
} }
// for root folder // for root folder
//同步根目录
try { try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -391,6 +412,7 @@ 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=?)",
new String[] { new String[] {
@ -425,6 +447,7 @@ public class GTaskManager {
} }
// for local existing folders // for local existing folders
//同步已经存在的文件夹
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -461,6 +484,7 @@ public class GTaskManager {
} }
// for remote add folders // for remote add folders
//同步远程添加的文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next();
@ -476,6 +500,7 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
} }
//在之前对于各方面的同步操作中多次调用了这个函数,作用是依据不同的同步类型去调用不同的函数,以达到本地与远程同步的实际操作
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -522,12 +547,14 @@ 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;
//若待添加节点是任务列表中的节点,则进行操作,若待增添节点不是任务列表中的节点,进一步操作
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)) {
@ -555,6 +582,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++) {
@ -585,17 +613,21 @@ public class GTaskManager {
} }
// create the local node // create the local node
//把getGid()获取的node节点Gid用于设置本地Gtask的ID然后更新本地便签
sqlNote.setGtaskId(node.getGid()); sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false); sqlNote.commit(false);
// update gid-nid mapping // update gid-nid mapping
//更新gid与nid的映射表
mGidToNid.put(node.getGid(), sqlNote.getId()); mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid()); mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta // update meta
//更新本地节点
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
//更新本地节点,两个传入参数,一个是待更新的节点,一个是指向待增加位置的指针
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -616,9 +648,11 @@ public class GTaskManager {
sqlNote.commit(true); sqlNote.commit(true);
// update meta info // update meta info
//升级meta
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
//这个函数是添加远程结点参数node是要添加远程结点的本地结点c是数据库的指针
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,6 +662,7 @@ public class GTaskManager {
Node n; Node n;
// update remotely // update remotely
// 如果sqlNote是节点类型则设置好它的参数以及更新哈希表再把节点更新到远程数据里
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = new Task(); Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent()); task.setContentByLocalJSON(sqlNote.getContent());
@ -648,6 +683,7 @@ public class GTaskManager {
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
//当文件夹存在则跳过,若不存在则创建新的文件夹
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT; folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -672,6 +708,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());
@ -682,16 +719,19 @@ public class GTaskManager {
} }
// update local note // update local note
//进行本地节点的更新
sqlNote.setGtaskId(n.getGid()); sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false); sqlNote.commit(false);
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
// gid-id mapping // gid-id mapping
//进行gid与nid映射关系的更新
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
//更新远程结点node是要更新的结点c是数据库的指针
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -700,13 +740,16 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely // update remotely
//远程更新
node.setContentByLocalJSON(sqlNote.getContent()); node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node); GTaskClient.getInstance().addUpdateNode(node);
// update meta // update meta
//更新元数据
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary // move task if necessary
//判断节点类型是否符合要求
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = (Task) node; Task task = (Task) node;
TaskList preParentList = task.getParent(); TaskList preParentList = task.getParent();
@ -726,10 +769,12 @@ public class GTaskManager {
} }
// clear local modified flag // clear local modified flag
//清除本地修改标记
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
} }
//更新远程的元数据节点
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
@ -746,6 +791,7 @@ public class GTaskManager {
} }
} }
//刷新本地便签ID从远程同步
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -758,6 +804,10 @@ public class GTaskManager {
initGTaskList(); initGTaskList();
Cursor c = null; Cursor c = null;
//query语句五个参数NoteColumns.TYPE + " DESC"-----为按类型递减顺序返回查询结果。
// newString[{String.valueOf(Notes.TYPE_SYSTEM),String.valueOf(Notes.ID_TRASH_FOLER)}
//------ 为选择参数。"(type<>? AND parent_id<>?)"-------指明返回行过滤器。SqlNote.PROJECTION_NOTE
//-------- 应返回的数据列的名字。Notes.CONTENT_NOTE_URI--------contentProvider包含所有数据集所对应的uri
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[] {
@ -790,10 +840,12 @@ public class GTaskManager {
} }
} }
//string类化getSyncAccount()
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }
//取消同步置mCancelled为true
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} }

@ -23,26 +23,34 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
//由Service组件扩展而来作用是提供GTask的同步服务
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
//定义了一系列静态变量,用来表示同步操作的状态。
public final static String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
//用数字0、1、2分别表示开始同步、取消同步、同步无效
public final static int ACTION_START_SYNC = 0; public final static int ACTION_START_SYNC = 0;
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_CANCEL_SYNC = 1;
public final static int ACTION_INVALID = 2; public final static int ACTION_INVALID = 2;
//服务广播的名称
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
//表示广播正在同步
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
//GTask 广播服务消息
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
private static GTaskASyncTask mSyncTask = null; private static GTaskASyncTask mSyncTask = null;
private static String mSyncProgress = ""; private static String mSyncProgress = "";
//开始一个同步工作
private void startSync() { private void startSync() {
//若当前没有同步工作申请一个task并把指针指向新任务广播后执行
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() { public void onComplete() {
@ -56,20 +64,25 @@ public class GTaskSyncService extends Service {
} }
} }
//取消同步
private void cancelSync() { private void cancelSync() {
// 如果有同步任务,则取消
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
@Override @Override
//初始化任务直接把mSyncTask指针的值置为空
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
@Override @Override
//onStartCommand会告诉系统如何重启服务如判断是否异常终止后重新启动在何种情况下异常终止。返回值是一个(int)整形有四种返回值。参数的flags表示启动服务的方式
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
//判断当前的同步状态,根据开始或取消,执行对应操作
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC: case ACTION_START_SYNC:
@ -87,16 +100,19 @@ public class GTaskSyncService extends Service {
} }
@Override @Override
//发送广播
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
//用于绑定操作的函数
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
//发送广播内容
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,6 +121,7 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent); sendBroadcast(intent);
} }
//对变量activity事件进行同步操作
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,16 +129,19 @@ public class GTaskSyncService extends Service {
activity.startService(intent); activity.startService(intent);
} }
//取消同步
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);
} }
//判断当前是否处于同步状态
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
//返回当前同步状态
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }

@ -35,24 +35,24 @@ import java.util.ArrayList;
public class Note { public class Note {
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;//ContentValues是用于给其他应用调用小米便签的内容的共享数据
private NoteData mNoteData; private NoteData mNoteData;
private static final String TAG = "Note"; private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * Create a new note id for adding a new note to databases
*/ */
public static synchronized long getNewNoteId(Context context, long folderId) { public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database // Create a new note in the database//获取新建便签的编号
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis(); long createdTime = System.currentTimeMillis();//读取当前系统时间
values.put(NoteColumns.CREATED_DATE, createdTime); values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime); values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId); values.put(NoteColumns.PARENT_ID, folderId);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
//外部应用对ContentProvider中的数据进行添加、删除、修改和查询操作
long noteId = 0; long noteId = 0;//实现外部应用对数据的插入删除等操作
try { try {
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
@ -65,12 +65,12 @@ public class Note {
return noteId; return noteId;
} }
public Note() { public Note() {//定义两个变量用来存储便签的数据,一个是存储便签属性、一个是存储便签内容
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
} }
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {//设置数据库表格的标签属性数据
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
@ -79,33 +79,33 @@ public class Note {
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
} }
//设置数据库表格的标签文本内容的数据
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
} }
//设置文本数据的ID
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
} }
//获取文本数据的id
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
} }
//设置电话号码数据的ID
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
} }
//得到电话号码数据的ID
public boolean isLocalModified() { public boolean isLocalModified() {//判断是否是本地修改
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {//判断便签是否同步
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
if (!isLocalModified()) { if (!isLocalModified()) {//如果本地没有发现修改直接返回1指示已经同步到数据库中
return true; return true;
} }
@ -114,15 +114,15 @@ public class Note {
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info * note data info
*/ */
if (context.getContentResolver().update( if (context.getContentResolver().update(//发现更新错误时,及时反馈错误信息
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) { null) == 0) {
Log.e(TAG, "Update note error, should not happen"); Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through // Do not return, fall through
} }
mNoteDiffValues.clear(); mNoteDiffValues.clear();//初始化便签特征值
if (mNoteData.isLocalModified() if (mNoteData.isLocalModified()//判断未同步
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false; return false;
} }
@ -130,7 +130,7 @@ public class Note {
return true; return true;
} }
private class NoteData { private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据
private long mTextDataId; private long mTextDataId;
private ContentValues mTextDataValues; private ContentValues mTextDataValues;
@ -141,14 +141,14 @@ public class Note {
private static final String TAG = "NoteData"; private static final String TAG = "NoteData";
public NoteData() { public NoteData() {//NoteData的构造函数初始化四个变量
mTextDataValues = new ContentValues(); mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); mCallDataValues = new ContentValues();
mTextDataId = 0; mTextDataId = 0;
mCallDataId = 0; mCallDataId = 0;
} }
boolean isLocalModified() { boolean isLocalModified() {//下面是上述几个函数的具体实现
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
@ -159,26 +159,26 @@ public class Note {
mTextDataId = id; mTextDataId = id;
} }
void setCallDataId(long id) { void setCallDataId(long id) {//判断ID是否合法
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
} }
mCallDataId = id; mCallDataId = id;
} }
void setCallData(String key, String value) { void setCallData(String key, String value) {//设置电话号码数据内容,并且保存修改时间
mCallDataValues.put(key, value); mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
void setTextData(String key, String value) { void setTextData(String key, String value) {//设置文本数据
mTextDataValues.put(key, value); mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {//下面函数的作用是将新的数据通过Uri的操作存储到数据库
/** /**
* Check for safety * Check for safety
*/ */
@ -186,24 +186,24 @@ public class Note {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();//数据库操作链表
ContentProviderOperation.Builder builder = null; ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {//把文本数据存入DataColumns
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) { if (mTextDataId == 0) {//uri插入文本数据
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues); mTextDataValues);
try { try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));//尝试重新给它设置id
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId); Log.e(TAG, "Insert new text data fail with noteId" + noteId);//插入数据失败
mTextDataValues.clear(); mTextDataValues.clear();
return null; return null;
} }
} else { } else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(//更新builder对象追加uri数据和文本ID
Notes.CONTENT_DATA_URI, mTextDataId)); Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues); builder.withValues(mTextDataValues);
operationList.add(builder.build()); operationList.add(builder.build());
@ -211,20 +211,20 @@ public class Note {
mTextDataValues.clear(); mTextDataValues.clear();
} }
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {//对于电话号码的数据也是和文本数据一样的同步处理
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) { if (mCallDataId == 0) {//将电话号码的id设定为uri提供的id
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues); mCallDataValues);
try { try {/
setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId); Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear(); mCallDataValues.clear();
return null; return null;
} }
} else { } else {// 当电话号码不为新建时更新电话号码ID
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId)); Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues); builder.withValues(mCallDataValues);
@ -232,18 +232,18 @@ public class Note {
} }
mCallDataValues.clear(); mCallDataValues.clear();
} }
//把电话号码数据存入DataColumns
if (operationList.size() > 0) { if (operationList.size() > 0) {//存储过程中如果遇到异常,通过如下进行处理
try { try {
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList); Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) { } catch (RemoteException e) {//捕捉操作异常并写回日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} catch (OperationApplicationException e) { } catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));//异常日志
return null; return null;
} }
} }

@ -32,6 +32,7 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; import net.micode.notes.tool.ResourceParser.NoteBgResources;
//声明WorkingNote类,创建小米便签的主要类,包括创建空便签,保存便签,加载小米便签内容,和设置小米便签的一些小部件之类的操作
public class WorkingNote { public class WorkingNote {
// Note for the working note // Note for the working note
private Note mNote; private Note mNote;
@ -62,6 +63,7 @@ public class WorkingNote {
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
//声明 NOTE_PROJECTION字符串数组
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -102,6 +104,7 @@ public class WorkingNote {
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct // New note construct
//缺省noteID的构造函数直接使用内容和文件号新建便签
private WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0;
@ -115,6 +118,7 @@ public class WorkingNote {
} }
// Existing note construct // Existing note construct
//加载便签
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
mNoteId = noteId; mNoteId = noteId;
@ -124,6 +128,7 @@ public class WorkingNote {
loadNote(); loadNote();
} }
//输出mNoteId的所有属性值
private void loadNote() { private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
@ -146,6 +151,7 @@ public class WorkingNote {
loadNoteData(); loadNoteData();
} }
//加载便签数据
private void loadNoteData() { private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
@ -174,6 +180,7 @@ public class WorkingNote {
} }
} }
//创建空的Note传参context文件夹idwidget背景颜色
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
@ -183,12 +190,16 @@ public class WorkingNote {
return note; return note;
} }
//导入一个新的正在写入的便签
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
//保存note
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
//判断是否有价值去保存
if (isWorthSaving()) { if (isWorthSaving()) {
//当数据库中没有当前版本便签的时候才需要保存
if (!existInDatabase()) { if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
@ -201,6 +212,7 @@ public class WorkingNote {
/** /**
* Update widget content if there exist any widget of this note * Update widget content if there exist any widget of this note
*/ */
//判断窗口大小是否变化,如果变化也要保存这个变化
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) { && mNoteSettingStatusListener != null) {
@ -212,11 +224,14 @@ public class WorkingNote {
} }
} }
//判断便签是否已经存在于数据库中
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
//判断是否有保存的必要性
private boolean isWorthSaving() { private boolean isWorthSaving() {
//如果是误删,或者是空的,或者在本地并没有修改,那么不需要保存
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
return false; return false;
@ -225,11 +240,14 @@ public class WorkingNote {
} }
} }
//设置监听“设置状态改变”
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
//设置提示日期
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
//若 mAlertDate与data不同则更改mAlertDate并设定NoteValue
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
@ -239,6 +257,7 @@ public class WorkingNote {
} }
} }
//设定删除标记
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
@ -247,9 +266,11 @@ public class WorkingNote {
} }
} }
//设置背景颜色为第ID号颜色
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
//判断此id是否是背景颜色id如果不是则更新背景颜色
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
} }
@ -257,7 +278,9 @@ public class WorkingNote {
} }
} }
//设定检查列表模式
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
//如果传入的模式与原模式不同,则更改原模式为当前模式
if (mMode != mode) { if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
@ -267,81 +290,101 @@ public class WorkingNote {
} }
} }
//设置窗口类型
public void setWidgetType(int type) { public void setWidgetType(int type) {
//判断传入的类型是否与当前类型一样,否则更改为传入的类型并储存便签的窗口数据
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
} }
} }
//设置窗口编号
public void setWidgetId(int id) { public void setWidgetId(int id) {
// 判断传入是否与当前id一样否则更改为传入id
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
} }
} }
//设定编辑文本
public void setWorkingText(String text) { public void setWorkingText(String text) {
//判断文本内容是否相同,否则更新文本
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent);
} }
} }
//转换成电话提醒的便签
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
//判断是否有时钟提醒
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
//获取便签内容
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
//获取待提醒日期
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
//获取修改之后的日期
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
//获取背景颜色资源ID
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
//获取背景颜色ID
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
//获取标题背景来源
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
//获取清单的模式
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
//获取便签ID
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
//获取文件夹ID
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
//获取窗口编号
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
//监听检测便签设置变化的接口
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
//监听便签内部所有属性改变,当便签的属性改变的时候,这个类里面会有相应的记录,但是这个类只有个框架。
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed

@ -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 {//创建一个私有类HeadViewHolder用于对界面进行设置包括文本内容图片内容等
public TextView tvModified; public TextView tvModified;
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
@ -82,10 +82,10 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public TextView tvAlertDate; public TextView tvAlertDate;
public ImageView ibSetBgColor; public ImageView ibSetBgColor;
} }//该类实现了对当前便签界面进行编辑功能继承了父类Activity并实现了接口封装有方法39个
//声明Hashmap类将按钮和对应的资源解析器中的各个属性关联。
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static { static {//对HashMap进行初始化主要是颜色的对应
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,6 +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>();
//代码块运用Hashmap,将资源解析器中的对应颜色与已选择的颜色按钮关联起来。
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);
@ -103,7 +104,8 @@ 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,46 +113,48 @@ 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 { //常量实现资源解析器中字号ID与字体大小按钮已选择对应
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";//为本模块进行标签设置“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;//私有化一个界面操作mFontSizeSelector对标签字体的操作
private EditText mNoteEditor; private EditText mNoteEditor;//文本操作
private View mNoteEditorPanel; private View mNoteEditorPanel;//.文本编辑控制板
private WorkingNote mWorkingNote; private WorkingNote mWorkingNote;//对模板WorkingNote的初始化
private SharedPreferences mSharedPrefs; private SharedPreferences mSharedPrefs;//私有化SharedPreferences的数据存储方式
private int mFontSizeId; private int mFontSizeId;//.操作字体大小
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;//设置标题最大长度为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//重写Activity类的onCreate方法
protected void onCreate(Bundle savedInstanceState) { //@param savedInstanceState 已保存的便签实例状态
protected void onCreate(Bundle savedInstanceState) {//创建该activity然后对content进行设置。通过对State的相关信息判断是否返回
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.setContentView(R.layout.note_edit); this.setContentView(R.layout.note_edit);
@ -166,7 +170,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);
@ -179,13 +183,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
private boolean initActivityState(Intent intent) { private boolean initActivityState(Intent intent) {//初始化Activity的状态
/** /**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
* then jump to the NotesListActivity * then jump to the NotesListActivity
*/ */
mWorkingNote = null; mWorkingNote = null;
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {//判断初始化该Activity的Intent所包含的action是ACTION_VIEW还是ACTION_INSERT_OR_EDIT然后进行不同的操作
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
mUserQuery = ""; mUserQuery = "";
@ -214,7 +218,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
getWindow().setSoftInputMode( getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {//通过 getAction得到的字符串来决定做什么
// New note // New note
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
@ -263,21 +267,21 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
@Override @Override
protected void onResume() { protected void onResume() {//进行重新返回的函数
super.onResume(); super.onResume();
initNoteScreen(); initNoteScreen();
} }
private void initNoteScreen() { private void initNoteScreen() {//对界面进行初始化的操作
mNoteEditor.setTextAppearance(this, TextAppearanceResources mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId)); .getTexAppearanceResource(mFontSizeId));
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//判断是否为清单列表界面,是则切换到清单列表的处理过程,否则继续执行
switchToListMode(mWorkingNote.getContent()); switchToListMode(mWorkingNote.getContent());
} else { } else {
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
mNoteEditor.setSelection(mNoteEditor.getText().length()); mNoteEditor.setSelection(mNoteEditor.getText().length());
} }
for (Integer id : sBgSelectorSelectionMap.keySet()) { for (Integer id : sBgSelectorSelectionMap.keySet()) {//循环遍历所有sBgSelectorSelectionMap中id对应的资源文件使其不可见且不占用空间
findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);
} }
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
@ -295,7 +299,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
showAlertHeader(); showAlertHeader();
} }
private void showAlertHeader() { private void showAlertHeader() {//设置闹钟的显示
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
if (time > mWorkingNote.getAlertDate()) { if (time > mWorkingNote.getAlertDate()) {
@ -313,20 +317,20 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
@Override @Override
protected void onNewIntent(Intent intent) { protected void onNewIntent(Intent intent) {//新建一个传值对象
super.onNewIntent(intent); super.onNewIntent(intent);
initActivityState(intent); initActivityState(intent);
} }
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(Bundle outState) {//用于保存数据
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
/** /**
* For new note without note id, we should firstly save it to * For new note without note id, we should firstly save it to
* generate a id. If the editing note is not worth saving, there * generate a id. If the editing note is not worth saving, there
* is no id which is equivalent to create new note * is no id which is equivalent to create new note
*/ */
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {//如果该workingnote实例无法在数据库中找到即为新建的便签则先将其存储
saveNote(); saveNote();
} }
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
@ -334,8 +338,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {//MotionEvent是对屏幕触控的传递机制
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE if (mNoteBgColorSelector.getVisibility() == View.VISIBLE//背景颜色选择器是否可见
&& !inRangeOfView(mNoteBgColorSelector, ev)) { && !inRangeOfView(mNoteBgColorSelector, ev)) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
@ -349,7 +353,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return super.dispatchTouchEvent(ev); return super.dispatchTouchEvent(ev);
} }
private boolean inRangeOfView(View view, MotionEvent ev) { private boolean inRangeOfView(View view, MotionEvent ev) {//对屏幕触控的坐标进行操作
int []location = new int[2]; int []location = new int[2];
view.getLocationOnScreen(location); view.getLocationOnScreen(location);
int x = location[0]; int x = location[0];
@ -363,7 +367,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
private void initResources() { private void initResources() {//对标签各项属性内容的初始化
mHeadViewPanel = findViewById(R.id.note_title); mHeadViewPanel = findViewById(R.id.note_title);
mNoteHeaderHolder = new HeadViewHolder(); mNoteHeaderHolder = new HeadViewHolder();
mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);
@ -374,46 +378,46 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mNoteEditor = (EditText) findViewById(R.id.note_edit_view); mNoteEditor = (EditText) findViewById(R.id.note_edit_view);
mNoteEditorPanel = findViewById(R.id.sv_note_edit); mNoteEditorPanel = findViewById(R.id.sv_note_edit);
mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
for (int id : sBgSelectorBtnsMap.keySet()) { for (int id : sBgSelectorBtnsMap.keySet()) {//对所有颜色选择按钮设置监听器
ImageView iv = (ImageView) findViewById(id); ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this); iv.setOnClickListener(this);
} }
mFontSizeSelector = findViewById(R.id.font_size_selector); mFontSizeSelector = findViewById(R.id.font_size_selector);
for (int id : sFontSizeBtnsMap.keySet()) { for (int id : sFontSizeBtnsMap.keySet()) {//对于每一个字体大小的选择按钮都设置监听器
View view = findViewById(id); View view = findViewById(id);
view.setOnClickListener(this); view.setOnClickListener(this);
}; };
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);//初始化共享设置
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);//从偏好设置中得到设置字体大小的ID
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case, * The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/ */
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {//如果获取到的字体大小值的长度大于资源文件应有长度则将其设置为默认长度缺省值为1.
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
} }
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
} }
@Override @Override
protected void onPause() { protected void onPause() {//onPause()在activity退出前想保存用户重要数据的必须在onPause中处理调用父类的界面暂停操作并输出对应信息。
super.onPause(); super.onPause();
if(saveNote()) { if(saveNote()) {//保存便签
Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());
} }
clearSettingState(); clearSettingState();
} }
private void updateWidget() { private void updateWidget() {//更新窗口与桌面小窗口同步
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);//新建一个包含改变widget动作的intent实例
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {//根据workingnote的widget类型大小设置intent中映射的类
intent.setClass(this, NoteWidgetProvider_2x.class); intent.setClass(this, NoteWidgetProvider_2x.class);
} else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) {//如果是4倍大小
intent.setClass(this, NoteWidgetProvider_4x.class); intent.setClass(this, NoteWidgetProvider_4x.class);
} else { } else {
Log.e(TAG, "Unspported widget type"); Log.e(TAG, "Unspported widget type");//Log输出error信息不支持的widget类型
return; return;
} }
@ -427,16 +431,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public void onClick(View v) { public void onClick(View v) {
int id = v.getId(); int id = v.getId();
if (id == R.id.btn_set_bg_color) { if (id == R.id.btn_set_bg_color) {//如果点击的是 设置背景颜色,执行下面的函数。
mNoteBgColorSelector.setVisibility(View.VISIBLE); mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(View.VISIBLE);
- View.VISIBLE); } else if (sBgSelectorBtnsMap.containsKey(id)) {//如果点击的是背景颜色设置器中的背景颜色选项按钮,执行下面的函数
} else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE); View.GONE);
mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id));
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
} else if (sFontSizeBtnsMap.containsKey(id)) { } else if (sFontSizeBtnsMap.containsKey(id)) {//如果点击的是文字大小设置器中的文字大小选项按钮
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE);
mFontSizeId = sFontSizeBtnsMap.get(id); mFontSizeId = sFontSizeBtnsMap.get(id);
mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();
@ -453,7 +456,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
@Override @Override
public void onBackPressed() { public void onBackPressed() {//监听按下返回键的操作。
if(clearSettingState()) { if(clearSettingState()) {
return; return;
} }
@ -462,18 +465,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
super.onBackPressed(); super.onBackPressed();
} }
private boolean clearSettingState() { private boolean clearSettingState() {//清除设置状态
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {//如果背景色选择器可见,设置为不可见
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
} else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {//如果字体选择菜单可见,设置为不可见
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
return true; return true;
} }
return false; return false;
} }
public void onBackgroundColorChanged() { public void onBackgroundColorChanged() {//背景颜色改变
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE); View.VISIBLE);
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
@ -481,23 +484,23 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {//准备菜单内容
if (isFinishing()) { if (isFinishing()) {//如果窗口正在关闭,则不做处理
return true; return true;
} }
clearSettingState(); clearSettingState();//清除设置状态
menu.clear(); menu.clear();//清除菜单项
if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {//如果便签所在的文件夹为便签的通话记录文件夹,执行下面函数
getMenuInflater().inflate(R.menu.call_note_edit, menu); getMenuInflater().inflate(R.menu.call_note_edit, menu);
} else { } else {
getMenuInflater().inflate(R.menu.note_edit, menu); getMenuInflater().inflate(R.menu.note_edit, menu);
} }
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果workingNote模式为核对列表模式则执行下面函数
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode);
} else { } else {
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode);
} }
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {//如果workingNote对象中有时钟提醒事项则执行下面函数。
menu.findItem(R.id.menu_alert).setVisible(false); menu.findItem(R.id.menu_alert).setVisible(false);
} else { } else {
menu.findItem(R.id.menu_delete_remind).setVisible(false); menu.findItem(R.id.menu_delete_remind).setVisible(false);
@ -506,8 +509,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {//动态改变菜单选项内容
switch (item.getItemId()) { switch (item.getItemId()) {//判断选择项
case R.id.menu_new_note: case R.id.menu_new_note:
createNewNote(); createNewNote();
break; break;
@ -553,7 +556,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
private void setReminder() { private void setReminder() {//建立事件提醒器
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
d.setOnDateTimeSetListener(new OnDateTimeSetListener() { d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
public void OnDateTimeSet(AlertDialog dialog, long date) { public void OnDateTimeSet(AlertDialog dialog, long date) {
@ -567,14 +570,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* Share note to apps that support {@link Intent#ACTION_SEND} action * Share note to apps that support {@link Intent#ACTION_SEND} action
* and {@text/plain} type * and {@text/plain} type
*/ */
private void sendTo(Context context, String info) { private void sendTo(Context context, String info) {//共享便签
Intent intent = new Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, info); intent.putExtra(Intent.EXTRA_TEXT, info);
intent.setType("text/plain"); intent.setType("text/plain");
context.startActivity(intent); context.startActivity(intent);
} }
private void createNewNote() { private void createNewNote() {//创建新的便签
// Firstly, save current editing notes // Firstly, save current editing notes
saveNote(); saveNote();
@ -586,16 +589,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
startActivity(intent); startActivity(intent);
} }
private void deleteCurrentNote() { private void deleteCurrentNote() {//删除当前便签
if (mWorkingNote.existInDatabase()) { if (mWorkingNote.existInDatabase()) {//先判断便签是否在数据库中
HashSet<Long> ids = new HashSet<Long>(); HashSet<Long> ids = new HashSet<Long>();
long id = mWorkingNote.getNoteId(); long id = mWorkingNote.getNoteId();
if (id != Notes.ID_ROOT_FOLDER) { if (id != Notes.ID_ROOT_FOLDER) {//如果不是头文件夹建立一个hash表把便签id存起来
ids.add(id); ids.add(id);
} else { } else {
Log.d(TAG, "Wrong note id, should not happen"); Log.d(TAG, "Wrong note id, should not happen");
} }
if (!isSyncMode()) { if (!isSyncMode()) {//如果不是同步模式,则执行下面函数
if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
Log.e(TAG, "Delete Note error"); Log.e(TAG, "Delete Note error");
} }
@ -608,19 +611,19 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote.markDeleted(true); mWorkingNote.markDeleted(true);
} }
private boolean isSyncMode() { private boolean isSyncMode() {//判断是否为同步模式
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
public void onClockAlertChanged(long date, boolean set) { public void onClockAlertChanged(long date, boolean set) {//监听闹钟变化事件函数
/** /**
* User could set clock to an unsaved note, so before setting the * User could set clock to an unsaved note, so before setting the
* alert clock, we should save the note first * alert clock, we should save the note first
*/ */
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {//如果设置提醒的便签未保存,则先保存
saveNote(); saveNote();
} }
if (mWorkingNote.getNoteId() > 0) { if (mWorkingNote.getNoteId() > 0) {//数据库中有该提醒的id,执行下面操作。否则,报错。
Intent intent = new Intent(this, AlarmReceiver.class); Intent intent = new Intent(this, AlarmReceiver.class);
intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
@ -645,24 +648,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public void onWidgetChanged() { public void onWidgetChanged() {
updateWidget(); updateWidget();
} }
//当widget变化时执行更新widget这个函数
public void onEditTextDelete(int index, String text) { public void onEditTextDelete(int index, String text) {//当删除编辑文本时,执行这个函数
int childCount = mEditTextList.getChildCount(); int childCount = mEditTextList.getChildCount();
if (childCount == 1) { if (childCount == 1) {//当删除编辑文本时,执行这个函数
return; return;
} }
for (int i = index + 1; i < childCount; i++) { for (int i = index + 1; i < childCount; i++) {//将index后面的每一个项覆盖前面的项即将index的项删除后面补上去
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i - 1); .setIndex(i - 1);
} }
mEditTextList.removeViewAt(index); mEditTextList.removeViewAt(index);
NoteEditText edit = null; NoteEditText edit = null;
if(index == 0) { if(index == 0) {//如果index为0则将edit定位到第一个EditText项
edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(
R.id.et_edit_text); R.id.et_edit_text);
} else { } else {//index不为0则将edit定位到index-1对应的EditText项
edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(
R.id.et_edit_text); R.id.et_edit_text);
} }
@ -672,11 +676,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.setSelection(length); edit.setSelection(length);
} }
public void onEditTextEnter(int index, String text) { public void onEditTextEnter(int index, String text) {//当编辑便签中输入enter时执行该函数
/** /**
* Should not happen, check for debug * Should not happen, check for debug
*/ */
if(index > mEditTextList.getChildCount()) { if(index > mEditTextList.getChildCount()) {//如果越界就报错
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
} }
@ -685,17 +689,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
edit.requestFocus(); edit.requestFocus();
edit.setSelection(0); edit.setSelection(0);
for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {//遍历子文本框并设置对应对下标
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i); .setIndex(i);
} }
} }
private void switchToListMode(String text) { private void switchToListMode(String text) {//该函数转到列表模式
mEditTextList.removeAllViews(); mEditTextList.removeAllViews();
String[] items = text.split("\n"); String[] items = text.split("\n");
int index = 0; int index = 0;
for (String item : items) { for (String item : items) {//清空所有视图,初始化下标
if(!TextUtils.isEmpty(item)) { if(!TextUtils.isEmpty(item)) {
mEditTextList.addView(getListItem(item, index)); mEditTextList.addView(getListItem(item, index));
index++; index++;
@ -708,13 +712,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList.setVisibility(View.VISIBLE); mEditTextList.setVisibility(View.VISIBLE);
} }
private Spannable getHighlightQueryResult(String fullText, String userQuery) { private Spannable getHighlightQueryResult(String fullText, String userQuery) {//获取高亮效果的反馈结果
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
if (!TextUtils.isEmpty(userQuery)) { if (!TextUtils.isEmpty(userQuery)) {//将用户的询问进行解析,如果搜索结果不为空,执行下面函数
mPattern = Pattern.compile(userQuery); mPattern = Pattern.compile(userQuery);
Matcher m = mPattern.matcher(fullText); Matcher m = mPattern.matcher(fullText);
int start = 0; int start = 0;
while (m.find(start)) { while (m.find(start)) {//将匹配到的内容设置为高亮。
spannable.setSpan( spannable.setSpan(
new BackgroundColorSpan(this.getResources().getColor( new BackgroundColorSpan(this.getResources().getColor(
R.color.user_query_highlight)), m.start(), m.end(), R.color.user_query_highlight)), m.start(), m.end(),
@ -725,13 +729,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return spannable; return spannable;
} }
private View getListItem(String item, int index) { private View getListItem(String item, int index) {//获取列表项
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {//如果CheckBox已勾选则执行下面函数设置显示方式。
if (isChecked) { if (isChecked) {
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else { } else {
@ -740,11 +744,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
}); });
if (item.startsWith(TAG_CHECKED)) { if (item.startsWith(TAG_CHECKED)) {//判断是否勾选
cb.setChecked(true); cb.setChecked(true);
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
item = item.substring(TAG_CHECKED.length(), item.length()).trim(); item = item.substring(TAG_CHECKED.length(), item.length()).trim();
} else if (item.startsWith(TAG_UNCHECKED)) { } else if (item.startsWith(TAG_UNCHECKED)) {//选择不勾选项
cb.setChecked(false); cb.setChecked(false);
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();
@ -756,20 +760,20 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return view; return view;
} }
public void onTextChange(int index, boolean hasText) { public void onTextChange(int index, boolean hasText) {//便签内容发生改变所 触发的事件
if (index >= mEditTextList.getChildCount()) { if (index >= mEditTextList.getChildCount()) {//越界报错
Log.e(TAG, "Wrong index, should not happen"); Log.e(TAG, "Wrong index, should not happen");
return; return;
} }
if(hasText) { if(hasText) {//如果内容不为空则将其子编辑框可见性置为可见,否则不可见
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);
} else { } else {//选择框不可见
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
} }
} }
public void onCheckListModeChanged(int oldMode, int newMode) { public void onCheckListModeChanged(int oldMode, int newMode) {//检查模式和列表模式的切换
if (newMode == TextNote.MODE_CHECK_LIST) { if (newMode == TextNote.MODE_CHECK_LIST) {// 如果是变为清单模式
switchToListMode(mNoteEditor.getText().toString()); switchToListMode(mNoteEditor.getText().toString());
} else { } else {
if (!getWorkingText()) { if (!getWorkingText()) {
@ -782,11 +786,11 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
private boolean getWorkingText() { private boolean getWorkingText() {//设置勾选选项表并返回是否勾选的标记
boolean hasChecked = false; boolean hasChecked = false;
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//判断是否是清单模式
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < mEditTextList.getChildCount(); i++) { for (int i = 0; i < mEditTextList.getChildCount(); i++) {//for循环遍历EditTextList的项
View view = mEditTextList.getChildAt(i); View view = mEditTextList.getChildAt(i);
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
if (!TextUtils.isEmpty(edit.getText())) { if (!TextUtils.isEmpty(edit.getText())) {
@ -799,16 +803,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
mWorkingNote.setWorkingText(sb.toString()); mWorkingNote.setWorkingText(sb.toString());
} else { } else {//若不是该模式直接用编辑器中的内容设置运行中标签的内容
mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); mWorkingNote.setWorkingText(mNoteEditor.getText().toString());
} }
return hasChecked; return hasChecked;
} }
private boolean saveNote() { private boolean saveNote() {//保存便签
getWorkingText(); getWorkingText();
boolean saved = mWorkingNote.saveNote(); boolean saved = mWorkingNote.saveNote();
if (saved) { if (saved) {//如果workingNote已经保存则将结果设置为ok。
/** /**
* There are two modes from List view to edit view, open one note, * There are two modes from List view to edit view, open one note,
* create/edit a node. Opening node requires to the original * create/edit a node. Opening node requires to the original
@ -821,17 +825,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return saved; return saved;
} }
private void sendToDesktop() { private void sendToDesktop() {//将便签发送到桌面
/** /**
* Before send message to home, we should make sure that current * Before send message to home, we should make sure that current
* editing note is exists in databases. So, for new note, firstly * editing note is exists in databases. So, for new note, firstly
* save it * save it
*/ */
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {//若不存在数据也就是新的标签就先保存
saveNote(); saveNote();
} }
if (mWorkingNote.getNoteId() > 0) { if (mWorkingNote.getNoteId() > 0) {//若便签的id大于0则执行以下程序
Intent sender = new Intent(); Intent sender = new Intent();
Intent shortcutIntent = new Intent(this, NoteEditActivity.class); Intent shortcutIntent = new Intent(this, NoteEditActivity.class);
shortcutIntent.setAction(Intent.ACTION_VIEW); shortcutIntent.setAction(Intent.ACTION_VIEW);
@ -845,7 +849,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
showToast(R.string.info_note_enter_desktop); showToast(R.string.info_note_enter_desktop);
sendBroadcast(sender); sendBroadcast(sender);
} else { } else {//如果便签的id错误则保存提醒用户
/** /**
* There is the condition that user has input nothing (the note is * There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he * not worthy saving), we have no note id, remind the user that he
@ -856,18 +860,20 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
private String makeShortcutIconTitle(String content) { private String makeShortcutIconTitle(String content) {//编辑小图标的标题
content = content.replace(TAG_CHECKED, ""); content = content.replace(TAG_CHECKED, "");
content = content.replace(TAG_UNCHECKED, ""); content = content.replace(TAG_UNCHECKED, "");
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
SHORTCUT_ICON_TITLE_MAX_LEN) : content; SHORTCUT_ICON_TITLE_MAX_LEN) : content;//直接设置为content中的内容并返回有勾选和未勾选2种
} }
private void showToast(int resId) { private void showToast(int resId) {//显示提示的视图 函数实现:根据下标显示对应的提示
showToast(resId, Toast.LENGTH_SHORT); showToast(resId, Toast.LENGTH_SHORT);
} }
private void showToast(int resId, int duration) { private void showToast(int resId, int duration) {
//持续显示提示的视图 函数实现根据下标和持续的时间duration编辑提示视图并显示
Toast.makeText(this, resId, duration).show(); Toast.makeText(this, resId, duration).show();
} }
} }

@ -37,17 +37,17 @@ 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 {//声明了一个公有类NoteEditText,它继承了EditText
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText";//标志为字符串"NoteEditText"
private int mIndex; private int mIndex;
private int mSelectionStartBeforeDelete; private int mSelectionStartBeforeDelete;
private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_TEL = "tel:" ;//声明字符串常量,标志电话、网址、邮件
private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ; private static final String SCHEME_EMAIL = "mailto:" ;
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();//设置映射,将文本内容(电话、网址、邮件)做链接处理
static { static {//这个接口将会被NoteEditActivity实现来删除或添加编辑文本
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
@ -56,52 +56,52 @@ 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 {//该接口用于实现对TextView组件中的文字信息进行修改
/** /**
* 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);//当触发删除文本KeyEvent时删除文本
/** /**
* 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);//当触发输入文本KeyEvent时增添文本
/** /**
* 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);//文字更改时隐藏或显示项目选项
} }
private OnTextViewChangeListener mOnTextViewChangeListener; private OnTextViewChangeListener mOnTextViewChangeListener;
public NoteEditText(Context context) { public NoteEditText(Context context) {//这个函数是NoteEditText的构造函数,直接借用了父类的构造函数
super(context, null); super(context, null);
mIndex = 0; mIndex = 0;
} }
public void setIndex(int index) { public void setIndex(int index){//这个函数设置了针对textview的监听器
mIndex = index; mIndex = 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()) {//根据按键的KeyCode来处理
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
int x = (int) event.getX(); int x = (int) event.getX();
@ -123,7 +123,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) {//根据按键的KeyCode来处理
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
return false; return false;
@ -139,8 +139,8 @@ 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) {//根据按键的 Unicode 编码值来处理有删除和进入2种操作
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
@ -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,8 +180,8 @@ 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();
@ -189,16 +189,16 @@ public class NoteEditText extends EditText {
int max = Math.max(selStart, selEnd); int max = Math.max(selStart, selEnd);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) { if (urls.length == 1) {//设置url的信息的范围值
int defaultResId = 0; int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) { for(String schema: sSchemaActionResMap.keySet()) {//获取计划表中所有的key值
if(urls[0].getURL().indexOf(schema) >= 0) { if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema); defaultResId = sSchemaActionResMap.get(schema);
break; break;
} }
} }
if (defaultResId == 0) { if (defaultResId == 0) {//defaultResId == 0则说明url并没有添加任何东西所以置为连接其他SchemaActionResMap的值
defaultResId = R.string.note_link_other; defaultResId = R.string.note_link_other;
} }

@ -26,8 +26,8 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; 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,
@ -42,7 +42,7 @@ public class NoteItemData {
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;//声明类属性,包括背景颜色、手机号码等
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3; private static final int CREATED_DATE_COLUMN = 3;
@ -76,51 +76,52 @@ 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) {//初始化NoteItemData利用光标和context获取的内容
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);//调用getxxxx的函数是指 数据库游标通过把参数索引获得数据
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);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;//判断行列
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(//把每项前的方框符号和✔符号去掉
NoteEditActivity.TAG_UNCHECKED, ""); NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN); mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = ""; mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {//初始化电话号码的信息
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) { if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber); mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) { if (mName == null) {
mName = mPhoneNumber; mName = mPhoneNumber;
} }
} }
} }
if (mName == null) { if (mName == null) {//如果没有对name复制成功则把name设置为空值
mName = ""; mName = "";
} }
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) {//如果是note格式并且不是第一个元素则获取光标位置并根据上一行信息更改标记
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
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {//若光标满足SYSTEM或FOLDER格式
if (cursor.getCount() > (position + 1)) { if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true; mIsMultiNotesFollowingFolder = true;
} else { } else {
@ -136,7 +137,7 @@ public class NoteItemData {
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }//以下都是获取标记的函数
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;

@ -79,65 +79,66 @@ 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; //这个类继承于Activity类实现了两个接口分别是点击监听器和长按监听器即在这个类的界面实现对这两种操作的响应这是整个project的主类
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;//查询记号
private static final int MENU_FOLDER_DELETE = 0; private static final int MENU_FOLDER_DELETE = 0;//删除菜单文件
private static final int MENU_FOLDER_VIEW = 1; private static final int MENU_FOLDER_VIEW = 1;// 阅读菜单文件
private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final int MENU_FOLDER_CHANGE_NAME = 2;//更改菜单文件名称
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";//用于第一次打开小米便签的判断
private enum ListEditState { private enum ListEditState {//列表编辑三种状态
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
}; };
private ListEditState mState; private ListEditState mState;// 声明一些私有属性
private BackgroundQueryHandler mBackgroundQueryHandler; private BackgroundQueryHandler mBackgroundQueryHandler;//后台疑问处理功能
private NotesListAdapter mNotesListAdapter; private NotesListAdapter mNotesListAdapter;//便签列表配适器
private ListView mNotesListView; private ListView mNotesListView;//主界面的视图
private Button mAddNewNote; private Button mAddNewNote;//最下方添加便签的按钮
private boolean mDispatch; private boolean mDispatch;//是否调度的判断变量
private int mOriginY; private int mOriginY;//首次触摸时屏幕上的垂直距离y值
private int mDispatchY; private int mDispatchY;//重新调度时的触摸的在屏幕上的垂直距离
private TextView mTitleBar; private TextView mTitleBar;//子文件夹下的标头
private long mCurrentFolderId; private long mCurrentFolderId;//当前文件夹的ID
private ContentResolver mContentResolver; private ContentResolver mContentResolver;//提供内容分析
private ModeCallback mModeCallBack; private ModeCallback mModeCallBack;//返回调用方法
private static final String TAG = "NotesListActivity"; private static final String TAG = "NotesListActivity";//名称(可用于日志文件调试)
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;//列表滚轮速度
private NoteItemData mFocusNoteDataItem; private NoteItemData mFocusNoteDataItem;//所指的便签数据内容
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";//定义私有字符串变量
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"//用于表明处于父文件夹下(主列表)
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)"; + NoteColumns.NOTES_COUNT + ">0)";
private final static int REQUEST_CODE_OPEN_NODE = 102; private final static int REQUEST_CODE_OPEN_NODE = 102;//请求代码开放节点
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);//super调用父类的protected函数,创建窗口时使用
setContentView(R.layout.note_list); setContentView(R.layout.note_list);
initResources(); initResources();
@ -148,38 +149,38 @@ 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);
} else { } else {//如果条件不满足则将数据返回给父类即调用父类的onActivityResult()。
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
} }
} }
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();
InputStream in = null; InputStream in = null;
try { try {//从原始配置文件当中获取基本信息
in = getResources().openRawResource(R.raw.introduction); in = getResources().openRawResource(R.raw.introduction);
if (in != null) { if (in != null) {//如果加载到输入流成功,填充到缓冲区里
InputStreamReader isr = new InputStreamReader(in); InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr);
char [] buf = new char[1024]; char [] buf = new char[1024];
int len = 0; int len = 0;
while ((len = br.read(buf)) > 0) { while ((len = br.read(buf)) > 0) {//不断在buf中读取数据放入sb里
sb.append(buf, 0, len); sb.append(buf, 0, len);
} }
} else { } else {
Log.e(TAG, "Read introduction file error"); Log.e(TAG, "Read introduction file error");//报错,读取文件错误
return; return;
} }
} catch (IOException e) { } catch (IOException e) {//获取IO中断异常
e.printStackTrace(); e.printStackTrace();
return; return;
} finally { } finally {// finally是必然会执行的部分
if(in != null) { if(in != null) {
try { try {
in.close(); in.close();
@ -194,7 +195,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED); ResourceParser.RED);
note.setWorkingText(sb.toString()); note.setWorkingText(sb.toString());
if (note.saveNote()) { if (note.saveNote()) {//判断便签是否保存成功。
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else { } else {
Log.e(TAG, "Save introduction note error"); Log.e(TAG, "Save introduction note error");
@ -204,12 +205,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
protected void onStart() { protected void onStart() {//调用父类的onCreate活动和同步便签列表
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;
@ -232,18 +233,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
//实现了ActionMode接口该接口继承了MultiChoiceListenerOnMenuItemClickListener两个类用户界面所看到的就是长按后进入多选模式以及之后的多种操作
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);
if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
|| DataUtils.getUserFolderCount(mContentResolver) == 0) { || DataUtils.getUserFolderCount(mContentResolver) == 0) {//如果父类id在文件夹中保存或者用户文件数量为零设置移动菜单为不可见否者设为可见
mMoveMenu.setVisible(false); mMoveMenu.setVisible(false);
} else { } else {//设置菜单项目为可见
mMoveMenu.setVisible(true); mMoveMenu.setVisible(true);
mMoveMenu.setOnMenuItemClickListener(this); mMoveMenu.setOnMenuItemClickListener(this);
} }
@ -259,7 +261,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
(Button) customView.findViewById(R.id.selection_menu), (Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown); R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {//点击菜单时,设置为全选并更新菜单
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu(); updateMenu();
return true; return true;
@ -269,13 +271,14 @@ 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);
mDropDownMenu.setTitle(format); mDropDownMenu.setTitle(format);
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
if (item != null) { if (item != null) {//当全选成功,则将“全选”菜单项改为“取消全选”菜单,否则仍保持“全选”菜单项。
if (mNotesListAdapter.isAllSelected()) { if (mNotesListAdapter.isAllSelected()) {
item.setChecked(true); item.setChecked(true);
item.setTitle(R.string.menu_deselect_all); item.setTitle(R.string.menu_deselect_all);
@ -286,40 +289,41 @@ 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);
} }
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) {//勾选的状态改变时,更改勾选状态,更新菜单
mNotesListAdapter.setCheckedItem(position, checked); mNotesListAdapter.setCheckedItem(position, checked);
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()) {//根据id号判断是删除还是移动
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,10 +350,10 @@ 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();
int screenHeight = display.getHeight(); int screenHeight = display.getHeight();
@ -359,7 +363,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
/** /**
* Minus TitleBar's height * Minus TitleBar's height
*/ */
if (mState == ListEditState.SUB_FOLDER) { if (mState == ListEditState.SUB_FOLDER) {//如果再其他文件夹下则需要减去子文件夹的title的高度
eventY -= mTitleBar.getHeight(); eventY -= mTitleBar.getHeight();
start -= mTitleBar.getHeight(); start -= mTitleBar.getHeight();
} }
@ -372,11 +376,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
* Notice that, if the background of the button changes, the formula should * Notice that, if the background of the button changes, the formula should
* also change. This is very bad, just for the UI designer's strong requirement. * also change. This is very bad, just for the UI designer's strong requirement.
*/ */
if (event.getY() < (event.getX() * (-0.12) + 94)) { if (event.getY() < (event.getX() * (-0.12) + 94)) {//如果当前点击的位置不在“写便签”区域内
View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1
- mNotesListView.getFooterViewsCount()); - mNotesListView.getFooterViewsCount());
if (view != null && view.getBottom() > start if (view != null && view.getBottom() > start
&& (view.getTop() < (start + 94))) { && (view.getTop() < (start + 94))) {//如果不在新建便签的按钮上,重新调度响应按键
mOriginY = (int) event.getY(); mOriginY = (int) event.getY();
mDispatchY = eventY; mDispatchY = eventY;
event.setLocation(event.getX(), mDispatchY); event.setLocation(event.getX(), mDispatchY);
@ -386,7 +390,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);
@ -396,7 +400,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
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 +412,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,18 +421,19 @@ 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);
} }
@Override @Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) { protected void onQueryComplete(int token, Object cookie, Cursor cursor) {//查询完成后对光标的处理
switch (token) { switch (token) {
case FOLDER_NOTE_LIST_QUERY_TOKEN: case FOLDER_NOTE_LIST_QUERY_TOKEN://如果是便签查询被采用,更改光标位置
mNotesListAdapter.changeCursor(cursor); mNotesListAdapter.changeCursor(cursor);
break; break;
case FOLDER_LIST_QUERY_TOKEN: case FOLDER_LIST_QUERY_TOKEN://如果是采用列表查询,显示菜单列表
if (cursor != null && cursor.getCount() > 0) { if (cursor != null && cursor.getCount() > 0) {
showFolderListMenu(cursor); showFolderListMenu(cursor);
} else { } else {
@ -441,13 +446,13 @@ 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);//文件夹列表配适器
builder.setAdapter(adapter, new DialogInterface.OnClickListener() { builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {//为对话框设置监听事件
DataUtils.batchMoveToFolder(mContentResolver, DataUtils.batchMoveToFolder(mContentResolver,
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
Toast.makeText( Toast.makeText(
@ -462,18 +467,18 @@ 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);//新建一个意图与NoteEditActivity相关联
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();
if (!isSyncMode()) { if (!isSyncMode()) {//如果为同步模式则删除笔记,若删除不成功打印错误信息
// if not synced, delete notes directly // if not synced, delete notes directly
if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
.getSelectedItemIds())) { .getSelectedItemIds())) {
@ -492,7 +497,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) { protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {//这是一个循环体结构如果id不等的话会进行更新id的操作。
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 +511,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 +521,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) {//如果存在对应桌面挂件那么判断挂件信息如果挂件id有效且挂件类型有效则更新挂件信息
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,23 +538,23 @@ 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) {//如果当前id是保存在文件夹的id将列表编辑状态置为call文件夹否则设置为镜像文件夹
mState = ListEditState.CALL_RECORD_FOLDER; mState = ListEditState.CALL_RECORD_FOLDER;
mAddNewNote.setVisibility(View.GONE); mAddNewNote.setVisibility(View.GONE);
} else { } else {
mState = ListEditState.SUB_FOLDER; mState = ListEditState.SUB_FOLDER;
} }
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//如果当前id是保存在文件夹的id设置标题内容为文件夹名字否则设置为文本的前部片段内容
mTitleBar.setText(R.string.call_record_folder_name); mTitleBar.setText(R.string.call_record_folder_name);
} else { } else {
mTitleBar.setText(data.getSnippet()); mTitleBar.setText(data.getSnippet());
@ -557,8 +562,8 @@ 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()) {//得到我们所点击组件的ID号并进行判断
case R.id.btn_new_note: case R.id.btn_new_note:
createNewNote(); createNewNote();
break; break;
@ -567,24 +572,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) {//若输入为空进行对应操作使软键盘显示第二个参数hideFlags用来设置是否隐藏等于0
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);//获得et_foler_name这个组件并将其转化为EditText类
showSoftInput(); showSoftInput();
if (!create) { if (!create) {//如果create==false将对话框标题设置为 修改文件夹名称,否则设置为新建文件夹
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));
@ -600,23 +605,24 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
//点击触发软键盘隐藏
hideSoftInput(etName); hideSoftInput(etName);
} }
}); });
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) {//当文件名字存在时判断是否为创建操作若不是则更新values信息若是则插入values信息
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);
@ -637,27 +643,27 @@ 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,8 +671,8 @@ 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;
mState = ListEditState.NOTE_LIST; mState = ListEditState.NOTE_LIST;
@ -688,9 +694,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
private void updateWidget(int appWidgetId, int appWidgetType) { private void updateWidget(int appWidgetId, int appWidgetType) {//更新不同widget的插件
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) {//判断不同类型widget的操作并建立不同的类型
intent.setClass(this, NoteWidgetProvider_2x.class); intent.setClass(this, NoteWidgetProvider_2x.class);
} else if (appWidgetType == Notes.TYPE_WIDGET_4X) { } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
intent.setClass(this, NoteWidgetProvider_4x.class); intent.setClass(this, NoteWidgetProvider_4x.class);
@ -699,7 +705,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return; return;
} }
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {//putExtra中两个参数为键对值第一个参数为键名
appWidgetId appWidgetId
}); });
@ -707,9 +713,9 @@ 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());
menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);
menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);
@ -719,20 +725,20 @@ 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);//不设置监听事件
} }
super.onContextMenuClosed(menu); super.onContextMenuClosed(menu);
} }
@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;
} }
switch (item.getItemId()) { switch (item.getItemId()) {//根据项目id判断要执行的功能分别是打开文件、删除文件以及更改文件名
case MENU_FOLDER_VIEW: case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem); openFolder(mFocusNoteDataItem);
break; break;
@ -761,9 +767,9 @@ 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);
// set sync or sync_cancel // set sync or sync_cancel
menu.findItem(R.id.menu_sync).setTitle( menu.findItem(R.id.menu_sync).setTitle(
@ -779,8 +785,9 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {//实现菜单项目的操作通过case语句对各个菜单项目分别设置事件
switch (item.getItemId()) { switch (item.getItemId()) {//五个菜单项的响应实现
//调用不同方法实现不同菜单项
case R.id.menu_new_folder: { case R.id.menu_new_folder: {
showCreateOrModifyFolderDialog(true); showCreateOrModifyFolderDialog(true);
break; break;
@ -790,13 +797,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
break; break;
} }
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))) {//如果项目title与菜单同步相同则进行同步
GTaskSyncService.startSync(this); GTaskSyncService.startSync(this);
} else { } else {
GTaskSyncService.cancelSync(this); GTaskSyncService.cancelSync(this);
} }
} else { } else {//如果不是同步模式,则开始设置动作
startPreferenceActivity(); startPreferenceActivity();
} }
break; break;
@ -819,23 +826,24 @@ 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>() {
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
//未被占用的话后台进行
return backup.exportToText(); return backup.exportToText();
} }
@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 +851,8 @@ 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) {//如果导出成功,则显示成功
//并且会显示“Export text file 《便签名称》 to SD 《目录名称》 directory”
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 +861,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) {//如果系统错误,则显示 导出失败请检查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));
@ -866,20 +875,20 @@ 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) {//判断view是否是NotesListItem的一个实例如果是就获取他的项目信息装入item中
NoteItemData item = ((NotesListItem) view).getItemData(); NoteItemData item = ((NotesListItem) view).getItemData();
if (mNotesListAdapter.isInChoiceMode()) { if (mNotesListAdapter.isInChoiceMode()) {
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
@ -890,7 +899,7 @@ 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) {
@ -917,7 +926,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 + ")";
@ -927,7 +936,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
FoldersListAdapter.PROJECTION, FoldersListAdapter.PROJECTION,
selection, selection,
new String[] { new String[] {//新建字符列表
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.TYPE_FOLDER),
String.valueOf(Notes.ID_TRASH_FOLER), String.valueOf(Notes.ID_TRASH_FOLER),
String.valueOf(mCurrentFolderId) String.valueOf(mCurrentFolderId)
@ -936,6 +945,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//实现长按项目的点击事件。如果长按的是便签则通过ActionMode菜单实现如果长按的是文件夹则通过ContextMenu菜单实现。
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,56 +31,56 @@ 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;//HashMap是一个散列表储存键值对的映射关系
private int mNotesCount; private int mNotesCount;
private boolean mChoiceMode; private boolean mChoiceMode;//选择模式标志
public static class AppWidgetAttribute { public static class AppWidgetAttribute {//桌面widget的属性包括编号和类型
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;//新建一个视图来存储光标所指向的数据
mNotesCount = 0; mNotesCount = 0;
} }
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {//利用NotesListLtem类创建新布局
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) {//将已经存在的视图和鼠标指向的数据进行捆绑
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor); NoteItemData itemData = new NoteItemData(context, cursor);//新建一个项目选项并且用bind跟将view和鼠标内容便签数据捆绑在一起
((NotesListItem) view).bind(context, itemData, mChoiceMode, ((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition())); isSelectedItem(cursor.getPosition()));
} }
} }
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) {//重置下标并根据参数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++) {//历可用光标位置如果光标移动且光标当前指向的便签项目类型为TYPE_NOTE则设置为勾选状态
if (cursor.moveToPosition(i)) { if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked); setCheckedItem(i, checked);
@ -89,15 +89,15 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {//建立选择项目的ID的HASH表
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) {
Long id = getItemId(position); Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) { if (id == Notes.ID_ROOT_FOLDER) {//原文件不需要添加则将id该下标假如选项集合中
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "Wrong item id, should not happen");
} else { } else {
itemSet.add(id); itemSet.add(id);//将该id加入到选项集合当中
} }
} }
} }
@ -105,22 +105,22 @@ 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) {
Cursor c = (Cursor) getItem(position); Cursor c = (Cursor) getItem(position);//获取条目
if (c != null) { if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c); NoteItemData item = new NoteItemData(mContext, c);//新建widget并更新ID和类型最后添加到选项表中
widget.widgetId = item.getWidgetId(); widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType(); widget.widgetType = item.getWidgetType();
itemSet.add(widget); itemSet.add(widget);//加入条目集合
/** /**
* Don't close cursor here, only the adapter could close it * Don't close cursor here, only the adapter could close it
*/ */
} else { } else {
Log.e(TAG, "Invalid cursor"); Log.e(TAG, "Invalid cursor");//设置标签无效的cursor
return null; return null;
} }
} }
@ -128,14 +128,14 @@ 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()) {//如果iter后面还有则count加一
if (true == iter.next()) { if (true == iter.next()) {
count++; count++;
} }
@ -143,40 +143,40 @@ 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;
} }
return mSelectedIndex.get(position); return mSelectedIndex.get(position);//判断Item是否被选中的状态
} }
@Override @Override
protected void onContentChanged() { protected void onContentChanged() {//activity内容变动时调用calcNotesCount计算便签数量
super.onContentChanged(); super.onContentChanged();//执行父类函数
calcNotesCount(); calcNotesCount();
} }
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);//重载父类函数
calcNotesCount(); calcNotesCount();
} }
private void calcNotesCount() { private void calcNotesCount() {//实现方式类似前面代码中的selectAll函数
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) {//判断语句如果光标不是null那么便得到信息便签数目加1
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {//若选项的数据类型为便签类型,那么计数+1
mNotesCount++; mNotesCount++;
} }
} else { } else {
Log.e(TAG, "Invalid cursor"); Log.e(TAG, "Invalid cursor");//否则就将设置为无效的光标
return; return;
} }
} }

@ -30,80 +30,82 @@ 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 {// 构建便签列表的各个项目的详细具体信息
private ImageView mAlert; private ImageView mAlert;//闹钟图片
private TextView mTitle; private TextView mTitle;//标题
private TextView mTime; private TextView mTime;//时间
private TextView mCallName; private TextView mCallName;//闹铃名称
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);//inflate()作用就是将xml定义的一个布局找出来
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mAlert = (ImageView) findViewById(R.id.iv_alert_icon);//findViewById用于从contentView中查找指定ID的View转换出来的形式根据需要而定
mTitle = (TextView) findViewById(R.id.tv_title); mTitle = (TextView) findViewById(R.id.tv_title);//获取题目
mTime = (TextView) findViewById(R.id.tv_time); mTime = (TextView) findViewById(R.id.tv_time);//获取时间
mCallName = (TextView) findViewById(R.id.tv_name); mCallName = (TextView) findViewById(R.id.tv_name);//获取标题
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) {//根据data的属性对各个控件的属性的控制
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { // 主要是可见性Visibility内容setText格式setTextAppearance
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {//如果处于选择模式并且是便签类型时,设置为可见及勾选,否则设置为不可见。
mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked); mCheckBox.setChecked(checked);//设置勾选
} else { } else {
mCheckBox.setVisibility(View.GONE); mCheckBox.setVisibility(View.GONE);//否则设置复选框不可见
} }
mItemData = data; mItemData = data;//把数据传给标签
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//设置控件属性通过判断保存到文件夹的ID、当前ID以及父ID之间关系决定
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);//设置setText 的style
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);//编写联系人姓名文本框
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { if (data.hasAlert()) {//如果当前便签存在提醒时间
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);//设置图片来源
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);//
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} }//否则设置提醒图标不可见
} else { } else {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);//如果父类和当前id均与保存在文件夹中的id不同设置联系人姓名不可见
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {//设置标题格式
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet()//设置便签标题内容为便签的前面部分的内容+文件数+便签数
+ context.getString(R.string.format_folder_files_count, + context.getString(R.string.format_folder_files_count,
data.getNotesCount())); data.getNotesCount()));
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} else { } else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { //若没有设置标题,将标题设置为内容前面部分
if (data.hasAlert()) {//若存在提醒时间
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);//否则设置威不可见
} }
} }
} }
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) {//根据data的文件属性来设置背景
int id = data.getBgColorId(); int id = data.getBgColorId();//获取id用此id用来获取背景颜色
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {//若是note型文件则4种情况对于4种不同情况的背景来源
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {//单个数据或只有一个文件夹
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));//设置背景颜色为单个便签背景
} else if (data.isLast()) { } else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) { } else if (data.isFirst() || data.isMultiFollowingFolder()) {
@ -118,5 +120,5 @@ public class NotesListItem extends LinearLayout {
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }//返回当前便签的文件信息
} }

@ -49,60 +49,64 @@ import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
//NotesPreferenceActivity在小米便签中主要实现的是对背景颜色和字体大小的数据储存。
// 继承了PreferenceActivity主要功能为对系统信息和配置进行自动保存的Activity
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "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";
//同步时间
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; public static final String PREFERENCE_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";
//
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
//同步账户密码
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
//设置本地密码
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
//设置账户分组
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
//同步任务接收器
private Account[] mOriAccounts; private Account[] mOriAccounts;
//账户
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
// 账户的has标记
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {//创建一个activity在函数里要完成所有的正常静态设置
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);
mReceiver = new GTaskReceiver(); //根据同步账户密码进行账户分组
IntentFilter filter = new IntentFilter(); mReceiver = new GTaskReceiver();//设置同步任务接收器
IntentFilter filter = new IntentFilter();//设置过滤项
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
//注册监听器和对应的filter绑定
mOriAccounts = null; mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
//从xml获取Listview获取listvivewListView的作用:用于列出所有选择
} }
@Override @Override
protected void onResume() { protected void onResume() {//activity交互功能的实现用于接受用户的输入
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();//获取google同步账户
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) {//循环判断当前账户列表中的账户是否与新建账户名相同
if (TextUtils.equals(accountOld.name, accountNew.name)) { if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true; found = true;
break; break;//.若是没有找到旧的账户,那么同步账号中就只添加新账户
} }
} }
if (!found) { if (!found) {
@ -117,70 +121,72 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {//销毁Activity
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));//与google task同步便签记录
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {//设置preference的的监听器
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {//功能描述:响应偏好对应元素的点击
if (!GTaskSyncService.isSyncing()) { //函数实现:判断是否处于同步模式和默认的数据,指向不同的操作
if (!GTaskSyncService.isSyncing()) {//若不在同步状态
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // the first time to set account
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // if the account has already been set, we need to promp
// user about the risk // user about the risk
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();//已有账户则显示确认对话框
} }
} else { } else {//若处于同步状态的情况下
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); .show();
} }//不能切换处于同步的账号
return true; return true;
} }
}); });
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)); if (GTaskSyncService.isSyncing()) {//若是在同步状态下
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setText(getString(R.string.preferences_button_sync_cancel));//
syncButton.setOnClickListener(new View.OnClickListener() {//设置监听器
public void onClick(View v) { public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
} }
}); });
} 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) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
@ -189,74 +195,75 @@ public class NotesPreferenceActivity extends PreferenceActivity {
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
} else { } else {
lastSyncTimeView.setVisibility(View.GONE); lastSyncTimeView.setVisibility(View.GONE);
} }//最近同步时间为空设置同步时间不可见
} }
} }
private void refreshUI() { private void refreshUI() {
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);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);//设置标题及子标题内容
dialogBuilder.setPositiveButton(null, null); dialogBuilder.setPositiveButton(null, null);//取消设置键按钮
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();//获得谷歌当前账户列表
String defAccount = getSyncAccountName(this); String defAccount = getSyncAccountName(this);//默认账户
mOriAccounts = accounts; mOriAccounts = accounts;
mHasAddedAccount = false; mHasAddedAccount = false;//获得账户同步信息
if (accounts.length > 0) { if (accounts.length > 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;
int index = 0; int index = 0;
for (Account account : accounts) { for (Account account : accounts) {//for循环检查账户列表
if (TextUtils.equals(account.name, defAccount)) { if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index; checkedItem = index;//查询目标账户
} }
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());//同步账户设置
dialog.dismiss(); dialog.dismiss();//取消对话框
refreshUI(); refreshUI();//刷新界面
} }
}); });
} }
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;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls" "gmail-ls"
}); });//建立网络组件
startActivityForResult(intent, -1); startActivityForResult(intent, -1);//返回上一选项
dialog.dismiss(); dialog.dismiss();
} }
}); });
} }
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);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
@ -269,42 +276,42 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
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();
} else if (which == 1) { } else if (which == 1) {
removeSyncAccount(); removeSyncAccount();
refreshUI(); refreshUI();
} }
} }
}); });//
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();
if (account != null) { if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);//若账户不为空,编辑账户的首选项
} else { } else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
editor.commit(); editor.commit();//提交数据
// clean up last sync time // clean up last sync time
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// 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() {//清除本地的gtask关联的信息 将一些参数设置为0或NULL
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0); values.put(NoteColumns.SYNC_ID, 0);
@ -314,24 +321,24 @@ public class NotesPreferenceActivity extends PreferenceActivity {
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();//将toast的文本信息置为“设置账户成功”并显示出来
} }
} }
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)) {//若当前账户首选项存在数据,就删除
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
} }
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {//删除当前账户存在时间
editor.remove(PREFERENCE_LAST_SYNC_TIME); editor.remove(PREFERENCE_LAST_SYNC_TIME);
} }
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() {//清除本地的gtask关联的信息将一些参数设置为0或NULL
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0); values.put(NoteColumns.SYNC_ID, 0);
@ -340,49 +347,50 @@ 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();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
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) {//获取随广播而来的Intent中的同步服务的数据
refreshUI(); refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
} }//如果在同步状态,改变同步按钮显示的文本
} }
} }
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);
//开始创建活动
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);
return true; return true;
default: default:
return false; return false;//若出现错误则返回
} }
} }
} }

Loading…
Cancel
Save