Compare commits

...

33 Commits

Author SHA1 Message Date
2310175682@qq.com 47fbd00574 other
2 years ago
2310175682@qq.com 104b0aeec5 other
2 years ago
2310175682@qq.com 4f14defff4 src
2 years ago
2310175682@qq.com ec082210d9 doc
2 years ago
2310175682@qq.com 885550904a doc
2 years ago
2310175682@qq.com 6af86bcc43 src
2 years ago
2310175682@qq.com de225604a1 Merge branch 'xiaokaiwen_branch' of https://bdgit.educoder.net/pvg45a2sy/git-xiaomibianqian
2 years ago
2310175682@qq.com dbd1b1dafa Merge branch 'master' of https://bdgit.educoder.net/pvg45a2sy/git-xiaomibianqian
2 years ago
2310175682@qq.com 8cd085e040 doc
2 years ago
wukunwei 2e420816bc 吴堃玮
2 years ago
wukunwei d26d136d0d model
2 years ago
wukunwei fc71734993 Initial commit
2 years ago
wukunwei 715a354ce1 1
2 years ago
pvg45a2sy 4cbe043b5e Merge pull request 'src' (#7) from develop into master
2 years ago
wukunwei b84c401bba Merge branch 'master' of https://bdgit.educoder.net/pvg45a2sy/git-xiaomibianqian into develop
2 years ago
wukunwei 8a7bfc4bb8 src
2 years ago
wukunwei 94f9ed419b 1
2 years ago
pvg45a2sy 1a3edab75f Merge pull request '肖凯文' (#5) from xiaokaiwen_branch into develop
2 years ago
pvg45a2sy ee01037fc2 Merge pull request '李昊阳' (#4) from lihaoyang_branch into develop
2 years ago
李昊阳 1320d150f3 李昊阳
2 years ago
李昊阳 8554a70193 Merge branch 'develop' of https://bdgit.educoder.net/pvg45a2sy/git-xiaomibianqian into lihaoyang_branch
2 years ago
2310175682@qq.com 2393587f90 Merge branch 'develop' of https://bdgit.educoder.net/pvg45a2sy/git-xiaomibianqian into xiaokaiwen_branch
2 years ago
pvg45a2sy bd3c812553 Merge pull request '许超雨model' (#2) from xuchaoyu_branch into develop
2 years ago
2310175682@qq.com cfdbd0ad77 1
2 years ago
2310175682@qq.com 87e9a6a587 肖凯文
2 years ago
wukunwei 026574b801 src
2 years ago
wukunwei 411c6eb0c8 doc
2 years ago
李昊阳 bc3a585e3a 小米便签注释
2 years ago
wukunwei 08a8e48c2b 1
2 years ago
wukunwei 278be3984e src
2 years ago
李昊阳 c0fb563004 mm
2 years ago
2310175682@qq.com 00ec1c070b src
2 years ago
wukunwei 6334e41dba doc/小米便签源代码泛读报告.docx
2 years ago

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

@ -0,0 +1,43 @@
一、
用例名:在小米便签中插入视频或图片
业务目标:允许用户在小米便签中插入视频或图片
执行者:小米便签用户
前置条件:
用户已经打开小米便签应用程序,并已经登录
用户已经创建或打开了一个便签进入编辑界面
触发条件:用户想要在笔记中插入视频或图片
基本交互动作:
用户在编辑笔记的页面中选择需要插入视频或图片的位置
用户点击添加媒体按钮
系统弹出媒体库选择框,用户可以选择从相册导入或拍摄视频或拍摄照片
用户选择并添加所需的视频或图片
系统将视频或图片插入到笔记中,并根据需要自动调整大小和位置
扩展交互动作:
1a. 用户可以调整视频或图片的大小和位置
用户长按视频或图片,拖动手指以调整位置
用户使用两个手指放大或缩小视频或图片以调整大小
2a. 用户可以删除视频或图片
用户长按视频或图片,系统弹出删除确认对话框,用户确认后,系统将视频或图片从笔记中删除
二、
用例名:在小米便签中设置标题段落行距
业务目标:允许用户在小米便签中设置标题段落的行距
执行者:小米便签用户
前置条件:
用户已经打开小米便签应用程序,并已经登录
用户已经创建或打开了一个便签进入编辑界面
触发条件:用户想要设置标题段落的行距
基本交互动作:
用户选中需要设置行距的标题段落
用户在编辑笔记的页面中选择需要设置行距的标题段落
用户双击标题段落,或者长按标题段落并选择“编辑”
用户点击设置行距按钮
在标题段落上方的菜单栏中,用户点击“行距”按钮
系统弹出行距设置框,用户可以选择所需的行距
系统弹出行距设置框,用户可以从下拉列表中选择所需的行距
用户选择所需的行距
用户在行距设置框中选择所需的行距,或者点击“取消”按钮以取消行距设置
系统将行距应用到标题段落中
系统将用户选择的行距应用到标题段落中,并自动调整段落的行距
扩展交互动作:
1a. 用户可以调整标题段落的字体大小和样式
在编辑笔记的页面中,用户可以选择标题段

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 262 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

@ -0,0 +1,74 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;//当前文件所在的包名
/*接下来引用android的一些库*/
import android.content.Context;//调用Android自带的类
import android.database.Cursor;//从数据库导入Cursor
import android.provider.ContactsContract.CommonDataKinds.Phone;//导入联系人电话
import android.provider.ContactsContract.Data;//存储通讯信息
import android.telephony.PhoneNumberUtils;//格式化用户输入的电话号码
import android.util.Log;//安卓日志输出工具类
import java.util.HashMap;//用hashmap存储联系人信息
public class Contact {//存放联系人信息
private static HashMap<String, String> sContactCache;//存储联系人及对应的电话号码
private static final String TAG = "Contact";//定义字符串常量 TAG指向Contact
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER//定义 CALLER_ID_SELECTION字符串用于匹配联系人
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "//定义的callerIDSELEDTION所包含的各项数据
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/*Context context phoneNumber
*/
public static String getContact(Context context, String phoneNumber) {//获取联系人
if(sContactCache == null) {//如果当前还没有联系人那么新建一个HashMap存储联系人
sContactCache = new HashMap<String, String>();//创建哈希表
}
if(sContactCache.containsKey(phoneNumber)) {//如果hashmap实例里包含电话号码则返回电话号码
return sContactCache.get(phoneNumber);//如果根据电话号码phoneNumber索引到了对应的联系人那么把对应的联系人的信息返回
}
String selection = CALLER_ID_SELECTION.replace("+",//将CALLER_ID_SELECTION的“+”号替代为号码的后MIN_MATCH位
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query(//通过selection的查询语句去数据库查询
Data.CONTENT_URI,//提供联系人的内容的地址
new String [] { Phone.DISPLAY_NAME },//返回联系人名字
selection,//设置条件相当于whlie
new String[] { phoneNumber },//get..函数返回字符串类phoneNUmber手机号码
null);//判定查询结果
if (cursor != null && cursor.moveToFirst()) {// 判断查询结果,如果找到,并且成功返回第一天数据
try {//得到cursor的第一个字符串name
String name = cursor.getString(0);//从内容中获取联系人姓名
sContactCache.put(phoneNumber, name);//将联系人姓名和电话号码写入缓存
return name;//返回名字
} catch (IndexOutOfBoundsException e) {//出现异常
Log.e(TAG, " Cursor get string error " + e.toString());//Log.e为红色可以想到error错误这里仅显示红色的错误信息
return null;
} finally {//关闭数据库的访问
cursor.close();//关闭数据库的访问
}
} else {//未找到相关信息,返回空指针
Log.d(TAG, "No contact matched with number:" + phoneNumber);//如果没有找到信息,返回没有匹配到该电话
return null;//返回空
}
}
}

@ -0,0 +1,279 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;//声明该文件所属包名
import android.net.Uri;//用来识别或者标识资源名称用的一串字符串
public class Notes {//Notes 类中定义了很多常量这些常量大多是int型和string型
public static final String AUTHORITY = "micode_notes";//定义了一个权限名称,看作为数字证书
public static final String TAG = "Notes";//设置标签表示APP的名称是Notes
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;//对三种TYPENOTE,FOLDER,SYSTEM进行变量定义
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/
public static final int ID_ROOT_FOLDER = 0;//回收站目录
public static final int ID_TEMPARAY_FOLDER = -1;//不属于文件夹的便签
public static final int ID_CALL_RECORD_FOLDER = -2;//设定背景
public static final int ID_TRASH_FOLER = -3;//回收站文件夹
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";//文件夹编号
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";//背景颜色
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";//插件的大小
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";//大号桌面插件
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";//定义文件夹的名称
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";//定义call_date的ID
public static final int TYPE_WIDGET_INVALIDE = -1;//定义查询便签和文件夹的指针
public static final int TYPE_WIDGET_2X = 0;//定义查找数据的指针
public static final int TYPE_WIDGET_4X = 1;//4*4桌面大小
public static class DataConstants {//DataContants类存放textnotes和callnotes地址
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;//定义变量NOTE用来识别text_note的存放地址
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;//DataContants类存放TextNotes和CallNotes地址
}
/**
* Uri to query all notes and folders
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");//URI常量方便进行系统查询
/**
* Uri to query data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");//URI常量方便查询数据
public interface NoteColumns {//定义了类NoteColumns的部分参数
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";//每一行的ID
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";//父节点的ID
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";//用来保存一些创建信息,比如时间
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";//提醒的日期
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";//储存 提醒时间
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet";//文件夹的名字或者便签内容
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";//note的布局ID
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";//小部件类型
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";//便签背景颜色的ID
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";//设置附件是否存在
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";//文件夹中的便签数量
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type";//设置文件的类型
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";//最后一次同步的ID
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";//本地信号是否修改
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";//移动到临时文件夹之前的父文件夹
/**
* The gtask id
* <P> Type : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";//后台任务ID
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version";// 版本代号
}
public interface DataColumns {//定义了接口类在数据库的创建、查询中需要DataColumns的所有信息主要存储便签数据的信息。
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";//定义DataColumns的部分常量
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
*/
public static final String MIME_TYPE = "mime_type";// 这一排表示的项目的MIME类型。MIME类型包含视频、图像、文本、音频、应用程序等数据。
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";//便签ID
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
// 创建日期
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
//最新的修改时间
/**
* Data's content
* <P> Type: TEXT </P>
*/
public static final String CONTENT = "content";//数据包含的内容
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA1 = "data1";//文本内容的数据结构
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA2 = "data2";//定义了文本内容的类型
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA3 = "data3";//定义常量
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA5 = "data5";//.继承DataColumns的类组织电话内容数据结构
}
public static final class TextNote implements DataColumns {//文本笔记,通过定义的接口集成了上面的属性
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/
public static final String MODE = DATA1;//模式数据为data1类型
public static final int MODE_CHECK_LIST = 1;//note中内容的类型
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";//定义内容类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";//内容项目类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");//通过uri的parse方法访问资源
}
public static final class CallNote implements DataColumns {//记录通话数据的表头
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*/
public static final String CALL_DATE = DATA1;//存放通话时间信息到DATA1中
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;//电话号码为data3类型
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";//修改CONTENT_TYPE属性即内容类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";//内容项目类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");// 访问uri并将解析结果保存于CONTENT_URI属性
}
}

@ -0,0 +1,362 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;//声明包
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;//数据库操作中保存数据信息
public class NotesDatabaseHelper extends SQLiteOpenHelper {//继承于SQLiteOpenHelper的类NotesDatabaseHelper用于实现对便签或者 文件的数据库操作,例如删除便签
private static final String DB_NAME = "note.db";//定义数据库的名称为“note.db”
private static final int DB_VERSION = 4;//数据库版本号
public interface TABLE {//将接口分成note和data
public static final String NOTE = "note";//创建便签表的数据库
public static final String DATA = "data";//数据库中需要存储的项目的名称,就类似创建一个表格的表头的内容。
}
private static final String TAG = "NotesDatabaseHelper";//存储便签编号的一个数据表格
private static NotesDatabaseHelper mInstance;//创建类NotesDatabaseHelper的对象——mInstance
private static final String CREATE_NOTE_TABLE_SQL =//文件夹增加Note后需要更改的数据的表格
"CREATE TABLE " + TABLE.NOTE + "(" +//文件夹减少Note后需要更改的数据的表格
NoteColumns.ID + " INTEGER PRIMARY KEY," +//文件夹插入Note后需要更改的数据的表格
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +//文件夹删除Note后需要更改的数据的表格
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +//应用界面颜色选择
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +// 创建时间数据
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +//文件夹中便签数据初始化为0
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +//Note中数据删除更改的数据表格。
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +//数据库中需要存储的项目的名称,就相当于创建一个表格的表头的内容
")";
private static final String CREATE_DATA_TABLE_SQL =//创建SQL的data表
"CREATE TABLE " + TABLE.DATA + "(" +//note删除数据触发
DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";//文件夹删除note触发
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =//文件夹移除note时触发垃圾回收
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";//存储便签编号的一个数据表格
//以下几个都是在创建触发器(trigger)。触发器是一些在特定的数据库事件(database-event) 发生时自动进行的数据库操作
/**
* Increase folder's note count when move note to the folder
*///Increase增加文件Decrease减少文件
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//将新的note移入该文件夹时更新该文件夹note的数量
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";// 在文件夹中移入一个Note之后需要更改的数据的表格
/**
* Decrease folder's note count when move note from folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =//notes从文件夹移除后数量减一并且进行一系列的操作
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +//在文件夹中移出一个Note之后需要更改的数据的表格
" END";
//便签从文件夹移除后,数量减一,并且进行一系列的操作进行更新
/**
* Increase folder's note count when insert new note to the folder
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =//在文件夹中新建notes后数量加1
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";//在文件夹中插入一个Note之后需要更改的数据的表格
/**
* Decrease folder's note count when delete note from the folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +//定义一个更新文件夹中便签数目的SQL语句。当有便签从该文件夹中删除时使用
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";//在文件夹中删除一个Note之后需要更改的数据的表格
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
*///构建一条SQL语句用于实现在note中输入data后进行当前状态的更新
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";//在文件夹中对一个Note导入新的数据之后需要更改的数据的表格
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
*///在data数据改变后对整个应用进行数据刷新
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";//Note数据被修改后需要更改的数据的表格
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
*///在数据被删除时,进行更新。
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";//Note数据被删除后需要更改的数据的表格
/**
* Delete datas belong to note which has been deleted
*///实现在note被删除后将该note对应的data删除的功能
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";//删除已删除的便签的数据后需要更改的数据的表格
/**
* Delete notes belong to folder which has been deleted
*///用于实现在文件夹被删除后将该文件夹中的note删除的功能
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";//删除已删除的文件夹的便签后需要更改的数据的表格
/**
* Move notes belong to folder which has been moved to trash folder
*///恢复删除的notes,并且更新一些数据
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =//将垃圾文件夹里的note还原并更新数据表格
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";//还原垃圾桶中便签后需要更改的数据的表格
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}//构造函数,传入数据库的名称和版本
public void createNoteTable(SQLiteDatabase db) {//标注出数据库的名称和版本
db.execSQL(CREATE_NOTE_TABLE_SQL);//创建表头
reCreateNoteTableTriggers(db);
createSystemFolder(db);
Log.d(TAG, "note table has been created");
}//创建表格,存储标签属性
private void reCreateNoteTableTriggers(SQLiteDatabase db) {//创建一个储存标签属性的表格
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");//创建增加文件夹的触发器
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");//创建减少文件夹的触发器
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
//在删除原来的触发器后,创建新的触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);//创建自己的数据库操作
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);//创建更新减少文件夹的触发器
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);//创建删除notes的触发器
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);//创建将回收站中的notes还原的触发器
}//execSQL通过添加sql语句可以执行sql操作
//execSQL通过添加sql语句可以执行sql操作
private void createSystemFolder(SQLiteDatabase db) {//创建几个系统文件夹
ContentValues values = new ContentValues();//向数据库中插入数据就要新建一个contentValues的对象。但只能存储基本类型数据
/**
* call record foler for call notes
*///储存呼叫记录的文件夹
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);//放入数据(NoteColumns的id,呼叫记录文件夹的ld
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);//插入ContantValues对象
/**
* root folder which is default folder
*///对默认文件夹(根文件夹)进行操作
values.clear();//对根文件夹默认文件夹进行修改首先先把values容器清空在对他添加内容最后放入数据库
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);//将数据库ID与通话记录文件夹ID形成映射
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);//将数据库中数据类型与通话记录文件夹类型形成映射
db.insert(TABLE.NOTE, null, values);
/**
* temporary folder which is used for moving note
*///移动note的临时文件夹
values.clear();// 临时文件夹的修改操作
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);//将数据库ID与通话记录文件夹ID形成映射
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*///创建垃圾文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);//将数据库ID与通话记录文件夹ID形成映射
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
public void createDataTable(SQLiteDatabase db) {//将数据库ID与通话记录文件夹ID形成映射
db.execSQL(CREATE_DATA_TABLE_SQL);//用来重新创建note对应的data的表项
reCreateDataTableTriggers(db);//重新建立数据表的触发器
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
Log.d(TAG, "data table has been created");
}
private void reCreateDataTableTriggers(SQLiteDatabase db) {//删除重建表格
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
static synchronized NotesDatabaseHelper getInstance(Context context) {//如果NotesDatabaseHelper的实例创建失败那就重新建一个重新分配内从空间
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
}
@Override
public void onCreate(SQLiteDatabase db) {//在NotesDatabaseHelper对象生命周期开始时创建Note table和Datatable
createNoteTable(db);//函数生命周期开始的时候oncreate 被调用这里对其进行重写加入notes表单和数据表单
createDataTable(db);
}//实现两个表格
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//数据库版本的更新
boolean reCreateTriggers = false;//是否重新建立note及data的表项
boolean skipV2 = false;
if (oldVersion == 1) {//代码段:如果版本是一则更新到版本二
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++;
}
if (oldVersion == 2 && !skipV2) {//判断旧版本是不是2号版本且没有跳过2号版本就更新到3号版本
upgradeToV3(db);
reCreateTriggers = true;
oldVersion++;
}
if (oldVersion == 3) {//v3-v4
upgradeToV4(db);
oldVersion++;
}
if (reCreateTriggers) {//重新创建的同时创建新的note table和datatable
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
if (oldVersion != newVersion) {//旧版本与最新版本不一致,抛出异常
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
}
}
private void upgradeToV2(SQLiteDatabase db) {//将数据库的版本更新到V2
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db);
createDataTable(db);
}
private void upgradeToV3(SQLiteDatabase db) {//gengxinv3
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder在数据库的便签note表单中加上一个默认的垃圾文件夹不用用户自己创建
ContentValues values = new ContentValues();//添加垃圾系统文件夹
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);//插入到表中
}
private void upgradeToV4(SQLiteDatabase db) {//数据库版本升级到V4
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
}

@ -0,0 +1,305 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;//标注该文件所属的软件包
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;// SearchManager 的作用是提供对系统搜索服务的访问
public class NotesProvider extends ContentProvider {//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据
private static final UriMatcher mMatcher;//UriMatcher是Android提供的用来操作Uri的工具类
private NotesDatabaseHelper mHelper;//数据库辅助类的实例化
private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
static {//初始化mMatcher UriMatcher类
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);//创建UriMatcher时调用UriMatcher。UriMatcher.NO_MATCH表示不匹配任何路径
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);//SUGGEST_URI_PATH_QUERY 并不属于URI的一部分而应是用于指向此路径的常量。
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
}//注册完需要匹配的Uri后就可以使用sMatcher.match(uri)方法对输入的Uri进行匹配
/**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","//声明 NOTES_SEARCH_PROJECTION
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","//设置表明额外数据、推荐显示的文本、图标、操作、数据
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","//TEXT_1是将该字段作为安卓搜索框中建议显示的文本。如果每个建议想显示两行数据还有SearchManager.SUGGEST_COLUMN_TEXT_2
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION//构造数据库查询语句用于通过notes的片段查询notes
+ " FROM " + TABLE.NOTE//在特定表中某一字段检索特定子串
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override
public boolean onCreate() {//创建一个便签数据库助手helper
mHelper = NotesDatabaseHelper.getInstance(getContext());//对mHelper进行实例化
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,//在数据库中查询uri然后返回uri的位置
String sortOrder) {
Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
switch (mMatcher.match(uri)) {
case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM://查询便签条目
id = uri.getPathSegments().get(1);//获取uri中1号描述符
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA://根据日期进行查询
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM://查询id对应的具体数据
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH://匹配到搜索
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");//在查询时不能指定排序参数sortOrder、查询条件selection、占位符(selectionArgs)、要查询的表projection
}
String searchString = null;//搜索所得的内容
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {//利用URI的getQueryParameter方法可以获取字符串参数
searchString = uri.getQueryParameter("pattern");
}
if (TextUtils.isEmpty(searchString)) {//格式化搜索的字符串
return null;
}
try {//非法状态异常
searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default://如果以上多个case均不命中则抛出未知uri的异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (c != null) {//若getContentResolver发生变化就接收通知
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {//插入一个uriuri是一个用于标识某一互联网资源名称的字符串
SQLiteDatabase db = mHelper.getWritableDatabase();//获得可写的数据库
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {//数据库的插入,用来存放数据
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA://如果是数据类型且其id能对应于某个便签id则插入
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {//错误的数据格式没有note的id
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);//未知uri异常
}
// Notify the note uri
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);//把noteId加到URI的尾部连接成新的URI
}
// Notify the data uri
if (dataId > 0) {//更新data
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);//返回插入的uri的路径
}
return ContentUris.withAppendedId(uri, insertedId);//返回插入的uri的路径
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {//从数据库中删除uri
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE://查找到不同类型的相应的uri后在数据库中删除
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM://如果是便签条目获取对应id且对应id非系统文件夹则删除
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
long noteId = Long.valueOf(id);//.语句将string类型转换为long类型
if (noteId <= 0) {
break;
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);//删除数据
deleteData = true;
break;
case URI_DATA_ITEM://删除uri标识的指定数据
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default://匹配失败,则报错
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {//对上述的操作进行判断上述更改发生count>0
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);//对所有修改进行通知
}
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {//数据库更新uri
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);//升级note版本
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id//对notes item uri进行更新
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA://对多个数据进行修改
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);//获取该项目id并将其uri更新
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
updateData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {//代码段:通知观察者,数据更新
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
//将字符串解析成规定格式
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
if (id > 0 || !TextUtils.isEmpty(selection)) {//操作条件selection不为空或者ID>0增加WHERE语句
sql.append(" WHERE ");
}
if (id > 0) {//如果id为正更新id
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
if (!TextUtils.isEmpty(selection)) {//输入的文本非空的条件下输入到数据库中
String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);//用args替换掉的占位符
}
sql.append(selectString);//增加selectString语句
}
mHelper.getWritableDatabase().execSQL(sql.toString());//execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;//初始化,返回一个空指针
}
}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//动作失败异常
//小米便签运行过程中的运行异常处理
package net.micode.notes.gtask.exception;
public class ActionFailureException extends RuntimeException {//用来验证版本一致性,如果不一致会导致反序列化的时候版本不一致的异常。
private static final long serialVersionUID = 4425249765923293627L;
// 函数:交给父类的构造函数(包括下面的两个构造函数)
public ActionFailureException() {
super();
}//super是指向父类的一个指针与其相对的还有this指向当前类。
//调用父类具有相同形参paramString的构造方法
public ActionFailureException(String paramString) {
super(paramString);
}
//函数:第三种形式的构造函数
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}

@ -0,0 +1,127 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {/*GTask
private void showNotification(int tickerId, String content) */
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
//初始化异步功能
public interface OnCompleteListener {
void onComplete();
}
private Context mContext;//文本内容
private NotificationManager mNotifiManager;//对象: 通知管理器类的实例化
private GTaskManager mTaskManager;//实例化任务管理器
private OnCompleteListener mOnCompleteListener;
public GTaskASyncTask(Context context, OnCompleteListener listener) {//函数: GTaskASyncTask类的构造函数
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
mTaskManager = GTaskManager.getInstance();
}
public void cancelSync() {//取消同步
mTaskManager.cancelSync();
}
public void publishProgess(String message) {//显示消息
publishProgress(new String[] {
message
});
}
private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
} else {//点击清除按钮或点击通知后会自动消失
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
}
//若同步成功就从系统取得一个来启动一个NotesListActivity的对象
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))//设置最新事件信息
.setContentText(content)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification=builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//执行后台操作
}
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this);//显示进度的更新
}
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
@Override
protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) {//设置任务,比如在用户界面显示一个进度条
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
}
if (mOnCompleteListener != null) {//若监听器为空,则创建新进程
new Thread(new Runnable() {
public void run() {//执行完后调用然后返回主线程中
mOnCompleteListener.onComplete();
}
}).start();
}
}
}

@ -0,0 +1,585 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.ui.NotesPreferenceActivity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class GTaskClient {//GTaskClient类实现GTask的登录以及创建GTask任务和任务列表从网络上获取任务内容
private static final String TAG = GTaskClient.class.getSimpleName();//Google邮箱指定URL
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";//传递URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
private static GTaskClient mInstance = null;//后续使用的参数以及变量
private DefaultHttpClient mHttpClient;
private String mGetUrl;
//构造函数:初始化各属性
private String mPostUrl;
private long mClientVersion;
private boolean mLoggedin;
private long mLastLoginTime;
private int mActionId;
private Account mAccount;
private JSONArray mUpdateArray;
private GTaskClient() {//初始化客户端如果没有就new一个否则就用当前的。
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
mClientVersion = -1;
mLoggedin = false;
mLastLoginTime = 0;
mActionId = 1;
mAccount = null;
mUpdateArray = null;
}
public static synchronized GTaskClient getInstance() {//获取实例如果当前没有示例则新建一个登陆的gtask如果有直接返回
if (mInstance == null) {
mInstance = new GTaskClient();
}
return mInstance;
}
public boolean login(Activity activity) {//login用于实现登录的方法以activity作为参数
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch
if (mLoggedin//在登陆成功的情况下检测到用户名和密码不匹配时登录失败
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false;
}
if (mLoggedin) {//代码块,如果登录的时候符合上面的要求则让其显示已登录登陆
Log.d(TAG, "already logged in");
return true;
}
mLastLoginTime = System.currentTimeMillis();
String authToken = loginGoogleAccount(activity, false);
if (authToken == null) {//登录失败的情况
Log.e(TAG, "login google account failed");
return false;
}
// login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()//使用用户域名进行登录
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1;//返回@第一次出现的位置并把位置+1后记录在index里
String suffix = mAccount.name.substring(index);
url.append(suffix + "/");
mGetUrl = url.toString() + "ig";
mPostUrl = url.toString() + "r/ig";
if (tryToLoginGtask(activity, authToken)) {//成功登入
mLoggedin = true;
}
}
// try to login with google official url
if (!mLoggedin) {//代码块: 若前面的尝试失败,则尝试使用官方的域名登陆
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
if (!tryToLoginGtask(activity, authToken)) {//第二次登录失败返回false
return false;
}
}
mLoggedin = true;
return true;
}
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {//登录谷歌账号的主函数,在登陆成功后获取认证令牌
String authToken;
AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google");
if (accounts.length == 0) {//如果没有这样的账号输出日志信息“无有效的google账户”
Log.e(TAG, "there is no available google account");
return null;
}
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null;
for (Account a : accounts) {//找到后,为属性赋值
if (a.name.equals(accountName)) {
account = a;
break;
}
}
if (account != null) {//判断设置里有无该账号
mAccount = account;
} else {
Log.e(TAG, "unable to get an account with the same name in the settings");
return null;
}
// get the token now
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
if (invalidateToken) {//如果是非法的令牌,那么废除这个账号,取消登录状态
accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false);
}
} catch (Exception e) {
Log.e(TAG, "get auth token failed");
authToken = null;
}
return authToken;
}
private boolean tryToLoginGtask(Activity activity, String authToken) {//方法用于判断令牌对于登陆gtask账号是否有效
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
// token and try again
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
if (!loginGtask(authToken)) {//代码块: 重新获取的令牌再次失效
Log.e(TAG, "login gtask failed");
return false;
}
}
return true;
}
private boolean loginGtask(String authToken) {//.loginGtask实现登录Gtask的方法
int timeoutConnection = 10000;
int timeoutSocket = 15000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
try {//登录Gtask
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the cookie now
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
if (cookie.getName().contains("GTL")) {//验证cookie信息这里通过GTL标志来验证
hasAuthCookie = true;
}
}
if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie");
}
// get the client version
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
}
JSONObject js = new JSONObject(jsString);
mClientVersion = js.getLong("v");//验证cookie信息这里通过GTL标志来验证
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
return true;
}
private int getActionId() {
return mActionId++;
}//获取动作的id号码
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("AT", "1");
return httpPost;
}
private String getResponseContent(HttpEntity entity) throws IOException {//getResponseContent获取服务器响应的数据主要通过方法getContentEncoding来获取网上资源返回这些资源
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding);
}
InputStream input = entity.getContent();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater);
}
try {//完成将字节流数据内容进行存储的功能
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while (true) {
String buff = br.readLine();
if (buff == null) {
return sb.toString();
}
sb = sb.append(buff);
}
} finally {
input.close();
}
}
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {//获取客户端资源的函数
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
HttpPost httpPost = createHttpPost();
try {//.实例化一个对象,用于与服务器交互和发送请求
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// execute the post
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("error occurs when posting request");
}
}
public void createTask(Task task) throws NetworkFailureException {//创建单个任务通过json获取TASK中的内容并创建对应的jsPost通过postRequest方法获取任务的返回信息使用setGid方法设置task的new_id
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {//对异常情况的处理
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed");
}
}
public void createTaskList(TaskList tasklist) throws NetworkFailureException {//创建一个任务列表
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {//创建失败
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed");
}
}
public void commitUpdate() throws NetworkFailureException {//更新时出现异常
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
// action_list
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed");
}
}
}
public void addUpdateNode(Node node) throws NetworkFailureException {//添加更新节点主要利用commitUpdate
if (node != null) {
// too many update items may result in an error
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
if (mUpdateArray == null)
mUpdateArray = new JSONArray();
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
public void moveTask(Task task, TaskList preParent, TaskList curParent)//移动一个任务通过getGid获取task所属的Id还是通过JSONObject和postRequest实现
throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {//只有当移动是发生在任务列表中且不是第一个时设置优先级
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) {//当移动发生在不同的任务列表之间设置为dest_list
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed");
}
}
public void deleteNode(Node node) throws NetworkFailureException {//删除节点,过程类似移动
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed");
}
}
public JSONArray getTaskLists() throws NetworkFailureException {//获取任务列表首先通过getURI在网上获取数据在截取所需部分内容返回
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
try {
HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the task list
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {//带参数的获取指定的任务列表
jsString = resString.substring(begin + jsBegin.length(), end);
}
JSONObject js = new JSONObject(jsString);
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed");
}
}
public JSONArray getTaskList(String listGid) throws NetworkFailureException {//方法对于已经获取的任务列表可以通过其id来获取到
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list 通过action.pu()t对JSONObject对象action添加元素通过jsPost.put()对jsPost添加相关元素然后通过postRequest()提交更新后的请求并返回一个JSONObject的对象最后使用jsResponse.getJSONArray( )获取jsResponse中的JSONArray值并作为函数返回值
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) {//处理异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed");
}
}
public Account getSyncAccount() {
return mAccount;
}//获得同步账户
public void resetUpdateArray() {
mUpdateArray = null;
}//重置更新内容
}

@ -0,0 +1,800 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.data.MetaData;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.SqlNote;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class GTaskManager {//GTask管理类封装了对GTask进行管理的一些方法
private static final String TAG = GTaskManager.class.getSimpleName();
public static final int STATE_SUCCESS = 0;//成功
public static final int STATE_NETWORK_ERROR = 1;//网络错误
public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4;
private static GTaskManager mInstance = null;//private 定义一系列不可被外部的类访问的量
private Activity mActivity;
private Context mContext;//构造函数
private ContentResolver mContentResolver;
private boolean mSyncing;
private boolean mCancelled;
private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid;
private GTaskManager() {//类的构造函数,对其内部变量进行初始化
mSyncing = false;//正在同步标识false代表未同步
mCancelled = false;
mGTaskListHashMap = new HashMap<String, TaskList>();
mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>();
mMetaList = null;
mLocalDeleteIdMap = new HashSet<Long>();
mGidToNid = new HashMap<String, Long>();
mNidToGid = new HashMap<Long, String>();
}
public static synchronized GTaskManager getInstance() {//synchronized指明该函数可以运行在多线程下
if (mInstance == null) {
mInstance = new GTaskManager();
}
return mInstance;
}
public synchronized void setActivityContext(Activity activity) {//对类的当前实例进行加锁防止其他线程同时访问该类的该实例的所有synchronized块
// used for getting authtoken
mActivity = activity;
}
public int sync(Context context, GTaskASyncTask asyncTask) {//实现本地和远程同步的操作
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
mContext = context;
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
try {//异常处理程序
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// login google task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}//登录 google 任务失败
}
// get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();//调用下面自定义的方法初始化GTaskList
// do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();//同步便签内容
} catch (NetworkFailureException e) {
Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) {
Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR;
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {//结束后清空环境
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
mSyncing = false;
}
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;//若在同步时操作未取消,则说明同步成功,否则返回同步操作取消
}
private void initGTaskList() throws NetworkFailureException {//初始化GTask列表将google上的JSONTaskList转为本地任务列表
if (mCancelled)
return;
GTaskClient client = GTaskClient.getInstance();
try {//客户端获取任务列表
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name//如果 name 等于 字符串 "[MIUI_Notes]" + "METADATA"执行if语句块
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// load meta data
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
MetaData metaData = new MetaData();
metaData.setContentByRemoteJSON(object);
if (metaData.isWorthSaving()) {
mMetaList.addChildTask(metaData);
if (metaData.getGid() != null) {
mMetaHashMap.put(metaData.getRelatedGid(), metaData);//把元数据放到哈希表中
}
}
}
}
}
// create meta list if not existed
if (mMetaList == null) {//若元数据列表不存在则创建一个
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
}
// init task list
for (int i = 0; i < jsTaskLists.length(); i++) {//以下循环用于初始化任务列表
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();//创建一个新的任务列表
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// load tasks
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {//任务id号
object = (JSONObject) jsTasks.getJSONObject(j);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task();
task.setContentByRemoteJSON(object);
if (task.isWorthSaving()) {//判断该任务有无价值保存
task.setMetaInfo(mMetaHashMap.get(gid));
tasklist.addChildTask(task);
mGTaskHashMap.put(gid, task);
}
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed");
}
}
private void syncContent() throws NetworkFailureException {//实现内容同步
int syncType;
Cursor c = null;
String gid;
Node node;
mLocalDeleteIdMap.clear();
if (mCancelled) {//对于本地已删除的便签采取的动作
return;
}
// for local deleted note
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, null);
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
}
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
}
} else {
Log.w(TAG, "failed to query trash folder");
}
} finally {//最后把c关闭并重置
if (c != null) {
c.close();
c = null;
}
}
// sync folder first
syncFolder();
// for note existing in database
try {//对于数据库中已经存在的便签,采取以下操作
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
doContentSync(syncType, node, c);
}
} else {
Log.w(TAG, "failed to query existing note in database");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// go through remaining items//访问保留的项目
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
if (!mCancelled) {//终止标识有可能被其他进程改变,因此需要一个个进行检查
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// refresh local sync id
if (!mCancelled) {//更新同步表
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
}
}
private void syncFolder() throws NetworkFailureException {//初始化文件夹。放在第一种情况之后是因为第一种情况不需要初始化文件夹
Cursor c = null;
String gid;
Node node;
int syncType;
if (mCancelled) {
return;
}
// for root folder
try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
if (c != null) {
c.moveToNext();
gid = c.getString(SqlNote.GTASK_ID_COLUMN);//获取指针指向内容对应的gid
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
} else {
Log.w(TAG, "failed to query root folder");//出现异常时,在日志中写回出错信息
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// for call-note folder
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
if (c != null) {
if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
if (!node.getName().equals(//若当前访问的文件夹是系统文件夹则只需要更新
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
}
} else {
Log.w(TAG, "failed to query call note folder");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// for local existing folders
try {//对于本地已存在的文件的操作
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {//使指针遍历所有的文件夹
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
doContentSync(syncType, node, c);
}
} else {//进行同步操作
Log.w(TAG, "failed to query existing folder");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// for remote add folders
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {//使用迭代器对远程增添的内容进行遍历
Map.Entry<String, TaskList> entry = iter.next();
gid = entry.getKey();
node = entry.getValue();
if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
}
if (!mCancelled)
GTaskClient.getInstance().commitUpdate();
}
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {//内容同步,同步同步类型、节点以及数据库指针
if (mCancelled) {
return;
}
MetaData meta;
switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL:
addLocalNode(node);
break;
case Node.SYNC_ACTION_ADD_REMOTE:
addRemoteNode(node, c);
break;
case Node.SYNC_ACTION_DEL_LOCAL:
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
}
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
break;
case Node.SYNC_ACTION_DEL_REMOTE:
meta = mMetaHashMap.get(node.getGid());
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
}
GTaskClient.getInstance().deleteNode(node);
break;
case Node.SYNC_ACTION_UPDATE_LOCAL:
updateLocalNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_REMOTE:
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
break;
case Node.SYNC_ACTION_ERROR:
default:
throw new ActionFailureException("unkown sync action type");
}//抛出异常
}
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
if (node instanceof TaskList) {
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
} else if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else {
sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else {//代码块:若待增添节点不是任务列表中的节点,进一步操作
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
try {
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
note.remove(NoteColumns.ID);
}
}
}
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {//以下为判断便签中的数据条目
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
data.remove(DataColumns.ID);
}
}
}
}
} catch (JSONException e) {//出现异常时,打印异常信息
Log.w(TAG, e.toString());
e.printStackTrace();
}
sqlNote.setContent(js);
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node");
}
sqlNote.setParentId(parentId.longValue());
}
// create the local node
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
}
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {//更新本地节点,两个传入参数,一个是待更新的节点,一个是指向待增加位置的指针
if (mCancelled) {
return;
}
SqlNote sqlNote;
// update the note locally
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// update meta info
updateRemoteMeta(node.getGid(), sqlNote);
}
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {//添加远程节点
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// update remotely
if (sqlNote.isNoteType()) {
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task");
}
mGTaskListHashMap.get(parentGid).addChildTask(task);
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// add meta
updateRemoteMeta(task.getGid(), sqlNote);
} else {
TaskList tasklist = null;
// we need to skip folder if it has already existed//当文件夹存在则跳过,若不存在则创建新的文件夹
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
else
folderName += sqlNote.getSnippet();
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
String gid = entry.getKey();
TaskList list = entry.getValue();
if (list.getName().equals(folderName)) {
tasklist = list;
if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid);
}
break;
}
}
// no match we can add now
if (tasklist == null) {//直接新建一个任务链
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().createTaskList(tasklist);
mGTaskListHashMap.put(tasklist.getGid(), tasklist);
}
n = (Node) tasklist;
}
// update local note
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {//更新远程结点参数node是要更新的结点c是数据库的指针
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
if (sqlNote.isNoteType()) {//判断节点类型是否符合要求
Task task = (Task) node;
TaskList preParentList = task.getParent();
String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot update remote task");
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
if (preParentList != curParentList) {
preParentList.removeChildTask(task);
curParentList.addChildTask(task);
GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
}
}
// clear local modified flag
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {//更新远程结点的数据与上一个函数不同的是这里只更新数据因此只用将metadata复制上去即可。参数gid是要更新的数据对应的在数据库中的结点idsqlnote是用于获得数据内容
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) {
metaData.setMeta(gid, sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(metaData);
} else {
metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData);
mMetaHashMap.put(gid, metaData);
GTaskClient.getInstance().createTask(metaData);
}
}
}
private void refreshLocalSyncId() throws NetworkFailureException {//刷新本地便签id从远程同步
if (mCancelled) {
return;
}
// get the latest gtask list
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
initGTaskList();
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,//进行批量更改选择参数为NULL应该可以用insert替换参数分别为表名和需要更新的value对象。
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
Log.e(TAG, "something is missed");
throw new ActionFailureException(
"some local items don't have gid after sync");
}
}
} else {
Log.w(TAG, "failed to query local note to refresh sync id");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
}
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}//获取同步账号
public void cancelSync() {
mCancelled = true;
}//取消同步置mCancelled为true
}//若需要取消同步则将mCancelled值设置为真

@ -0,0 +1,128 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
public class GTaskSyncService extends Service {//service通常用作在后台处理耗时的逻辑不用与用户进行交互即使应用被销毁依然可以继续工作。
public final static String ACTION_STRING_NAME = "sync_action_type";//定义一系列静态变量
public final static int ACTION_START_SYNC = 0;//开始同步
public final static int ACTION_CANCEL_SYNC = 1;
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_IS_SYNCING = "isSyncing";
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";//进程消息
private static GTaskASyncTask mSyncTask = null;
private static String mSyncProgress = "";
private void startSync() {//开始同步
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() {//实现了在GTaskASyncTask类中定义的接口onComplete( )
mSyncTask = null;
sendBroadcast("");
stopSelf();
}
});
sendBroadcast("");
mSyncTask.execute();
}
}
private void cancelSync() {//取消同步
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
@Override
public void onCreate() {
mSyncTask = null;
}//初始化一个service
@Override
public int onStartCommand(Intent intent, int flags, int startId) {//充当重启便签指令
Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC:
startSync();
break;
case ACTION_CANCEL_SYNC:// 两种情况,开始同步或者取消同步
cancelSync();
break;
default:
break;
}
return START_STICKY;
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onLowMemory() {//发送广播
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
public IBinder onBind(Intent intent) {
return null;
}//service服务中的绑定操作
public void sendBroadcast(String msg) {//发送广播内容
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
sendBroadcast(intent);
}
public static void startSync(Activity activity) {//启动同步
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent);
}
public static void cancelSync(Context context) {//取消同步
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
public static boolean isSyncing() {
return mSyncTask != null;
}//判断当前是否处于同步状态
public static String getProgressString() {
return mSyncProgress;
}//返回当前同步状态
}

@ -0,0 +1,82 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;//包名继承于Task主要用于记录数据的变化。
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class MetaData extends Task {//创建一个继承 Task 的类MataData
private final static String TAG = MetaData.class.getSimpleName();//调用getSimpleName ()函数,得到类的简写名称存入字符串TAG中
private String mRelatedGid = null;//创建私有变量mRelatedGid并初始化为null
public void setMeta(String gid, JSONObject metaInfo) {//调用JSONObject库函数put ()Task类中的setNotes ()和setName ()函数,设置数据,即生成元数据库
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {//捕捉异常
Log.e(TAG, "failed to put related gid");
}
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);//设置gtask的名字
}
public String getRelatedGid() {
return mRelatedGid;
}//获取相关联的Gid
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}//判断是否值得存放,即当前数据是否有效,若数据非空则返回真值
@Override
public void setContentByRemoteJSON(JSONObject js) {//使用远程json数据对象设置元数据内容
super.setContentByRemoteJSON(js);
if (getNotes() != null) {//如果数据非空获取jsono metainfo和相关gid
try {
JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {//catch中的代码是进行异常处理的
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}
}
}
@Override
public void setContentByLocalJSON(JSONObject js) {//使用本地json数据对象设置元数据内容一般不会用到若用到则抛出异常
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
@Override
public JSONObject getLocalJSONFromContent() {//从元数据内容中获取本地json对象抛出异常
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");//非法参数异常
}
}

@ -0,0 +1,33 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*///小米便签运行过程中的网络异常处理
package net.micode.notes.gtask.exception;//小米便签网络异常处理包,该源文件里定义的所有类都属于这个包
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
//serialVersionUID相当于java类的身份证。主要用于版本控制。
public NetworkFailureException() {
super();
}
public NetworkFailureException(String paramString) {
super(paramString);
}//调用父类具有相同形参paramString的构造方法
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);// 调用父类具有相同形参paramString和paramThrowable的构造方法
}
}

@ -0,0 +1,101 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import org.json.JSONObject;
public abstract class Node {//同步操作的基础数据类型,定义了相关指示同步操作的常量
public static final int SYNC_ACTION_NONE = 0;//定义了各种用于表征同步状态的常量,需要操作标识
public static final int SYNC_ACTION_ADD_REMOTE = 1;//需要在远程云端增加内容
public static final int SYNC_ACTION_ADD_LOCAL = 2;//需要在本地增加内容
public static final int SYNC_ACTION_DEL_REMOTE = 3;
public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;
private String mGid;//记录最后一次修改时间
private String mName;//记录是否被删除
private long mLastModified;//记录最后一次修改时间
private boolean mDeleted;
public Node() {//构造函数进行初始化界面没有名字为空最后一次修改时间为0没有修改表征是否删除。
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
}
public abstract JSONObject getCreateAction(int actionId);//获取创建信息
public abstract JSONObject getUpdateAction(int actionId);//获取需要更新活动的ID
public abstract void setContentByRemoteJSON(JSONObject js);//创建相应的对象,并且实现远端与本地的同步操作
public abstract void setContentByLocalJSON(JSONObject js);//创建相应对象进行本地操作
public abstract JSONObject getLocalJSONFromContent();//声明JSONObject对象抽象类从目录中获取本地JSON
public abstract int getSyncAction(Cursor c);//声明int抽象类获取同步行为代号
public void setGid(String gid) {
this.mGid = gid;
}
public void setName(String name) {
this.mName = name;
}//设置名字
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}//设置删除标识
public String getGid() {
return this.mGid;
}//函数返回mGid
public String getName() {
return this.mName;
}//获取名称
public long getLastModified() {
return this.mLastModified;
}//获取最近创建时间标识
public boolean getDeleted() {
return this.mDeleted;
}//获取删除标识
}

@ -0,0 +1,189 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
public class SqlData {//数据库中基本数据类:读取数据、获取数据库中数据、提交数据到数据库
private static final String TAG = SqlData.class.getSimpleName();//调用getSimpleName ()函数来得到类的简写名称存入字符串TAG中
private static final int INVALID_ID = -99999;//将得到类的简写名称存入字符串TAG中为mDataId置初始值-99999
public static final String[] PROJECTION_DATA = new String[] {//新建一个字符串数组集合了interface DataColumns中所有SF常量
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,//获得数据列idmime类型内容1类型数据3类型数据
DataColumns.DATA3
};
public static final int DATA_ID_COLUMN = 0;//以下五个变量作为sql表中5列的编号
public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver;//定义的一些私有全局变量可以与sqlNote中的变量相对应分析
private boolean mIsCreate;
private long mDataId;
private String mDataMimeType;
private String mDataContent;
private long mDataContentData1;
private String mDataContentData3;
private ContentValues mDiffDataValues;
public SqlData(Context context) {//第一种SQLData的构造方式只从上下文获取初始化其中的变量
mContentResolver = context.getContentResolver();
mIsCreate = true;
mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE;
mDataContent = "";
mDataContentData1 = 0;
mDataContentData3 = "";//数据类型
mDiffDataValues = new ContentValues();//创建内容
}
public SqlData(Context context, Cursor c) {//构造函数,初始化数据,参数类型分别为 Context 和 Cursor
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDiffDataValues = new ContentValues();
}
private void loadFromCursor(Cursor c) {//构造函数,初始化数据,参数类型分别为 Context 和 Cursor
mDataId = c.getLong(DATA_ID_COLUMN);//调用cursor类的方法获取数据id参数为id长度
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
mDataContent = c.getString(DATA_CONTENT_COLUMN);
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
public void setContent(JSONObject js) throws JSONException {//设置共享数据并且抛出JSON类型的异常与处理机制
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;//设置数据 id如果传入的 JSONObject 对象中存在DataColumns.ID则获取并设置否则设为INVALID_ID
if (mIsCreate || mDataId != dataId) {//如果是根据目录创建的或者当前数据的ID与元数据的ID不符那么发送更新此ID 的请求
mDiffDataValues.put(DataColumns.ID, dataId);
}
mDataId = dataId;//与共享数据库同步后共享数据ID就等于数据ID
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)//若json中有MIME_TYPE这一项则将其获取否则将其定义为notes类中定义的文本类型
: DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {//如果共享数据文本类型与数据文本类型不同,则将原有的数据类型,放入共享库中
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
}
mDataMimeType = dataMimeType;
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) {//对比DataContent并更新contentValue中的DataContent
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}
mDataContent = dataContent;//共享数据同步后,共享数据内容等于该数据内容
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;// 如果传入的JSONObject对象有DataColumn.DATA1一项那么将其获取否则。将其设置为0。
if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
}
mDataContentData1 = dataContentData1;
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
}
mDataContentData3 = dataContentData3;
}
//获取共享数据内容及提供异常抛出与处理机制
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");//判断是否创建数据表
return null;
}
JSONObject js = new JSONObject();//将相关数据放入新创建的JSONObject对象并返回
js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType);
js.put(DataColumns.CONTENT, mDataContent);
js.put(DataColumns.DATA1, mDataContentData1);
js.put(DataColumns.DATA3, mDataContentData3);
return js;
}
//将当前数据提交到数据库
public void commit(long noteId, boolean validateVersion, long version) {//commit 函数用于把当前所做的修改保存到数据库
if (mIsCreate) {//判断是否是第一种SqlData构造方式
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {//如果该id是无效id且在共享数据中不存在该数据id对应的键则从共享数据中移除
mDiffDataValues.remove(DataColumns.ID);//删除数据
}
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);//加入的ID有效也就是操作有效则数据库加入这个note的ID这条data对应在这个note的ID下
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);//在note的资源标识下加入data数据
try {//上一句实现的是URI到Uri的转换/将路径转换为Long型附识给当前id
mDataId = Long.valueOf(uri.getPathSegments().get(1));//获取有效便签id并创建
} catch (NumberFormatException e) {//如果转换出错则日志中显示错误“获取note的ID出错”
Log.e(TAG, "Get note id error :" + e.toString());//获取note id错误e.toString()获取异常类型和异常详细消息
throw new ActionFailureException("create note failed");
}
} else {
if (mDiffDataValues.size() > 0) {//若共享数据存在则通过内容解析器更新关于新URI的共享数据
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(ContentUris.withAppendedId(//如果版本已确认则结果还记录下所在note的Id以及版本号
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {//如果版本确认了则从数据库中选取对应版本的id进行更新
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version)
});//更新不存在,可能是用户在同步时已更新
}
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
}
mDiffDataValues.clear();//回到初始化,清空,表示已经更新
mIsCreate = false;
}
public long getId() {
return mDataId;
}
}

@ -0,0 +1,505 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.tool.ResourceParser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SqlNote {//调用getSimpleName ()函数得到类的简写名称存入字符串TAG中
private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999;//将INVALID_ID 初始化为-99999
public static final String[] PROJECTION_NOTE = new String[] {//集合了interface NoteColumns中所有17个SF常量
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION
};//以下设置17个列的编号
public static final int ID_COLUMN = 0;//提醒时间
public static final int ALERTED_DATE_COLUMN = 1;//note的背景颜色
public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4;//最近修改时间
public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16;
private Context mContext;//以下定义了17个内部变量其中12个可以由content获得5个需要初始化为0或者new
private ContentResolver mContentResolver;
private boolean mIsCreate;
private long mId;//通过ArrayList记录note中的data
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
public SqlNote(Context context) {//构造函数参数只有context初始化新建的对象中的所有变量
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
mId = INVALID_ID;//无效用户
mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context);//系统默认背景
mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;//调用系统函数获得创建时间
mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
mType = Notes.TYPE_NOTE;
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mOriginParent = 0;
mVersion = 0;
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();//新建一个data的列表
}
public SqlNote(Context context, Cursor c) {//构造函数参数有context和cursor对cursor指向的对象进行初始化
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)//如果是note类型则调用下面的 loadDataContent()函数,加载数据内容
loadDataContent();
mDiffNoteValues = new ContentValues();
}
public SqlNote(Context context, long id) {//第三种构造方式采用context和id
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);//调用下面的 loadFromCursor函数通过ID从光标处加载数据
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
private void loadFromCursor(long id) {//通过id从光标处加载数据
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",//通过id获取ContentResolver中的相应内容并赋给cursor
new String[] {
String.valueOf(id)
}, null);//如果获取成功则cursor移动到下一条记录并加载该记录
if (c != null) {
c.moveToNext();
loadFromCursor(c);
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
} finally {
if (c != null)
c.close();
}
}
private void loadFromCursor(Cursor c) {//通过游标从光标处加载数据
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
mParentId = c.getLong(PARENT_ID_COLUMN);
mSnippet = c.getString(SNIPPET_COLUMN);
mType = c.getInt(TYPE_COLUMN);
mWidgetId = c.getInt(WIDGET_ID_COLUMN);
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN);
}
//获取ID对应content内容如果查询到该note的id确实有对应项即cursor有对应获取ID对应content内容
private void loadDataContent() {//通过content机制获取共享数据并加载到数据库当前游标处
Cursor c = null;
mDataList.clear();
try {//获取ID对应content内容
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,//获得该ID对应的数据内容
"(note_id=?)", new String[] {
String.valueOf(mId)
}, null);//查询到该note的id确实有对应项即cursor有对应
if (c != null) {
if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data");
return;
}
while (c.moveToNext()) {//记录数量不为0则循环直到记录不存在不断地取出记录放到DataList中
SqlData data = new SqlData(mContext, c);
mDataList.add(data);
}
} else {
Log.w(TAG, "loadDataContent: cursor = null");
}
} finally {//论如何,最后需要关闭数据库游标
if (c != null)
c.close();
}
}
public boolean setContent(JSONObject js) {//设置通过content机制共享的数据信息
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {//不能设置系统文件
Log.w(TAG, "cannot set system folder");//警告
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {//文件夹只能更新摘要和类型
// for folder we can only update the snnipet and type
String snippet = note.has(NoteColumns.SNIPPET) ? note//语句如果共享数据存在摘要则将其赋给snippet变量否则该变量为空
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;//将该摘要覆盖原摘要
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)//以下操作都和上面对snippet的操作一样一起根据共享的数据设置SqlNote内容的上述17项
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {//如果是新建的或 type 不匹配
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;//获取其提示日期
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
}
mId = id;
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note//获取数据的提醒日期
.getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
}
mAlertDate = alertDate;
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note//获取数据的背景颜色
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) {//如果只是通过上下文对note进行数据库操作或者该背景颜色与原背景颜色不相同
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
}
mBgColorId = bgColorId;
long createDate = note.has(NoteColumns.CREATED_DATE) ? note//对创建日期操作
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) {//如果只是通过上下文对note进行数据库操作或者该创建日期与原创建日期不相同
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);//将该创建日期保存在mDiffNoteValue这个变量中说明这两个值不相同
}
mCreatedDate = createDate;//将该创建日期覆盖原创建日期
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) {//如果只是通过上下文对note进行数据库操作或者该有无附件的布尔值与原有无附件的布尔值不相同
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
}
mHasAttachment = hasAttachment;
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note//对最近修改日期操作
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) {//如果只是通过上下文对note进行数据库操作或者该修改日期与原修改日期不相同
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
}
mModifiedDate = modifiedDate;
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
}
mParentId = parentId;
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {//如果只是通过上下文对note进行数据库操作或者该文本片段与原文本片段不相同
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)//获取数据的文件类型,
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)//对控件操作
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);//将该小部件ID保存在mDiffNoteValue这个变量中说明这两个值不相同
}
mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note// 获取数据的小部件种类
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
}
mWidgetType = widgetType;//将该小部件种类覆盖原小部件种类
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {//如果只是通过上下文对note进行数据库操作或者该原始父文件夹ID与原原始父文件夹ID不相同
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
}
mOriginParent = originParent;
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
if (data.has(DataColumns.ID)) {//该数据ID对应的数据如果存在将对应的数据存在数据库中
long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) {
if (dataId == temp.getId()) {
sqlData = temp;
}
}
}
if (sqlData == null) {
sqlData = new SqlData(mContext);
mDataList.add(sqlData);
}
sqlData.setContent(data);//最后为数据库数据进行设置
}
}
} catch (JSONException e) {//出现JSONException时日志显示错误同时打印堆栈轨迹
Log.e(TAG, e.toString());//获取异常类型和异常详细消息
e.printStackTrace();
return false;
}
return true;
}
//获取content机制提供的数据并加载到note中
public JSONObject getContent() {//获取content机制提供的数据并加载到note中
try {
JSONObject js = new JSONObject();
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
JSONObject note = new JSONObject();//新建变量note用于传输共享数据
if (mType == Notes.TYPE_NOTE) {//note类型
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId);//背景颜色ID
note.put(NoteColumns.CREATED_DATE, mCreatedDate);//创建日期
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
note.put(NoteColumns.PARENT_ID, mParentId);
note.put(NoteColumns.SNIPPET, mSnippet);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.WIDGET_ID, mWidgetId);
note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
JSONArray dataArray = new JSONArray();//获取数据库数据,并存入数组中
for (SqlData sqlData : mDataList) {//将note中的data全部存入JSONArray中
JSONObject data = sqlData.getContent();
if (data != null) {
dataArray.put(data);//再将这个JSONArray对应共享数据mata按键值对存入共享
}
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);//将元数据存入数组中
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {//类型为系统文件或目录文件时
note.put(NoteColumns.ID, mId);//将id类型以及摘要存入jsonobject,然后对应META_HEAD_NOTE键存入共享
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);//并存入元便签中
}
return js;
} catch (JSONException e) {//如果出现异常,则报错
Log.e(TAG, e.toString());
e.printStackTrace();
}
return null;
}
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
//设置当前ID的gtask的ID
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
//同步id
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}//初始化本地修改,即撤销所有当前修改
public long getId() {
return mId;
}//获得当前id
public long getParentId() {
return mParentId;
}//获得当前id的父id
public String getSnippet() {
return mSnippet;
}//获取小片段即用于显示的部分便签内容
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}//判断是否为便签类型
//将修改之后的数据上传
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);//那么就把这个ID移出便签列
}
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);//插入该便签的uri
try {
mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {//捕获异常转换出错显示错误“获取note的id出现错误”
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");//抛出异常,创建 note 失败
}
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
}
if (mType == Notes.TYPE_NOTE) {//对于note类型引用sqlData.commit方法操作
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
}
}
} else {
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {//判断是否含有这个便签
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");//尝试以无效 id 更新 note
}
if (mDiffNoteValues.size() > 0) {
mVersion ++;//更新版本:版本升级一个等级
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {//构造字符串
String.valueOf(mId)
});
} else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("//构造字符串失败
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
String.valueOf(mId), String.valueOf(mVersion)
});
}
if (result == 0) {//如果内容解析器没有更新,那么报错:没有更新,或许用户在同步时进行更新
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
if (mType == Notes.TYPE_NOTE) {//对note类型还是对其中的data引用commit从而实现目的
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
}
}
}
// refresh local info//更新本地信息
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)//如果是便签类型:
loadDataContent();//获取共享数据并加载到数据库
mDiffNoteValues.clear();//清空,回到初始化状态
mIsCreate = false;
}//改变数据库构造模式
}

@ -0,0 +1,351 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Task extends Node {//一个task类任务继承自Node类
private static final String TAG = Task.class.getSimpleName();//调用 getSimpleName ()函数来得到类的简写名称并存入字符串TAG中
private boolean mCompleted;//以下四个变量用于Task构造mCompleted判断是否完成
private String mNotes;//将在实例中存储数据的类型
private JSONObject mMetaInfo;
private Task mPriorSibling;//优先兄弟task的指针
private TaskList mParent;//任务列表的指针
public Task() {//Task类的构造函数对对象进行初始化
super();
mCompleted = false;
mNotes = null;
mPriorSibling = null;
mParent = null;
mMetaInfo = null;//对类的变量进行初始化
}
public JSONObject getCreateAction(int actionId) {//对操作号即actionId 进行一些操作的公用函数
JSONObject js = new JSONObject();
try {//共享数据存入动作类型
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));//设置索引
// entity_delta
JSONObject entity = new JSONObject();//创建实体数据并将name创建者id实体类型存入数据
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK);
if (getNotes() != null) {//如果有文本输入
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// parent_id
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
// dest_parent_type
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,//所在列表的id存入父id
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// list_id
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());//存入列表id
// prior_sibling_id
if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());//那么将其存入优先ID序列中
}
} catch (JSONException e) {//抛出异常处理机制
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject");//生成任务创建的数据传输失败
}
return js;//将这个存储字符串的变量返回
}
public JSONObject getUpdateAction(int actionId) {//接收更新action
JSONObject js = new JSONObject();
try {//同样是使用try和catch进行异常处理操作跟上面的差不多就不再赘述了
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
if (getNotes() != null) {//如果存在 notes ,则将其也放入 entity 中
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {//获取异常类型和异常详细消息
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject");//生成任务更新的数据传输失败
}
return js;
}
public void setContentByRemoteJSON(JSONObject js) {//通过云端传输的数据设置内容
if (js != null) {
try {//用try和catch进行异常处理操作
// id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {//设置最近修改
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {//设置notes
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {//设置name
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
// notes
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
}
// deleted
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
}
// completed
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));//异常处理
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject");
}
}
}
public void setContentByLocalJSON(JSONObject js) {//通过本地的json设置内容
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");//那么反馈给用户出错信息
}
try {//否则进行try和catch的异常处理操作
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {//note 类型匹配失败
Log.e(TAG, "invalid type");
return;
}
for (int i = 0; i < dataArray.length(); i++) {//遍历数据数组
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data
setName(data.getString(DataColumns.CONTENT));
break;
}
}
} catch (JSONException e) {//异常处理操作
Log.e(TAG, e.toString());
e.printStackTrace();
}
}
public JSONObject getLocalJSONFromContent() {//从content获取本地json
String name = getName();
try {
if (mMetaInfo == null) {//如果元数据的信息不存在
// new task created from web
if (name == null) {
Log.w(TAG, "the note seems to be an empty one");
return null;
}
JSONObject js = new JSONObject();//对指针进行初始化
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name);
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);//获取metainfo中的head_note
return js;
} else {
// synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);//定义一个数组并进行初始化
for (int i = 0; i < dataArray.length(); i++) {//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName());
break;
}
}
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo;
}
} catch (JSONException e) {
Log.e(TAG, e.toString());//e.toString()获取异常类型和异常详细消息
e.printStackTrace();
return null;
}
}
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
mMetaInfo = new JSONObject(metaData.getNotes());//那么进行异常处理,更新数据
} catch (JSONException e) {
Log.w(TAG, e.toString());
mMetaInfo = null;
}
}
}
public int getSyncAction(Cursor c) {//实现同步操作
try {
JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//便签元数据已被删除,不存在,返回更新云端数据的同步行为
}
if (noteInfo == null) {//云端便签 id 已被删除,不存在,返回更新本地数据的同步行为
Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE;
}
if (!noteInfo.has(NoteColumns.ID)) {//便签 id 不匹配,返回更新本地数据的同步行为
Log.w(TAG, "remote note id seems to be deleted");
return SYNC_ACTION_UPDATE_LOCAL;
}
// validate the note id now
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {//信息不匹配
Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL;
}
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {//判断有无同步
// there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
return SYNC_ACTION_NONE;
} else {//匹配失败,返回更新本地数据的同步行为
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
// validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {//判断gtask的id与获取的id是否匹配
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {//本地id与云端id一致即更新云端
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
} else {
return SYNC_ACTION_UPDATE_CONFLICT;
}
}
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return SYNC_ACTION_ERROR;
}
public boolean isWorthSaving() {//判断是否值得保存
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}//返回实例相关变量
public void setNotes(String notes) {
this.mNotes = notes;
}//设定是note成员变量
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}//设置优先兄弟 task 的优先级
public void setParent(TaskList parent) {
this.mParent = parent;
}//设置这个任务的父节点
public boolean getCompleted() {
return this.mCompleted;
}//获取 task 是否修改完毕的记录
public String getNotes() {
return this.mNotes;
}//获取成员变量 mNotes 的信息
public Task getPriorSibling() {
return this.mPriorSibling;
}//获取优先兄弟 task
public TaskList getParent() {
return this.mParent;
}//获取父节点列表
}

@ -0,0 +1,343 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class TaskList extends Node {//创建继承 Node的任务表类
private static final String TAG = TaskList.class.getSimpleName();//调用getSimpleName ()函数得到类的简称存入字符串TAG中
private int mIndex;//当前Tasklist的指针
private ArrayList<Task> mChildren;//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList
public TaskList() {//TaskList 的构造函数
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
public JSONObject getCreateAction(int actionId) {//生成并返回一个包含了一定数据的JSONObject实体
JSONObject js = new JSONObject();
try {
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);//这里放入动作的编号
// index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// entity_delta
JSONObject entity = new JSONObject();//.新建一个 JSONObject 对象,名为实体,将 namecreator identity type 三个信息存在一起
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);//将实体类型设置为“GROUP”
} catch (JSONException e) {
Log.e(TAG, e.toString());//获取异常类型和异常详细消息
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject");
}
return js;
}
public JSONObject getUpdateAction(int actionId) {//接受更新action返回jsonobject
JSONObject js = new JSONObject();
try {// 初始化 js 中的数据
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta创建一个 JSONObject 的实例化对象 entity实体
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {//代码块:处理异常信息
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject");
}
return js;
}
public void setContentByRemoteJSON(JSONObject js) {//通过云端 JSON 数据设置实例化对象 js 的内容
if (js != null) {
try {
// id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {//如果传入的对象中含有GTASK_JSON_ID说明动作的id存在于是根据内容进行设置
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {//语句块对任务的name进行设置
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject");//通过 JSONObeject 获取任务表内容失败
}
}
}
public void setContentByLocalJSON(JSONObject js) {//通过本地 JSON 数据设置对象 js 内容
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//NullPointerException这个异常出现在处理对象时对象不存在但又没有捕捉到进行处理的时候
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {//若为一般类型的文件夹
String name = folder.getString(NoteColumns.SNIPPET);//获取文件夹片段字符串作为文件夹名称
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);//设置名称MIUI系统文件夹前缀+文件夹名称
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)//若为根目录文件夹
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);//MIUI系统文件夹前缀+默认文件夹名称
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);
else
Log.e(TAG, "invalid system folder");//错误,无效的系统文件夹
} else {
Log.e(TAG, "error type");
}
} catch (JSONException e) {
Log.e(TAG, e.toString());//获取异常类型和异常详细消息
e.printStackTrace();
}
}
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
JSONObject folder = new JSONObject();//创建一个 JSONObject 的实例化对象 folder
String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length());
folder.put(NoteColumns.SNIPPET, folderName);
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
return js;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
}
}
public int getSyncAction(Cursor c) {//获取同步指令
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {//若本地记录未修改
// there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {//最近一次修改的 id 匹配成功,返回无的同步行为
// no update both side
return SYNC_ACTION_NONE;
} else {//匹配失败,返回更新本地数据的同步行为
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
// validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {//如果获取的ID不匹配返回同步动作失败
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// for folder conflicts, just apply local modification
return SYNC_ACTION_UPDATE_REMOTE;
}
}
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return SYNC_ACTION_ERROR;
}
//获取子任务数量
public int getChildTaskCount() {
return mChildren.size();
}
//在当前任务表末尾添加新的任务
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {//若添加成功,则设置优先兄弟和父节点
// need to set prior sibling and parent
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
task.setParent(this);
}
}
return ret;//返回值为是否成功添加任务
}
public boolean addChildTask(Task task, int index) {//在当前任务表的指定位置添加新的任务index是指针。
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
return false;
}
int pos = mChildren.indexOf(task);//获取要添加的任务在任务表中的位置
if (task != null && pos == -1) {
mChildren.add(index, task);
// update the task list
Task preTask = null;//更新任务表
Task afterTask = null;
if (index != 0)
preTask = mChildren.get(index - 1);
if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1);
task.setPriorSibling(preTask);//使得三个任务前后连在一块
if (afterTask != null)//下一个任务设置兄弟任务优先级
afterTask.setPriorSibling(task);
}
return true;
}
public boolean removeChildTask(Task task) {//删除TaskList中的一个Task
boolean ret = false;
int index = mChildren.indexOf(task);
if (index != -1) {
ret = mChildren.remove(task);//删除mChildren中的任务。
if (ret) {
// reset prior sibling and parent
task.setPriorSibling(null);
task.setParent(null);
// update the task list
if (index != mChildren.size()) {//代码块:删除成功后,要对任务列表进行更新
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
}
}
}
return ret;
}
public boolean moveChildTask(Task task, int index) {//以下为对子任务的移动,直接查找,获取任务索引,依据索引查找,依据坐标查找以及设定和获取索引的操作
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "move child task: invalid index");
return false;
}
int pos = mChildren.indexOf(task);//所要查找的子任务不存在,返回假值
if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list");
return false;
}
if (pos == index)
return true;
return (removeChildTask(task) && addChildTask(task, index));
}
public Task findChildTaskByGid(String gid) {//按gid寻找Task
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
if (t.getGid().equals(gid)) {
return t;
}
}
return null;
}
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}//返回指定Task的index
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
return null;
}
return mChildren.get(index);
}
public Task getChilTaskByGid(String gid) {//通过索引获取子任务
for (Task task : mChildren) {
if (task.getGid().equals(gid))
return task;
}
return null;
}
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}//获取子任务列表
public void setIndex(int index) {
this.mIndex = index;
}//设置任务索引
public int getIndex() {
return this.mIndex;
}//获取任务指针。
}

@ -0,0 +1,136 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
public abstract class NoteWidgetProvider extends AppWidgetProvider {
public static final String [] PROJECTION = new String [] {
NoteColumns.ID,//便签的ID
NoteColumns.BG_COLOR_ID,//背景颜色ID
NoteColumns.SNIPPET//摘录
};//定义了一个抽象类NoteWidgetProvider它继承了AppWidgetProvider类
public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
private static final String TAG = "NoteWidgetProvider";//定义字符串变量TAG用于在日志中标记该类的信息。
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues();//通过使用 ContentResolver.update()方法来更新 Notes.CONTENT_NOTE_URI 数据库中的笔记数据实现的。
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < appWidgetIds.length; i++) {
context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
new String[] { String.valueOf(appWidgetIds[i])});
}//更新操作使用 NoteColumns.WIDGET_ID + "=?" 作为查询条件,将笔记中 widget id 与当前 appWidgetId 匹配的记录进行更新。
}
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,//查询便签内容提供程序的Notes表查询的投影为PROJECTION
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null);//查询的条件为NoteColumns.WIDGET_ID = widgetId且NoteColumns.PARENT_ID不等于Notes.ID_TRASH_FOLER。查询结果返回一个Cursor对象。
}//一个私有方法用于获取指定widgetId的便签小部件信息。它接收两个参数上下文Context和widgetId
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false);
}//调用了另一个重载的 update 方法,并将最后一个参数设置为 false
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
int bgId = ResourceParser.getDefaultBgId(context);
String snippet = "";
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());//获取默认的背景ID和空字符串片段并创建一个Intent对象该对象指向NoteEditActivity类
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);//调用 getNoteWidgetInfo() 方法获取 widget 的信息
if (c != null && c.moveToFirst()) {
if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return;
}
snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID);
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW);
} //如果获取到了信息,就从 Cursor 对象中获取 snippet 和背景图像 ID并将这些数据设置到 Intent 对象中。
else {
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
}//如果没有获取到信息,就设置 snippet 为默认的文本内容,并将 Intent 对象的 action 设置为 ACTION_INSERT_OR_EDIT。
if (c != null) {
c.close();
}
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());//创建一个 RemoteViews 对象,并设置背景图像和文本内容
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);//根据 privacyMode 的值,为 RemoteViews 对象设置一个点击事件
/**
* Generate the pending intent to start host for the widget
*/
PendingIntent pendingIntent = null;
if (privacyMode) {
rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
}//如果 privacyMode 为 true就将文本内容设置为“正在访问模式下”并创建一个 PendingIntent 对象,指向 NotesListActivity 类
else {
rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}//如果 privacyMode 为 false就将文本内容设置为 snippet并创建一个 PendingIntent 对象,指向 NoteEditActivity 类
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);//PendingIntent 对象设置为 RemoteViews 对象的点击事件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);//使用 AppWidgetManager 对象更新 widget。
}//检查每个ID是否为INVALID_APPWIDGET_ID for 循环遍历 appWidgetIds 数组中的每个 widget并对每个 widget 进行更新。
}
}
protected abstract int getBgResourceId(int bgId);//根据给定的背景资源ID获取背景资源的资源ID
protected abstract int getLayoutId();//获取布局文件的资源ID
protected abstract int getWidgetType();//获取小部件的类型
}

@ -0,0 +1,47 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);//重写了 onUpdate() 方法,调用了父类的 update() 方法
}//继承自 NoteWidgetProvider 类
@Override
protected int getLayoutId() {
return R.layout.widget_2x;
}//重写了 getLayoutId() 方法,返回小部件布局的 ID
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}//重写了 getBgResourceId() 方法,返回小部件背景资源的 ID
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X;
}
}//重写了 getWidgetType() 方法,返回小部件的类型

@ -0,0 +1,46 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
}//调用了父类NoteWidgetProvider的update方法更新了widget
protected int getLayoutId() {
return R.layout.widget_4x;
}//返回了widget布局文件的资源id即R.layout.widget_4x
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
}//据传入的背景id获取对应的widget背景资源id具体实现在ResourceParser.WidgetBgResources类中
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X;
}
}//返回了widget类型即Notes.TYPE_WIDGET_4X

@ -0,0 +1,159 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId;//mNoteId可能是笔记的唯一标识符
private String mSnippet;//mSnippet可能是笔记的摘要或预览
private static final int SNIPPET_PREW_MAX_LEN = 60;//SNIPPET_PREW_MAX_LEN可能是规定的摘要或预览的最大长度初值为60
MediaPlayer mPlayer;//定义了一个名为mPlayer的MediaPlayer对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);//调用父类的onCreate
requestWindowFeature(Window.FEATURE_NO_TITLE);//请求窗口没有标题的特性
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);//获取当前窗口对象,并添加一个标志,以便在设备被锁定时显示该窗口
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
}//检查屏幕是否已经关闭,如果是,则设置一些标志来保持屏幕开启、打开屏幕并允许在屏幕开启时锁定屏幕,并将布局设置为插入装饰
Intent intent = getIntent();
try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);//获取传入的意图并从中获取笔记ID然后使用该ID从内容提供程序中获取笔记的摘录
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;//如果摘录超过了预定义的最大长度则将其截断并附加一些字符串该代码将截断后的摘录分配给变量mSnippet
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}//从Intent中获取传递的数据如果数据无效则抛出IllegalArgumentException异常并打印堆栈跟踪信息并返回
mPlayer = new MediaPlayer();//创建一个MediaPlayer对象
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
}//检查当前笔记是否可见于笔记数据库,如果是,则显示操作对话框并播放警报声音
else {
finish();
}//如果不是,结束当前活动
}
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);//获取 PowerManager 对象,然后调用其 isScreenOn()
return pm.isScreenOn();//调用其 isScreenOn() 方法,返回当前屏幕是否开启的值
}//判断屏幕是否开启
private void playAlarmSound() {// 获取系统当前默认的闹钟铃声的Uri
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);// 获取当前静音模式下受影响的流
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);// 如果闹钟铃声所在的流也受到了静音模式的影响,则使用受影响的流
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else { // 否则使用闹钟铃声所在的流
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try { // 设置闹钟铃声的Uri并准备播放
mPlayer.setDataSource(this, url);
mPlayer.prepare(); // 循环播放闹钟铃声
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showActionDialog() { // 创建对话框构建器
AlertDialog.Builder dialog = new AlertDialog.Builder(this); // 设置对话框标题
dialog.setTitle(R.string.app_name); // 设置对话框消息内容
dialog.setMessage(mSnippet); // 设置对话框确定按钮文本和点击事件监听器
dialog.setPositiveButton(R.string.notealert_ok, this); // 如果屏幕是开启的,则设置对话框取消按钮文本和点击事件监听器
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
} // 显示对话框,并设置对话框消失监听器
dialog.show().setOnDismissListener(this);
}
public void onClick(DialogInterface dialog, int which) {
switch (which) { // 当点击对话框的按钮时触发该方法
case DialogInterface.BUTTON_NEGATIVE:// 如果点击的是对话框的取消按钮
Intent intent = new Intent(this, NoteEditActivity.class);// 创建一个新的意图指定跳转到NoteEditActivity类
intent.setAction(Intent.ACTION_VIEW); // 设置意图的操作为ACTION_VIEW
intent.putExtra(Intent.EXTRA_UID, mNoteId);// 将笔记的ID作为额外的信息传递给NoteEditActivity类
startActivity(intent);// 启动NoteEditActivity类
break;
default: // 如果点击的不是对话框的取消按钮,则结束
break;
}
}
public void onDismiss(DialogInterface dialog) {// 当对话框消失时执行以下代码
stopAlarmSound();// 停止闹钟声音
finish(); // 结束当前Activity
}
private void stopAlarmSound() {
if (mPlayer != null) {// 如果音频播放器不为空
mPlayer.stop();// 停止播放音频
mPlayer.release();// 释放音频播放器的资源
mPlayer = null;// 将音频播放器置为空
}
}
}

@ -0,0 +1,67 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
public class AlarmInitReceiver extends BroadcastReceiver {// AlarmInitReceiver类继承自BroadcastReceiver类
private static final String [] PROJECTION = new String [] {// 定义一个字符串数组PROJECTION
NoteColumns.ID,// 第一个元素为NoteColumns.ID
NoteColumns.ALERTED_DATE// 第二个元素为NoteColumns.ALERTED_DATE
};
private static final int COLUMN_ID = 0; // 定义一个整型变量COLUMN_ID值为0
private static final int COLUMN_ALERTED_DATE = 1;// 定义一个整型变量COLUMN_ALERTED_DATE值为1
@Override
public void onReceive(Context context, Intent intent) {// 接收广播的方法
long currentDate = System.currentTimeMillis(); // 获取当前时间戳
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,// 通过内容提供器查询数据库
PROJECTION,// 查询的列
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,// 查询条件
new String[] { String.valueOf(currentDate) },// 查询参数
null); // 排序方式
if (c != null) {// 如果查询结果不为空
if (c.moveToFirst()) {// 将游标移动到第一行
do {// 循环遍历游标
long alertDate = c.getLong(COLUMN_ALERTED_DATE); // 获取提醒时间
Intent sender = new Intent(context, AlarmReceiver.class);// 创建一个新的意图
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));// 设置意图的数据
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);// 创建一个用于启动广播的PendingIntent
AlarmManager alermManager = (AlarmManager) context// 获取AlarmManager服务
.getSystemService(Context.ALARM_SERVICE);// 设置定时器
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);// 移动游标到下一行
} while (c.moveToNext());// 关闭游标
}
c.close();
}
}
}

@ -0,0 +1,30 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {// 定义一个名为AlarmReceiver的广播接收器类继承自BroadcastReceiver类
@Override
public void onReceive(Context context, Intent intent) {//重写BroadcastReceiver类的onReceive方法该方法在接收到广播时会被调用
intent.setClass(context, AlarmAlertActivity.class);// 设置Intent的目标Activity为AlarmAlertActivity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 给Intent添加FLAG_ACTIVITY_NEW_TASK标志表示启动一个新的任务栈
context.startActivity(intent);// 启动Intent所指定的Activity
}
}

@ -0,0 +1,502 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import net.micode.notes.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
public class DateTimePicker extends FrameLayout {// 定义一个名为DateTimePicker的类继承自FrameLayout类
// 定义常量
private static final boolean DEFAULT_ENABLE_STATE = true;
private static final int HOURS_IN_HALF_DAY = 12;
private static final int HOURS_IN_ALL_DAY = 24;
private static final int DAYS_IN_ALL_WEEK = 7;
private static final int DATE_SPINNER_MIN_VAL = 0;
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
// 定义控件
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
private Calendar mDate; // 定义日历对象
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; // 定义字符串数组
private boolean mIsAm; // 定义布尔型变量
private boolean mIs24HourView; // 是否为24小时制
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 控件是否可用
private boolean mInitialising; // 是否正在初始化
private OnDateTimeChangedListener mOnDateTimeChangedListener; // 定义接口
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
} // 构造函数
};
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {// 设置小时数值改变监听器
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;// 标记日期是否改变
Calendar cal = Calendar.getInstance();// 获取当前时间的日历对象
if (!mIs24HourView) { // 如果不是24小时制
// 如果从上午11点变成下午12点
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());// 设置时间为当前时间
cal.add(Calendar.DAY_OF_YEAR, 1);// 将日期加1天
isDateChanged = true; // 标记日期已改变
} // 如果从下午12点变成上午11点
else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());// 设置时间为当前时间
cal.add(Calendar.DAY_OF_YEAR, -1);// 将日期减1天
isDateChanged = true;// 标记日期已改变
}// 如果从11点到12点或从12点到11点
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;// 切换上下午标记
updateAmPmControl();// 更新上下午控件
}
} // 如果是24小时制
else {// 如果从23点到0点
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis()); // 设置时间为当前时间
cal.add(Calendar.DAY_OF_YEAR, 1);// 将日期加1天
isDateChanged = true;// 标记日期已改变
}// 如果从0点到23点
else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());// 设置时间为当前时间
cal.add(Calendar.DAY_OF_YEAR, -1);// 将日期减1天
isDateChanged = true;// 标记日期已改变
}
}
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
// 获取小时数,对半天的小时数取模,如果是下午,加上半天的小时数
// 这一行代码的作用是将 12 小时制转换为 24 小时制
// mHourSpinner 是一个 Spinner 控件,用于选择小时数
// HOURS_IN_HALF_DAY 是常量,表示半天的小时数
// mIsAm 是一个布尔值,表示当前是否是上午
mDate.set(Calendar.HOUR_OF_DAY, newHour);
// 将新的小时数设置到 Calendar 对象中
// Calendar 是一个日期时间类,用于处理日期时间相关的操作
onDateTimeChanged();// 调用 onDateTimeChanged() 方法,通知界面更新日期时间显示
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}// 如果日期有变化,更新当前年、月、日的显示
// cal 是一个 Calendar 对象,表示当前的日期时间
}
};
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { // 在值发生改变时调用的回调函数
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {// 获取分钟选择器的最小值和最大值
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;// 如果旧值等于最大值且新值等于最小值,那么时间向后偏移一小时
if (oldVal == maxValue && newVal == minValue) {
offset += 1;// 如果旧值等于最小值且新值等于最大值,那么时间向前偏移一小时
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
} // 如果偏移量不为0那么更新日期和小时选择器的值
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();// 获取当前的小时数
int newHour = getCurrentHourOfDay(); // 如果小时数大于等于12那么设置上午/下午为下午
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
updateAmPmControl();// 否则设置上午/下午为上午
} else {
mIsAm = true;
updateAmPmControl();
}
} // 设置日期的分钟数为新值
mDate.set(Calendar.MINUTE, newVal); // 调用日期时间改变的回调函数
onDateTimeChanged();
}
};
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {// 重写监听器的onValueChange方法
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm; // 反转mIsAm的布尔值
if (mIsAm) {// 如果mIsAm为true则将mDate时间减去12小时
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {// 如果mIsAm为false则将mDate时间加上12小时
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
}// 更新上午/下午控件的状态
updateAmPmControl();
onDateTimeChanged();// 调用onDateTimeChanged方法
}
};
public interface OnDateTimeChangedListener {// 定义一个OnDateTimeChangedListener接口
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}// 定义onDateTimeChanged方法传入日期时间选择器的年、月、日、时、分等参数
public DateTimePicker(Context context)// 定义一个公共的构造函数,传入上下文参数
{
this(context, System.currentTimeMillis());// 调用另一个构造函数,传入上下文和当前时间的毫秒数
}// 调用父类的构造函数传入上下文、时间毫秒数和是否为24小时制参数。这里用到了Java中的this关键字表示当前对象。
public DateTimePicker(Context context, long date) {// 定义一个公共的构造函数,传入上下文和时间毫秒数参数
this(context, date, DateFormat.is24HourFormat(context));// 调用另一个构造函数传入上下文、时间毫秒数和是否为24小时制参数
}
public DateTimePicker(Context context, long date, boolean is24HourView) {// 定义一个公共的日期选择器类继承自View类
super(context);// 调用父类的构造函数
mDate = Calendar.getInstance(); // 获取当前时间
mInitialising = true; // 设置初始化状态为true
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; // 判断当前时间是上午还是下午
inflate(context, R.layout.datetime_picker, this); // 加载布局文件
mDateSpinner = (NumberPicker) findViewById(R.id.date);// 获取日期选择器控件
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);// 设置日期选择器的最小值和最大值
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); // 设置日期选择器的值改变监听器
mHourSpinner = (NumberPicker) findViewById(R.id.hour); // 获取小时选择器控件
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); // 设置小时选择器的值改变监听器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); // 获取分钟选择器控件
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);// 设置分钟选择器的最小值
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);// 设置分钟选择器的最大值
mMinuteSpinner.setOnLongPressUpdateInterval(100);// 设置长按分钟选择器按钮的更新间隔为100毫秒
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);// 设置分钟选择器的值改变监听器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);// 获取上午/下午选择器控件
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);// 设置上午/下午选择器的最小值和最大值
mAmPmSpinner.setDisplayedValues(stringsForAmPm); // 设置上午/下午选择器的可显示值
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);// 设置上午/下午选择器的值改变监听器
// update controls to initial state
updateDateControl();// 更新日期选择器的控件状态
updateHourControl();// 更新小时选择器的控件状态
updateAmPmControl();// 更新上午/下午选择器的控件状态
set24HourView(is24HourView);//设置是否为24小时制
// set to current time
setCurrentDate(date);// 设置当前时间
setEnabled(isEnabled());// 设置是否可用
// set the content descriptions
mInitialising = false;// 设置内容描述
}
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {// 设置控件是否可用的方法
return; // 如果当前可用状态与要设置的状态一致,则直接返回,不进行任何操作
}
super.setEnabled(enabled);// 调用父类的setEnabled方法设置控件是否可用
mDateSpinner.setEnabled(enabled);// 设置日期选择器是否可用
mMinuteSpinner.setEnabled(enabled);// 设置分钟选择器是否可用
mHourSpinner.setEnabled(enabled);// 设置小时选择器是否可用
mAmPmSpinner.setEnabled(enabled);// 设置上午/下午选择器是否可用
mIsEnabled = enabled;// 更新当前可用状态
}
@Override
public boolean isEnabled() {
return mIsEnabled;
}// 判断是否启用
/**
* Get the current date in millis
*
* @return the current date in millis
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}// 获取当前时间的毫秒数
/**
* Set the current date
*
* @param date The current date in millis
*/
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();// 设置当前日期
cal.setTimeInMillis(date);// 获取日历实例
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),// 设置时间为指定毫秒数
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));// 调用设置当前日期的方法
}
/**
* Set the current date
*
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {// 设置当前日期
setCurrentYear(year);// 设置年份
setCurrentMonth(month); // 设置月份
setCurrentDay(dayOfMonth);// 设置日期
setCurrentHour(hourOfDay);// 设置小时
setCurrentMinute(minute);// 设置分钟
}
/**
* Get current year
*
* @return The current year
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}// 获取当前年份
/**
* Set current year
*
* @param year The current year
*/
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
return;
} // 如果不是初始化,并且年份与当前年份相同,则不进行任何操作
mDate.set(Calendar.YEAR, year);// 设置当前年份
updateDateControl();// 更新日期控件
onDateTimeChanged();// 触发日期时间改变事件
}
/**
* Get current month in the year
*
* @return The current month in the year
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
} // 获取当前月份
/**
* Set current month in the year
*
* @param month The month in the year
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
return;
}// 如果不是初始化,并且月份与当前月份相同,则不进行任何操作
mDate.set(Calendar.MONTH, month); // 设置当前月份
updateDateControl();// 更新日期控件
onDateTimeChanged(); // 触发日期时间改变事件
}
/**
* Get current day of the month
*
* @return The day of the month
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}// 获取当前日期
/**
* Set current day of the month
*
* @param dayOfMonth The day of the month
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
return;
} // 如果不是初始化,并且日期与当前日期相同,则不进行任何操作
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);// 设置当前日期
updateDateControl();// 更新日期控件
onDateTimeChanged(); // 触发日期时间改变事件
}
/**
* Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}// 获取当前小时数24小时制
private int getCurrentHour() {
if (mIs24HourView){ // 如果是24小时制
return getCurrentHourOfDay();// 直接返回当前小时数
} else {// 如果是12小时制
int hour = getCurrentHourOfDay();// 获取当前小时数
if (hour > HOURS_IN_HALF_DAY) {// 如果当前小时数大于12
return hour - HOURS_IN_HALF_DAY;// 返回减去12的小时数
} else {// 如果当前小时数小于等于12
return hour == 0 ? HOURS_IN_HALF_DAY : hour;// 如果当前小时数为0则返回12否则返回当前小时数
}
}
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;// 如果不是初始化并且设置的小时数与当前小时数相同,则直接返回
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);// 设置日期的小时数为设置的小时数
if (!mIs24HourView) {// 如果是12小时制
if (hourOfDay >= HOURS_IN_HALF_DAY) {// 如果设置的小时数大于等于12
mIsAm = false;// 设置为下午
if (hourOfDay > HOURS_IN_HALF_DAY) {// 如果设置的小时数大于12
hourOfDay -= HOURS_IN_HALF_DAY;// 小时数减去12
}
} else {// 如果设置的小时数小于12
mIsAm = true;// 设置为上午
if (hourOfDay == 0) {// 如果设置的小时数为0
hourOfDay = HOURS_IN_HALF_DAY;// 小时数设置为12
}
}
updateAmPmControl();// 更新上午/下午控件
}
mHourSpinner.setValue(hourOfDay);// 设置小时数的Spinner的值为设置的小时数
onDateTimeChanged();// 调用日期时间改变的回调方法
}
/**
* Get currentMinute
*
* @return The Current Minute
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}// 获取当前时间的分钟数
/**
* Set current minute
*/
public void setCurrentMinute(int minute) {// 设置当前时间的分钟数
if (!mInitialising && minute == getCurrentMinute()) {
return;
}// 如果不是初始化过程并且传入的分钟数等于当前分钟数,则直接返回
mMinuteSpinner.setValue(minute);// 设置分钟数的滚轮控件的值
mDate.set(Calendar.MINUTE, minute); // 设置时间对象的分钟数
onDateTimeChanged();// 调用日期时间改变的回调方法
}
/**
* @return true if this is in 24 hour view else false.
*/
public boolean is24HourView () {
return mIs24HourView;
}
/**
* Set whether in 24 hour or AM/PM mode.
*
* @param is24HourView True for 24 hour mode. False for AM/PM mode.
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}// 判断是否为24小时制
mIs24HourView = is24HourView;// 设置是否为24小时制
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); // 如果传入的值和当前值相等,则直接返回
int hour = getCurrentHourOfDay();// 获取当前小时数
updateHourControl();// 更新小时数的控件
setCurrentHour(hour); // 设置当前小时数
updateAmPmControl();// 更新上下午的控件
}
private void updateDateControl() {// 更新日期控件
Calendar cal = Calendar.getInstance();// 获取当前时间对象
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);//将时间对象的日期减去一周的一半再减一天,作为起始日期
mDateSpinner.setDisplayedValues(null); // 清空日期滚轮控件的显示值
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {// 循环添加一周的日期到日期滚轮控件的显示值中
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);// 设置日期滚轮控件的显示值和当前选中的值
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}
private void updateAmPmControl() {// 更新上午/下午控件的显示状态
if (mIs24HourView) {// 如果是24小时制
mAmPmSpinner.setVisibility(View.GONE);// 隐藏上午/下午控件
} else {// 如果是12小时制
int index = mIsAm ? Calendar.AM : Calendar.PM;// 获取当前时间是上午还是下午
mAmPmSpinner.setValue(index); // 设置上午/下午控件的值
mAmPmSpinner.setVisibility(View.VISIBLE);// 显示上午/下午控件
}
}
private void updateHourControl() {// 更新小时控件的显示范围
if (mIs24HourView) { // 如果是24小时制
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); // 设置小时控件的最小值为0
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);// 设置小时控件的最大值为23
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);// 设置小时控件的最小值为1
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);// 设置小时控件的最大值为12
}
}
/**
* Set the callback that indicates the 'Set' button has been pressed.
* @param callback the callback, if null will do nothing
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}// 设置日期时间变化监听器
private void onDateTimeChanged() {// 当日期时间发生变化时调用此方法
if (mOnDateTimeChangedListener != null) {// 如果日期时间变化监听器不为空
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}// 调用日期时间变化监听器的onDateTimeChanged方法传递当前日期时间的各个参数
}
}

@ -0,0 +1,90 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import java.util.Calendar;
import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {// 创建一个日期时间选择器对话框类继承自AlertDialog类并实现OnClickListener接口。
private Calendar mDate = Calendar.getInstance();// 创建一个日期时间选择器对话框类继承自AlertDialog类并实现OnClickListener接口。
private boolean mIs24HourView;// 创建一个日期时间选择器对话框类继承自AlertDialog类并实现OnClickListener接口。
private OnDateTimeSetListener mOnDateTimeSetListener;// 创建一个日期时间选择器对话框类继承自AlertDialog类并实现OnClickListener接口。
private DateTimePicker mDateTimePicker;// 创建一个日期时间选择器对话框类继承自AlertDialog类并实现OnClickListener接口。
public interface OnDateTimeSetListener {// 创建一个日期时间设置监听器接口OnDateTimeSetListener。
void OnDateTimeSet(AlertDialog dialog, long date);// 创建一个日期时间设置监听器接口OnDateTimeSetListener。
}
public DateTimePickerDialog(Context context, long date) {// 构造函数,接收一个上下文和一个日期的时间
super(context);// 构造函数,接收一个上下文和一个日期的时间
mDateTimePicker = new DateTimePicker(context);// 构造函数,接收一个上下文和一个日期的时间
setView(mDateTimePicker);// 构造函数,接收一个上下文和一个日期的时间
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {// 构造函数,接收一个上下文和一个日期的时间
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {// 当日期时间改变时,回调该方法
mDate.set(Calendar.YEAR, year);// 当日期时间改变时,回调该方法
mDate.set(Calendar.MONTH, month); // 设置日期时间的月份
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); // 设置日期时间的月份
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);// 设置日期时间的小时
mDate.set(Calendar.MINUTE, minute);// 设置日期时间的小时
updateTitle(mDate.getTimeInMillis()); // 更新对话框的标题
}
});
mDate.setTimeInMillis(date);// 设置时间为指定的时间
mDate.set(Calendar.SECOND, 0);// 将秒数设置为0防止影响时间的精确度
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());// 将时间设置到日期时间选择器中
setButton(context.getString(R.string.datetime_dialog_ok), this);// 设置确定和取消按钮的文本
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
set24HourView(DateFormat.is24HourFormat(this.getContext()));// 设置时间格式为24小时制或12小时制
updateTitle(mDate.getTimeInMillis());// 更新对话框标题,显示当前选择的时间
}
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; //将传入的值赋值给mIs24HourView变量
} //设置是否是24小时制的方法传入一个boolean值
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {//设置日期时间设置监听器的方法传入一个OnDateTimeSetListener对象
mOnDateTimeSetListener = callBack; //设置日期时间设置监听器的方法传入一个OnDateTimeSetListener对象
}
private void updateTitle(long date) {//更新对话框标题的方法传入一个日期时间的long型值
int flag =//更新对话框标题的方法传入一个日期时间的long型值
DateUtils.FORMAT_SHOW_YEAR | //显示年份
DateUtils.FORMAT_SHOW_DATE | //显示日期
DateUtils.FORMAT_SHOW_TIME; //显示时间
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;//根据mIs24HourView变量的值判断是否显示24小时制将标志位赋值给flag变量
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));//根据传入的日期时间值和标志位,格式化日期时间并设置为对话框标题
}
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());//当用户点击对话框上的“确认”按钮时如果设置了日期时间设置监听器则调用该监听器的OnDateTimeSet方法
}
}
}

@ -0,0 +1,62 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
public class DropdownMenu {
private Button mButton;// 按钮控件
private PopupMenu mPopupMenu;// 弹出菜单控件
private Menu mMenu; // 菜单控件
public DropdownMenu(Context context, Button button, int menuId) { // 构造函数,传入上下文、按钮控件和菜单 ID
mButton = button; // 初始化按钮控件
mButton.setBackgroundResource(R.drawable.dropdown_icon); // 设置按钮控件背景为下拉菜单图标
mPopupMenu = new PopupMenu(context, mButton);// 初始化弹出菜单控件,传入上下文和按钮控件
mMenu = mPopupMenu.getMenu();// 初始化弹出菜单控件,传入上下文和按钮控件
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);// 从菜单资源 ID 中填充菜单控件
mButton.setOnClickListener(new OnClickListener() {// 从菜单资源 ID 中填充菜单控件
public void onClick(View v)// 点击事件处理
{
mPopupMenu.show();// 显示弹出菜单控件
}
});
}
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
} // 设置下拉菜单项的点击监听器
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}// 查找指定id的菜单项
public void setTitle(CharSequence title) {
mButton.setText(title);
}// 设置按钮的标题文字
}

@ -0,0 +1,81 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
public class FoldersListAdapter extends CursorAdapter { // 文件夹列表适配器类继承自CursorAdapter
public static final String [] PROJECTION = {// 查询列的数组包含ID和SNIPPET两列
NoteColumns.ID,
NoteColumns.SNIPPET
};
public static final int ID_COLUMN = 0;// ID列的索引为0
public static final int NAME_COLUMN = 1;// SNIPPET列的索引为1
public FoldersListAdapter(Context context, Cursor c) {// 构造函数,接收上下文和游标作为参数
super(context, c);
// TODO Auto-generated constructor stub
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {// 创建新的视图
return new FolderListItem(context); // 返回自定义的文件夹列表项视图
}
@Override
public void bindView(View view, Context context, Cursor cursor) {// 绑定视图和数据
if (view instanceof FolderListItem) { // 判断视图类型是否为FolderListItem
// 获取文件夹名称
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);// 绑定文件夹名称到视图
((FolderListItem) view).bind(folderName);
}
}
public String getFolderName(Context context, int position) {// 获取指定位置的Cursor对象
Cursor cursor = (Cursor) getItem(position);// 获取文件夹名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
private class FolderListItem extends LinearLayout {//私有类 FolderListItem继承自 LinearLayout
private TextView mName;
public FolderListItem(Context context) {
super(context);//调用了 super(context) 来初始化父类 LinearLayout
inflate(context, R.layout.folder_list_item, this);//过 inflate 方法将布局文件 R.layout.folder_list_item 填充到当前 LinearLayout 中
mName = (TextView) findViewById(R.id.tv_folder_name);//通过 findViewById 方法获取到布局文件中的 TextView 控件 tv_folder_name并将其赋值给成员变量 mName
}
public void bind(String name) {
mName.setText(name);
}//定义了一个 bind 方法,用于将文件夹的名称绑定到 mName 控件上。在该方法中,通过 mName.setText(name) 将名称显示在 TextView 上
}
}

@ -0,0 +1,879 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.BackgroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.model.WorkingNote.NoteSettingChangedListener;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.tool.ResourceParser.TextAppearanceResources;
import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener;
import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
private class HeadViewHolder {// 内部类HeadViewHolder用于存储标题栏的控件
public TextView tvModified;// 最后修改时间的TextView
public ImageView ivAlertIcon;// 提醒图标的ImageView
public TextView tvAlertDate;// 提醒图标的ImageView
public ImageView ibSetBgColor;// 设置背景颜色的ImageView
}
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static {
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED);
sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);
sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN);
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
}
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static {// 静态代码块初始化sBgSelectorBtnsMap
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);// 将黄色按钮id和黄色颜色值放入sBgSelectorBtnsMap中
sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select);// 将红色按钮id和红色颜色值放入sBgSelectorBtnsMap中
sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); // 将蓝色按钮id和蓝色颜色值放入sBgSelectorBtnsMap中
sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);// 将绿色按钮id和绿色颜色值放入sBgSelectorBtnsMap中
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);// 将白色按钮id和白色颜色值放入sBgSelectorBtnsMap中
}
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();// 定义一个静态的、不可变的Map用于存储字体大小按钮的ID和对应的字体大小值
static {
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);// 将“大号字体”按钮的ID和字体大小值存入Map中
sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);// 将“小号字体”按钮的ID和字体大小值存入Map中
sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); // 将“中号字体”按钮的ID和字体大小值存入Map中
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);// 将“超大号字体”按钮的ID和字体大小值存入Map中
}
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();// 定义一个静态的、不可变的Map用于存储字体大小值和对应的字体选择器选中状态的ID
static {
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);// 将字体大小值为“大号字体”的选中状态ID存入Map中
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); // 将字体大小值为“小号字体”的选中状态ID存入Map中
sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);// 将字体大小值为“中号字体”的选中状态ID存入Map中
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);// 将字体大小值为“超大号字体”的选中状态ID存入Map中
}
private static final String TAG = "NoteEditActivity";// 定义常量TAG为字符串"NoteEditActivity"
// 声明变量
private HeadViewHolder mNoteHeaderHolder;// 头部视图的持有者
private View mHeadViewPanel; // 头部视图面板
private View mNoteBgColorSelector;// 笔记背景颜色选择器
private View mFontSizeSelector;// 笔记字体大小选择器
private EditText mNoteEditor;// 笔记编辑器
private View mNoteEditorPanel;// 笔记编辑器面板
private WorkingNote mWorkingNote;// 工作笔记
private SharedPreferences mSharedPrefs; // 共享偏好设置
private int mFontSizeId; // 字体大小ID
private static final String PREFERENCE_FONT_SIZE = "pref_font_size";// 字体大小偏好设置
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;// 快捷图标标题最大长度
public static final String TAG_CHECKED = String.valueOf('\u221A');// 选中标记
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); // 未选中标记
private LinearLayout mEditTextList;// 编辑文本列表
private String mUserQuery;// 用户查询
private Pattern mPattern;// 模式匹配对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);//调用父类的onCreate方法
this.setContentView(R.layout.note_edit); //设置当前Activity的布局文件为note_edit.xml
if (savedInstanceState == null && !initActivityState(getIntent())) {//如果savedInstanceState为空且initActivityState方法返回false
finish(); //结束当前Activity
return; //返回
}
initResources();//初始化资源
}
/**
* Current activity may be killed when the memory is low. Once it is killed, for another time
* user load this activity, we should restore the former state
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {//重写onRestoreInstanceState方法
super.onRestoreInstanceState(savedInstanceState); //调用父类的onRestoreInstanceState方法
if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {//如果savedInstanceState不为空且包含Intent.EXTRA_UID键
Intent intent = new Intent(Intent.ACTION_VIEW);//创建一个ACTION_VIEW的Intent对象
intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); //将Intent.EXTRA_UID键对应的值放入Intent中
if (!initActivityState(intent)) {//如果initActivityState方法返回false
finish();//结束当前Activity
return;
}
Log.d(TAG, "Restoring from killed activity"); //在Logcat中输出一条调试信息
}
}
private boolean initActivityState(Intent intent) {{ // 初始化Activity状态的方法传入一个Intent对象
/**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
* then jump to the NotesListActivity
*/
mWorkingNote = null;{ // 初始化Activity状态的方法传入一个Intent对象
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { // 如果Intent的动作是ACTION_VIEW
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); // 获取Intent中的noteId如果没有则默认为0
mUserQuery = "";// 初始化mUserQuery为空字符串
/**
* Starting from the searched result
*/
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {// 初始化mUserQuery为空字符串
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));// 获取搜索结果的noteId
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);// 获取用户查询的字符串
}
if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {// 如果noteId在Note数据库中不可见
Intent jump = new Intent(this, NotesListActivity.class); // 创建一个跳转到NotesListActivity的Intent
startActivity(jump); // 启动该Intent
showToast(R.string.error_note_not_exist); // 显示提示信息
finish(); // 结束当前Activity
return false; // 返回false
} else {// 如果noteId在Note数据库中可见
mWorkingNote = WorkingNote.load(this, noteId);// 加载指定noteId对应的WorkingNote对象
if (mWorkingNote == null) {// 如果加载失败
Log.e(TAG, "load note failed with note id" + noteId);// 记录错误信息
finish();
return false;
}
}
getWindow().setSoftInputMode( // 设置窗口的软输入模式
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN // 软输入状态为隐藏
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); // 软输入调整方式为自适应
} else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {// 如果Intent的动作是ACTION_INSERT_OR_EDIT
// New note
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);// 获取文件夹id
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);// 获取小部件id
int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE,
Notes.TYPE_WIDGET_INVALIDE); // 获取小部件类型
int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, // 获取背景资源id
ResourceParser.getDefaultBgId(this));
// Parse call-record note
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); // 获取电话号码
long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);// 获取通话记录日期
if (callDate != 0 && phoneNumber != null) {//如果通话日期和电话号码都存在
if (TextUtils.isEmpty(phoneNumber)) {//如果电话号码为空
Log.w(TAG, "The call record number is null");//输出警告信息
}
long noteId = 0; //定义笔记id变量
if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(),
phoneNumber, callDate)) > 0) {//如果能够通过电话号码和通话日期获取到笔记id
mWorkingNote = WorkingNote.load(this, noteId);//加载笔记
if (mWorkingNote == null) {//如果笔记加载失败
Log.e(TAG, "load call note failed with note id" + noteId); //输出错误信息
finish();
return false;
}
} else { //如果无法通过电话号码和通话日期获取到笔记id
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId,
widgetType, bgResId);//创建一个空的笔记
mWorkingNote.convertToCallNote(phoneNumber, callDate);//将笔记转换为通话记录类型
}
} else { //如果通话日期或电话号码不存在
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType,
bgResId); //创建一个空的笔记
}
getWindow().setSoftInputMode(//设置窗口的软键盘模式
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else { //如果意图未指定操作
Log.e(TAG, "Intent not specified action, should not support"); //输出错误信息
finish();
return false;
}
mWorkingNote.setOnSettingStatusChangedListener(this);//设置 mWorkingNote 对象的状态改变监听器为当前类this
return true;
}
@Override
protected void onResume() {
super.onResume();
initNoteScreen();
}//在onResume方法中调用initNoteScreen方法初始化笔记界面
//初始化笔记界面
private void initNoteScreen() {//设置笔记编辑器的字体样式
mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId));//如果是清单模式,则切换到列表模式
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
switchToListMode(mWorkingNote.getContent());
} else {//否则,将笔记内容显示在编辑器中,并高亮查询结果
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));//将光标移到文本末尾
mNoteEditor.setSelection(mNoteEditor.getText().length());//隐藏所有背景选择器
}
for (Integer id : sBgSelectorSelectionMap.keySet()) {
findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);
}//设置标题栏背景
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());//设置笔记编辑器背景
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());//设置笔记修改时间
mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_YEAR));
/**
* TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker
* is not ready
*/
showAlertHeader();
}
private void showAlertHeader() {// 显示警报头部信息的方法
if (mWorkingNote.hasClockAlert()) {// 如果当前笔记设置了警报
long time = System.currentTimeMillis(); // 获取当前时间
if (time > mWorkingNote.getAlertDate()) { // 如果当前时间已经超过了警报时间
mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); // 在警报时间的文本框中显示“已过期”
} else {
mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString(
mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));// 在警报时间的文本框中显示距离警报时间还有多长时间
}
mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); // 显示警报时间的文本框
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); // 显示警报图标
} else { // 如果当前笔记没有设置警报
mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);// 隐藏警报时间的文本框
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);// 隐藏警报图标
};
}
@Override
protected void onNewIntent(Intent intent) {// 当用户从其它界面返回到此界面时调用的方法
super.onNewIntent(intent); // 调用父类的方法
initActivityState(intent);// 初始化Activity的状态
}
@Override
protected void onSaveInstanceState(Bundle outState) { // 当Activity被销毁时调用的方法用于保存Activity的状态
super.onSaveInstanceState(outState);
/**
* For new note without note id, we should firstly save it to
* generate a id. If the editing note is not worth saving, there
* is no id which is equivalent to create new note
*/
if (!mWorkingNote.existInDatabase()) {// 如果工作笔记不存在于数据库中
saveNote();// 保存笔记
}
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());// 将工作笔记的ID放入保存状态中
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
}// 在日志中记录保存的工作笔记ID
// 触摸事件分发函数
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mNoteBgColorSelector, ev))// 如果笔记背景颜色选择器可见且触摸位置不在选择器内部
{
mNoteBgColorSelector.setVisibility(View.GONE);// 隐藏笔记背景颜色选择器
return true;
}
if (mFontSizeSelector.getVisibility() == View.VISIBLE// 如果字号选择器可见且触摸位置不在选择器内部
&& !inRangeOfView(mFontSizeSelector, ev)) {
mFontSizeSelector.setVisibility(View.GONE);// 隐藏字号选择器
return true;
}// 调用父类的触摸事件分发函数
return super.dispatchTouchEvent(ev);
}
// 判断触摸位置是否在视图范围内
private boolean inRangeOfView(View view, MotionEvent ev) {// 获取视图在屏幕上的位置
int []location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];// 获取视图在屏幕上的位置
if (ev.getX() < x
|| ev.getX() > (x + view.getWidth())
|| ev.getY() < y
|| ev.getY() > (y + view.getHeight())) {
return false;
}// 触摸位置在视图范围内
return true;
}
private void initResources() {// 获取笔记标题视图面板
mHeadViewPanel = findViewById(R.id.note_title);// 获取笔记标题视图面板
mNoteHeaderHolder = new HeadViewHolder();// 获取笔记标题视图面板
mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);// 获取笔记标题视图面板
mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);// 获取提醒时间文本视图
mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);// 获取设置背景颜色按钮视图
mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color);// 设置设置背景颜色按钮的点击监听器
mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);// 获取笔记编辑器视图
mNoteEditor = (EditText) findViewById(R.id.note_edit_view);// 获取笔记编辑器面板视图
mNoteEditorPanel = findViewById(R.id.sv_note_edit);// 获取笔记背景颜色选择器视图
mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);// 为所有背景选择器按钮设置点击监听器
for (int id : sBgSelectorBtnsMap.keySet()) {
ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this);
}
mFontSizeSelector = findViewById(R.id.font_size_selector);// 设置字体大小选择器控件
for (int id : sFontSizeBtnsMap.keySet()) {
View view = findViewById(id);
view.setOnClickListener(this);
};// 遍历字体大小按钮映射表,并为每个按钮设置点击事件监听器
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);// 获取默认的共享首选项对象
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);// 获取上一次使用的字体大小ID如果没有则使用默认值
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
}//ID可能大于资源长度在这种情况下
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
}// 获取笔记编辑列表布局
@Override
protected void onPause() {
super.onPause();
if(saveNote()) {
Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());
}// 如果保存笔记成功,则输出日志记录笔记内容长度
clearSettingState();// 清除设置状态
}
private void updateWidget() {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);// 创建更新小部件的意图
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
intent.setClass(this, NoteWidgetProvider_2x.class);
}// 根据当前笔记的小部件类型,设置意图的类别
else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) {
intent.setClass(this, NoteWidgetProvider_4x.class);
}
else {
Log.e(TAG, "Unspported widget type");
return;
}// 如果小部件类型不支持,则输出错误日志并返回
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
mWorkingNote.getWidgetId()
});// 将当前笔记的小部件ID添加到意图中
sendBroadcast(intent);// 发送广播更新小部件
setResult(RESULT_OK, intent);// 设置结果为“操作成功”
}
public void onClick(View v) {// 点击事件监听器
int id = v.getId();// 获取被点击的 View 的 ID
if (id == R.id.btn_set_bg_color) {// 如果被点击的是设置背景颜色的按钮
mNoteBgColorSelector.setVisibility(View.VISIBLE);// 显示背景颜色选择器
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.VISIBLE); // 显示当前背景颜色的选中状态
} else if (sBgSelectorBtnsMap.containsKey(id)) { // 如果被点击的是背景颜色选择器中的按钮
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE);// 隐藏之前选中的背景颜色的选中状态
mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); // 设置笔记的背景颜色 ID
mNoteBgColorSelector.setVisibility(View.GONE); // 隐藏背景颜色选择器
} else if (sFontSizeBtnsMap.containsKey(id)) {// 如果被点击的是字体大小选择器中的按钮
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); // 隐藏之前选中的字体大小的选中状态
mFontSizeId = sFontSizeBtnsMap.get(id);// 设置笔记的字体大小 ID
mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();// 将字体大小 ID 存储到 SharedPreferences 中
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);// 显示新选中的字体大小的选中状态
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果当前笔记处于待办事项模式
getWorkingText();//获取当前笔记的文本内容;
switchToListMode(mWorkingNote.getContent());//将当前笔记的编辑器切换为列表模式
} else {
mNoteEditor.setTextAppearance(this,
TextAppearanceResources.getTexAppearanceResource(mFontSizeId));//将当前笔记的编辑器文本外观设置为指定字体大小
}
mFontSizeSelector.setVisibility(View.GONE);//隐藏字体大小选择器
}
}
@Override
public void onBackPressed() { // 当用户按下返回键时执行该方法
if(clearSettingState()) { // 如果设置状态已经被清除,则直接返回
return;
}
saveNote(); // 保存笔记
super.onBackPressed(); // 调用父类的onBackPressed方法关闭当前Activity
}
private boolean clearSettingState() {// 清除设置状态的方法
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {// 如果笔记背景颜色选择器可见
mNoteBgColorSelector.setVisibility(View.GONE);// 如果笔记背景颜色选择器可见
return true; // 返回true表示设置状态已经被清除
} else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {// 否则如果字体大小选择器可见
mFontSizeSelector.setVisibility(View.GONE); // 隐藏字体大小选择器
return true; // 返回true表示设置状态已经被清除
}
return false; // 返回false表示设置状态未被清除
}
public void onBackgroundColorChanged() {// 当笔记背景颜色改变时执行该方法
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE); // 根据当前背景颜色id获取对应的选择器并将其设置为可见
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); // 根据当前背景颜色id获取对应的选择器并将其设置为可见
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); // 设置笔记标题栏的背景颜色为当前选择的背景颜色
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {// 当准备显示选项菜单时调用
if (isFinishing()) {// 如果Activity正在被销毁则返回true
return true;
}
clearSettingState(); // 清除设置状态(即隐藏字体大小选择器和背景颜色选择器)
menu.clear();// 清除菜单项
if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { // 如果当前笔记所在的文件夹是通话记录文件夹,则加载通话记录编辑菜单项
getMenuInflater().inflate(R.menu.call_note_edit, menu);
} else { // 否则加载笔记编辑菜单项
getMenuInflater().inflate(R.menu.note_edit, menu);
}
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { // 如果当前是清单模式,则将选项菜单中的“清单模式”改为“正常模式”
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode);
} else {// 否则将选项菜单中的“正常模式”改为“清单模式”
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode);
}
if (mWorkingNote.hasClockAlert()) { // 如果当前笔记设置了提醒,则隐藏“添加提醒”菜单项
menu.findItem(R.id.menu_alert).setVisible(false);
} else { // 否则隐藏“删除提醒”菜单项
menu.findItem(R.id.menu_delete_remind).setVisible(false);
}
return true; // 返回true表示已准备好显示选项菜单
}
@Override
public boolean onOptionsItemSelected(MenuItem item) { // 当用户点击菜单项时执行该方法
switch (item.getItemId()) {// 获取用户点击的菜单项ID
case R.id.menu_new_note:// 如果用户点击的是新建笔记菜单项
createNewNote();// 调用创建新笔记的方法
break;
case R.id.menu_delete:// 如果用户点击的是删除笔记菜单项
AlertDialog.Builder builder = new AlertDialog.Builder(this);// 创建一个对话框
builder.setTitle(getString(R.string.alert_title_delete)); // 设置对话框标题
builder.setIcon(android.R.drawable.ic_dialog_alert);// 设置对话框图标
builder.setMessage(getString(R.string.alert_message_delete_note)); // 设置对话框提示信息
builder.setPositiveButton(android.R.string.ok,// 设置对话框确认按钮的点击事件
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { // 当用户点击确认按钮时执行该方法
deleteCurrentNote(); // 调用删除笔记的方法
finish(); // 关闭当前活动
}
});
builder.setNegativeButton(android.R.string.cancel, null); // 设置对话框取消按钮的点击事件
builder.show();// 显示对话框
break;
case R.id.menu_font_size:// 如果用户点击的是字体大小菜单项
mFontSizeSelector.setVisibility(View.VISIBLE); // 显示字体大小选择器
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);// 显示当前选中的字体大小
break;
case R.id.menu_list_mode: // 如果用户点击的是清单模式菜单项
mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?// 切换清单模式
TextNote.MODE_CHECK_LIST : 0);
break;
case R.id.menu_share:// 如果用户点击的是分享菜单项
getWorkingText();// 获取当前笔记的内容
sendTo(this, mWorkingNote.getContent());// 调用分享方法,将笔记内容分享到其他应用
break;
case R.id.menu_send_to_desktop:// 如果用户点击的是发送到桌面菜单项
sendToDesktop(); // 调用发送到桌面的方法
break;
case R.id.menu_alert:// 如果用户点击的是设置提醒菜单项
setReminder();// 调用设置提醒的方法
break;
case R.id.menu_delete_remind: // 如果用户点击的是删除提醒菜单项
mWorkingNote.setAlertDate(0, false);// 将笔记的提醒日期设置为0表示删除提醒
break;
default:// 如果用户点击的是其他菜单项
break;
}
return true;// 返回true表示菜单项已经被处理
}
private void setReminder() {// 设置提醒时间
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());// 创建日期时间选择对话框
d.setOnDateTimeSetListener(new OnDateTimeSetListener() { // 设置日期时间选择监听器
public void OnDateTimeSet(AlertDialog dialog, long date) { // 在日期时间选择监听器中设置提醒时间
mWorkingNote.setAlertDate(date , true);// 设置提醒时间
}
});
d.show(); // 显示日期时间选择对话框
}
/**
* Share note to apps that support {@link Intent#ACTION_SEND} action
* and {@text/plain} type
*/
private void sendTo(Context context, String info) { // 分享笔记到其他应用
Intent intent = new Intent(Intent.ACTION_SEND); // 创建发送意图
intent.putExtra(Intent.EXTRA_TEXT, info);// 设置分享内容
intent.setType("text/plain");// 设置分享内容
context.startActivity(intent);// 启动分享应用
}
private void createNewNote() { // 创建新笔记
// Firstly, save current editing notes
saveNote();// 保存笔记
// For safety, start a new NoteEditActivity
finish();// 结束当前Activity
Intent intent = new Intent(this, NoteEditActivity.class);// 结束当前Activity
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置意图的操作为插入或编辑
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); // 设置意图的操作为插入或编辑
startActivity(intent);// 启动新笔记的Activity
}
private void deleteCurrentNote() {// 删除当前笔记
if (mWorkingNote.existInDatabase()) {// 如果当前笔记存在于数据库中
HashSet<Long> ids = new HashSet<Long>();// 初始化一个HashSet用于存储笔记的id
long id = mWorkingNote.getNoteId();// 初始化一个HashSet用于存储笔记的id
if (id != Notes.ID_ROOT_FOLDER) {// 如果id不是根文件夹的id
ids.add(id);
} else {
Log.d(TAG, "Wrong note id, should not happen");// 把id添加到HashSet中
}
if (!isSyncMode()) {// 把id添加到HashSet中
if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {// 批量删除笔记
Log.e(TAG, "Delete Note error");// 输出错误日志
}
} else {
if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {// 批量移动笔记到垃圾箱
Log.e(TAG, "Move notes to trash folder error, should not happens");// 输出错误日志
}
}
}
mWorkingNote.markDeleted(true);// 标记当前笔记已被删除
}
private boolean isSyncMode() {// 判断是否为同步模式
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
public void onClockAlertChanged(long date, boolean set) {// 监听提醒时间的变化
/**
* User could set clock to an unsaved note, so before setting the
* alert clock, we should save the note first
*/
if (!mWorkingNote.existInDatabase()) {
saveNote();
}// 如果笔记已保存到数据库中
if (mWorkingNote.getNoteId() > 0) {
Intent intent = new Intent(this, AlarmReceiver.class);// 初始化一个意图用于启动闹钟接收器
intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));// 设置意图的数据为当前笔记的Uri
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);// 获取一个用于启动闹钟接收器的PendingIntent
AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));// 获取一个闹钟管理器
showAlertHeader();// 获取一个闹钟管理器
if(!set) {// 如果不设置提醒时间
alarmManager.cancel(pendingIntent);// 如果不设置提醒时间
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);// 设置当前闹钟
}
} else {
/**
* 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
* should input something
*/
Log.e(TAG, "Clock alert setting error");
showToast(R.string.error_note_empty_for_clock);
}
}
public void onWidgetChanged() {// 当小部件发生改变时触发该方法
updateWidget();// 更新小部件
}
public void onEditTextDelete(int index, String text) {// 当删除编辑文本时触发该方法index表示编辑文本的索引text表示删除的文本内容
int childCount = mEditTextList.getChildCount();// 获取编辑文本列表中的子项数量
if (childCount == 1) {// 如果只有一个子项,则不进行删除操作
return;
}
for (int i = index + 1; i < childCount; i++) {// 循环遍历编辑文本列表将所有索引大于被删除文本的索引的文本的索引减1
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i - 1);
}
mEditTextList.removeViewAt(index); // 移除被删除的编辑文本
NoteEditText edit = null;
if(index == 0) { // 如果被删除的是第一个编辑文本,则将焦点设置到第一个编辑文本
edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(
R.id.et_edit_text);
} else { // 如果被删除的是第一个编辑文本,则将焦点设置到第一个编辑文本
edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(
R.id.et_edit_text);
}
int length = edit.length();// 获取编辑文本的长度
edit.append(text);// 将被删除的文本追加到编辑文本上
edit.requestFocus();// 获取焦点
edit.setSelection(length); // 设置光标位置为文本末尾
}
public void onEditTextEnter(int index, String text) {// 当添加编辑文本时触发该方法index表示编辑文本的索引text表示添加的文本内容
/**
* Should not happen, check for debug
*/
if(index > mEditTextList.getChildCount()) {// 如果索引大于编辑文本列表中的子项数量,则输出错误日志
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
}
View view = getListItem(text, index); // 根据传入的文本和索引获取列表项视图
mEditTextList.addView(view, index);// 将列表项添加到编辑文本列表中
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
edit.requestFocus();// 获取焦点
edit.setSelection(0); // 设置光标位置为文本开头
for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {// 循环遍历编辑文本列表将所有索引大于被添加文本的索引的文本的索引加1
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i);
}
}
private void switchToListMode(String text) {// 切换到列表模式
mEditTextList.removeAllViews();// 移除所有的 View
String[] items = text.split("\n");// 以换行符为分隔符,将字符串 text 分割成多个条目
int index = 0;
for (String item : items) {// 遍历每个条目
if(!TextUtils.isEmpty(item)) {// 如果条目不为空
mEditTextList.addView(getListItem(item, index));// 将新建的条目添加到 mEditTextList 中
index++;
}
}
mEditTextList.addView(getListItem("", index));// 添加一个空条目
mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();// 获取最后一个条目中的 NoteEditText并将其设为焦点
mNoteEditor.setVisibility(View.GONE);// 隐藏 mNoteEditor
mEditTextList.setVisibility(View.VISIBLE);// 显示 mEditTextList
}
private Spannable getHighlightQueryResult(String fullText, String userQuery) {// 获取高亮显示查询结果的 Spannable 对象
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);// 将 fullText 转换为 SpannableString 对象
if (!TextUtils.isEmpty(userQuery)) {// 使用正则表达式匹配 userQuery
mPattern = Pattern.compile(userQuery);
Matcher m = mPattern.matcher(fullText);
int start = 0;
while (m.find(start)) {// 将匹配到的字符串进行高亮显示
spannable.setSpan(
new BackgroundColorSpan(this.getResources().getColor(
R.color.user_query_highlight)), m.start(), m.end(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
start = m.end();
}
}
return spannable;
}
private View getListItem(String item, int index) {// 获取列表项视图
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);// 从布局文件中加载视图
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);// 获取编辑框
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));// 设置编辑框文本的外观样式
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));// 获取复选框
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {// 设置复选框状态改变的监听器
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {// 复选框状态改变时的回调方法
if (isChecked) {// 如果被选中,则在编辑框中添加删除线
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {// 否则,编辑框中的文本恢复正常样式
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
}
}
});
if (item.startsWith(TAG_CHECKED)) {// 否则,编辑框中的文本恢复正常样式
cb.setChecked(true); // 设置复选框为选中状态
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // 在编辑框中添加删除线
item = item.substring(TAG_CHECKED.length(), item.length()).trim();// 截取文本内容
} else if (item.startsWith(TAG_UNCHECKED)) { // 未选中
cb.setChecked(false); // 设置复选框为未选中状态
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); // 编辑框中的文本恢复正常样式
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); // 截取文本内容
}
edit.setOnTextViewChangeListener(this);// 设置编辑框的文本内容变化监听器
edit.setIndex(index);// 设置编辑框的索引值
edit.setText(getHighlightQueryResult(item, mUserQuery));// 设置编辑框的文本内容,并高亮显示用户查询结果
return view;// 返回列表项视图
}
public void onTextChange(int index, boolean hasText) {
if (index >= mEditTextList.getChildCount()) {// 当文本框的内容改变时,根据文本框的索引和是否有文本来显示或隐藏复选框
Log.e(TAG, "Wrong index, should not happen");
return;// 如果索引超出范围,打印错误日志并返回
}
if(hasText) {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);// 如果有文本,显示复选框
} else {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);// 如果没有文本,隐藏复选框
}
}
public void onCheckListModeChanged(int oldMode, int newMode) {// 当清单模式改变时
if (newMode == TextNote.MODE_CHECK_LIST) { // 如果新模式是清单模式
switchToListMode(mNoteEditor.getText().toString()); // 切换到清单模式
} else { // 如果新模式不是清单模式
if (!getWorkingText()) { // 如果当前没有工作文本
mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ",
"")); // 将工作文本设置为去掉未勾选标记的内容
}
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));// 设置文本框的内容为高亮查询结果
mEditTextList.setVisibility(View.GONE); // 隐藏文本框列表
mNoteEditor.setVisibility(View.VISIBLE); // 显示文本框
}
}
private boolean getWorkingText() {//获取当前编辑的文本内容,包括已完成和未完成的任务列表
boolean hasChecked = false;//标记是否有已完成的任务
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果目前是任务列表模式
StringBuilder sb = new StringBuilder(); //创建一个字符串构建器
for (int i = 0; i < mEditTextList.getChildCount(); i++) { //循环遍历所有的子项
View view = mEditTextList.getChildAt(i);//获取当前子项的视图
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);//获取当前子项的编辑框
if (!TextUtils.isEmpty(edit.getText())) { //如果编辑框不为空
if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { //如果当前项被选中
sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");//在字符串构建器中添加已完成的任务项
hasChecked = true;//标记有已完成的任务
} else {//如果当前项未被选中
sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n");//在字符串构建器中添加未完成的任务项
}
}
}
mWorkingNote.setWorkingText(sb.toString()); //将构建好的字符串设置为当前工作的文本内容
} else { //如果不是任务列表模式
mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); //将编辑框中的文本设置为当前工作的文本内容
}
return hasChecked; //返回是否有已完成的任务项的标记
}
private boolean saveNote() {// 保存笔记到数据库中
getWorkingText();// 获取编辑框中的文本内容
boolean saved = mWorkingNote.saveNote();// 将笔记保存到数据库中
if (saved) {
/**
* There are two modes from List view to edit view, open one note,
* create/edit a node. Opening node requires to the original
* position in the list when back from edit view, while creating a
* new node requires to the top of the list. This code
* {@link #RESULT_OK} is used to identify the create/edit state
*/
setResult(RESULT_OK);// 设置返回结果为RESULT_OK
}
return saved; // 返回是否保存成功的结果
}
private void sendToDesktop() {
/**
* Before send message to home, we should make sure that current
* editing note is exists in databases. So, for new note, firstly
* save it
*/
if (!mWorkingNote.existInDatabase()) {
saveNote(); // 如果笔记不存在于数据库中,则先保存笔记
}
if (mWorkingNote.getNoteId() > 0) { // 如果笔记存在于数据库中
Intent sender = new Intent(); // 创建Intent对象
Intent shortcutIntent = new Intent(this, NoteEditActivity.class); // 创建快捷方式Intent对象
shortcutIntent.setAction(Intent.ACTION_VIEW); // 设置快捷方式Intent的Action为ACTION_VIEW
shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); // 设置快捷方式Intent的额外数据
sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); // 设置发送Intent的额外数据
sender.putExtra(Intent.EXTRA_SHORTCUT_NAME,
makeShortcutIconTitle(mWorkingNote.getContent())); // 设置发送Intent的额外数据
sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); // 设置发送Intent的额外数据
sender.putExtra("duplicate", true); // 设置发送Intent的额外数据
sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); // 设置发送Intent的Action为INSTALL_SHORTCUT
showToast(R.string.info_note_enter_desktop);// 显示Toast提示信息
sendBroadcast(sender); // 发送广播
} else {
/**
* 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
* should input something
*/
Log.e(TAG, "Send to desktop error");// 打印错误日志信息
showToast(R.string.error_note_empty_for_send_to_desktop); // 显示Toast提示信息
}
}
private String makeShortcutIconTitle(String content) { // 生成快捷方式的图标标题,去掉勾选框的标记
content = content.replace(TAG_CHECKED, ""); // 去掉已勾选的标记
content = content.replace(TAG_UNCHECKED, ""); // 去掉未勾选的标记
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
SHORTCUT_ICON_TITLE_MAX_LEN) : content; // 如果标题超出指定长度,截取前 SHORTCUT_ICON_TITLE_MAX_LEN 个字符作为标题
}
private void showToast(int resId) { // 显示短时间的提示信息
showToast(resId, Toast.LENGTH_SHORT);
}
private void showToast(int resId, int duration) { // 显示指定时间的提示信息
Toast.makeText(this, resId, duration).show();
}
}

@ -0,0 +1,2 @@
#Tue Nov 09 19:08:53 CST 2021
gradle.version=6.8

@ -0,0 +1,19 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion '30.0.2'
defaultConfig {
applicationId "net.micode.notes"
minSdkVersion 21
targetSdkVersion 8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}

@ -0,0 +1,12 @@
/**
* Automatically generated file. DO NOT MODIFY
*/
package net.micode.notes;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "net.micode.notes";
public static final String BUILD_TYPE = "debug";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "0.1";
}

@ -0,0 +1,10 @@
{
"version": 2,
"artifactType": {
"type": "COMPATIBLE_SCREEN_MANIFEST",
"kind": "Directory"
},
"applicationId": "net.micode.notes",
"variantName": "debug",
"elements": []
}

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<merger version="3"><dataSet config="main" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="D:\android_workspace\MiNotes\app\src\main\assets"/><source path="D:\android_workspace\MiNotes\app\build\intermediates\shader_assets\debug\out"/></dataSet><dataSet config="debug" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="D:\android_workspace\MiNotes\app\src\debug\assets"/></dataSet></merger>

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<merger version="3"><dataSet config="main" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="D:\android_workspace\MiNotes\app\src\main\jniLibs"/></dataSet><dataSet config="debug" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="D:\android_workspace\MiNotes\app\src\debug\jniLibs"/></dataSet></merger>

@ -0,0 +1,96 @@
#Wed Nov 17 14:03:32 CST 2021
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\selected.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_selected.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_4x_green.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_4x_green.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_green_single.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_green_single.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\add_account_text.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_add_account_text.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_blue_down.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_blue_down.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_2x_yellow.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_2x_yellow.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\menu\\note_list_dropdown.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\menu_note_list_dropdown.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\font_small.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_font_small.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_title_yellow.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_title_yellow.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\note_edit_color_selector_panel.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_note_edit_color_selector_panel.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\new_note_normal.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_new_note_normal.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\notification.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_notification.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\widget_2x.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_widget_2x.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_yellow_middle.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_yellow_middle.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_red_up.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_red_up.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\color\\primary_text_dark.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\color_primary_text_dark.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\menu\\note_list.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\menu_note_list.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\dropdown_icon.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_dropdown_icon.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_4x_white.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_4x_white.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\raw\\introduction=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\raw_introduction.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_yellow_down.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_yellow_down.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\menu\\sub_folder.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\menu_sub_folder.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_yellow_single.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_yellow_single.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\menu\\note_edit.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\menu_note_edit.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\xml\\widget_2x_info.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\xml_widget_2x_info.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_red_down.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_red_down.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\clock.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_clock.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\xml\\searchable.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\xml_searchable.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable\\new_note.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable_new_note.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_green_down.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_green_down.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\font_normal.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_font_normal.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\menu_move.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_menu_move.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\note_edit_list_item.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_note_edit_list_item.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_title_red.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_title_red.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\note_list_footer.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_note_list_footer.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\bg_color_btn_mask.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_bg_color_btn_mask.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_4x_blue.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_4x_blue.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_footer_bg.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_footer_bg.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_white.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_white.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\menu\\call_note_edit.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\menu_call_note_edit.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\settings_header.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_settings_header.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_blue.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_blue.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_title_green.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_title_green.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\widget_4x.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_widget_4x.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\menu\\call_record_folder.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\menu_call_record_folder.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\dialog_edit_text.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_dialog_edit_text.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\raw-zh-rCN\\introduction=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\raw-zh-rCN_introduction.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_white_middle.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_white_middle.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\note_item.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_note_item.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_2x_green.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_2x_green.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\bg_btn_set_color.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_bg_btn_set_color.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_title_blue.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_title_blue.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\font_size_selector_bg.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_font_size_selector_bg.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_yellow_up.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_yellow_up.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_2x_blue.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_2x_blue.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_blue_up.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_blue_up.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\title_bar_bg.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_title_bar_bg.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_red_middle.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_red_middle.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\icon_app.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_icon_app.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_white_single.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_white_single.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\note_list.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_note_list.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_green_up.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_green_up.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\search_result.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_search_result.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_2x_white.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_2x_white.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\menu\\note_list_options.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\menu_note_list_options.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\font_large.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_font_large.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\datetime_picker.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_datetime_picker.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\note_edit.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_note_edit.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_red_single.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_red_single.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\folder_list_item.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_folder_list_item.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_2x_red.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_2x_red.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\call_record.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_call_record.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_red.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_red.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_background.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_background.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\new_note_pressed.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_new_note_pressed.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\xml\\preferences.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\xml_preferences.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\title_alert.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_title_alert.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_4x_red.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_4x_red.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\account_dialog_title.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_account_dialog_title.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\layout\\note_list_dropdown_menu.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\layout_note_list_dropdown_menu.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_white_up.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_white_up.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\menu_delete.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_menu_delete.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_green.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_green.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_blue_middle.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_blue_middle.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\delete.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_delete.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_yellow.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_yellow.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\widget_4x_yellow.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_widget_4x_yellow.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\font_super.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_font_super.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\edit_title_white.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_edit_title_white.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_green_middle.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_green_middle.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_blue_single.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_blue_single.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_white_down.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_white_down.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\drawable-hdpi\\list_folder.9.png=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\drawable-hdpi_list_folder.9.png.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\color\\secondary_text_dark.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\color_secondary_text_dark.xml.flat
D\:\\android_workspace\\MiNotes\\app\\src\\main\\res\\xml\\widget_4x_info.xml=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\res\\merged\\debug\\xml_widget_4x_info.xml.flat

File diff suppressed because one or more lines are too long

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<merger version="3"><dataSet config="main" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="D:\android_workspace\MiNotes\app\src\main\shaders"/></dataSet><dataSet config="debug" ignore_pattern="!.svn:!.git:!.ds_store:!*.scc:.*:&lt;dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~"><source path="D:\android_workspace\MiNotes\app\src\debug\shaders"/></dataSet></merger>

@ -0,0 +1,4 @@
#Thu Nov 18 13:20:45 CST 2021
base.0=D\:\\android_workspace\\MiNotes\\app\\build\\intermediates\\dex\\debug\\mergeProjectDexDebug\\classes.dex
path.0=classes.dex
renamed.0=classes.dex

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save