2310175682@qq.com 2 years ago
parent ec082210d9
commit 4f14defff4

@ -1,74 +0,0 @@
/*
* 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;//返回空
}
}
}

@ -1,279 +0,0 @@
/*
* 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属性
}
}

@ -1,362 +0,0 @@
/*
* 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");
}
}

@ -1,305 +0,0 @@
/*
* 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;//初始化,返回一个空指针
}
}

@ -1,34 +0,0 @@
/*
* 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);
}
}

@ -1,127 +0,0 @@
/*
* 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();
}
}
}

@ -1,585 +0,0 @@
/*
* 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;
}//重置更新内容
}

@ -1,800 +0,0 @@
/*
* 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值设置为真

@ -1,128 +0,0 @@
/*
* 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;
}//返回当前同步状态
}

@ -1,82 +0,0 @@
/*
* 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");//非法参数异常
}
}

@ -1,33 +0,0 @@
/*
* 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的构造方法
}
}

@ -1,101 +0,0 @@
/*
* 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;
}//获取删除标识
}

@ -1,189 +0,0 @@
/*
* 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;
}
}

@ -1,505 +0,0 @@
/*
* 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;
}//改变数据库构造模式
}

@ -1,351 +0,0 @@
/*
* 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;
}//获取父节点列表
}

@ -1,343 +0,0 @@
/*
* 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;
}//获取任务指针。
}

@ -1,268 +0,0 @@
/*
* 便
* 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.model;//包名
import android.content.ContentProviderOperation;//批量的更新、插入、删除数据
import android.content.ContentProviderResult;//操作结果
import android.content.ContentUris;//添加或者修改uri后面的ID
import android.content.ContentValues;//存储基本数据类型的数据
import android.content.Context;// 获取调用内容
import android.content.OperationApplicationException;//操作数据容错
import android.net.Uri;//Uri相关操作标识唯一的资源
import android.os.RemoteException;//异常处理
import android.util.Log;//输出日志,比如说出错、警告等
import net.micode.notes.data.Notes;//小米便签一些属性的操作
import net.micode.notes.data.Notes.CallNote;//调用操作
import net.micode.notes.data.Notes.DataColumns;//数据栏
import net.micode.notes.data.Notes.NoteColumns;//笔记栏
import net.micode.notes.data.Notes.TextNote;//操作区
import java.util.ArrayList;//导入Java,util,ArrayList
public class Note {//定义note类处理单个便签
private ContentValues mNoteDiffValues;//声明一个ContentValues私有变量ContentValues用来存储note与上次修改后的改动
private NoteData mNoteData;//声明一个私有变量NoteData用来记录单个便签的基本信息
private static final String TAG = "Note";//设置软件标签
/**
* Create a new note id for adding a new note to databases
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
//Create a new note in the database
/*
* 便ID
* 便便IDuri
* 便IDID
* @context便
* @folderId便ID
* @return便ID
*/
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
long noteId = 0;
try {
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
}
return noteId;
}
public Note() {//定义两个变量用来存储便签的数据,一个是存储便签属性、一个是存储便签内容
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
}
public void setNoteValue(String key, String value) {
/*
* 便
* key便valuemNoteDiffValues
* @key
* @value
*/
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
public void setTextData(String key, String value) {//设置数据库表格的标签文本内容的数据
mNoteData.setTextData(key, value);
}
public void setTextDataId(long id) {//设置文本数据的ID
mNoteData.setTextDataId(id);
}
public long getTextDataId() {//获取文本数据的ID
return mNoteData.mTextDataId;
}
public void setCallDataId(long id) {//设置电话号码数据的ID
mNoteData.setCallDataId(id);
}
public void setCallData(String key, String value) {//设置电话号码的数据
mNoteData.setCallData(key, value);
}
public boolean isLocalModified() {//判断便签是否进行了本地修改
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
public boolean syncNote(Context context, long noteId) {//判断对修改过的便签是否进行同步
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
if (!isLocalModified()) {
return true;
}
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
*/
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
}
mNoteDiffValues.clear();
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
}
return true;
}
private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据
private long mTextDataId;//文本数据id
private ContentValues mTextDataValues;//文本数据内容
private long mCallDataId;//电话号码数据ID
private ContentValues mCallDataValues;//电话号码数据内容
private static final String TAG = "NoteData";//默认构造函数
public NoteData() {//NoteData的构造函数初始化四个变量
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
mTextDataId = 0;
mCallDataId = 0;
}
boolean isLocalModified() {//判断是否本地修改
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
void setTextDataId(long id) {//设置文本数据的ID
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
}
void setCallDataId(long id) {//设置电话号码对应的id
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
}
mCallDataId = id;
}
void setCallData(String key, String value) {//设置电话号码数据内容,并且保存修改时间
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
void setTextData(String key, String value) {//设置文本数据
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
Uri pushIntoContentResolver(Context context, long noteId) {//使用uri将数据添加到数据库
/**
* Check for safety
*/
if (noteId <= 0) {//判断数据是否合法
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) {//把文本数据存入DataColumns
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {//文本数据ID为零意味着这个id是新建默认的id
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {//电话号码同步
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {//将电话号码的id设定为uri提供的id
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
}
} else {//当电话号码不为新建时更新电话号码ID
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}
mCallDataValues.clear();
}
if (operationList.size() > 0) {//存储过程中如果遇到异常,通过如下进行处理
try {//抛出远程异常,并写回日志
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {//捕捉操作异常并写回日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));//异常日志
return null;
}
}
return null;
}
}
}

@ -1,370 +0,0 @@
/*便
* 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.model;//在model包中
import android.appwidget.AppWidgetManager;//需要调用的其他类
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
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.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
public class WorkingNote {/*WorkingNote,便
便便便便*/
// Note for the working note
private Note mNote;
// Note Id
private long mNoteId;
// Note content
private String mContent;
// Note mode
private int mMode;
private long mAlertDate;
private long mModifiedDate;
private int mBgColorId;
private int mWidgetId;
private int mWidgetType;
private long mFolderId;
private Context mContext;
private static final String TAG = "WorkingNote";
private boolean mIsDeleted;
private NoteSettingChangedListener mNoteSettingStatusListener;
public static final String[] DATA_PROJECTION = new String[] {/*NOTE_PROJECTION
*/
DataColumns.ID,
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
public static final String[] NOTE_PROJECTION = new String[] {//保存便签属性信息的string数组
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE
};
private static final int DATA_ID_COLUMN = 0;//以下定义的是上述两个列表中各元素的索引
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
private WorkingNote(Context context, long folderId) {//初始化WorkingNote类的内部数据变量
mContext = context;
mAlertDate = 0;
mModifiedDate = System.currentTimeMillis();//获取系统当前时间的方法,返回当前时间
mFolderId = folderId;
mNote = new Note();//加载一个已存在的便签
mNoteId = 0;
mIsDeleted = false;
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;//默认是不可见
}
// Existing note construct
private WorkingNote(Context context, long noteId, long folderId) {//载入便签
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
mIsDeleted = false;
mNote = new Note();
loadNote();
}
private void loadNote() {//加载已有的便签
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
}
cursor.close();
} else {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData();
}
private void loadNoteData() {//加载便签数据
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
}, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) {
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) {
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
Log.d(TAG, "Wrong note type with type:" + type);
}
} while (cursor.moveToNext());
}
cursor.close();
} else {
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}
}
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {//创建一个空便签
WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
note.setWidgetType(widgetType);
return note;
}
public static WorkingNote load(Context context, long id) {//加载已经创建的便签
return new WorkingNote(context, id, 0);
}
public synchronized boolean saveNote() {//保存便签成功保存返回true否则返回false
if (isWorthSaving()) {
if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
mNote.syncNote(mContext, mNoteId);
/**
* Update widget content if there exist any widget of this note
*/
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
return true;
} else {
return false;
}
}
public boolean existInDatabase() {//查看该note是否已经存放到数据库中
return mNoteId > 0;
}
private boolean isWorthSaving() {//判断是否需要保存
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
} else {
return true;
}
}
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {//设置状态改变的监听器
mNoteSettingStatusListener = l;
}
public void setAlertDate(long date, boolean set) {//设置提醒日期
if (date != mAlertDate) {
mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
}
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onClockAlertChanged(date, set);
}
}
public void markDeleted(boolean mark) {//设置删除标志
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
}
public void setBgColorId(int id) {//设定背景颜色
if (id != mBgColorId) {
mBgColorId = id;
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged();
}
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
}
}
public void setCheckListMode(int mode) {//设置检查列表模式
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
}
mMode = mode;
mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
}
}
public void setWidgetType(int type) {//设置窗口类型
if (type != mWidgetType) {
mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
}
}
public void setWidgetId(int id) {//设置窗口编号
if (id != mWidgetId) {
mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
}
}
public void setWorkingText(String text) {//写入文本内容
if (!TextUtils.equals(mContent, text)) {
mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent);
}
}
public void convertToCallNote(String phoneNumber, long callDate) {//转换成电话提醒的便签
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
public boolean hasClockAlert() {//检测是否有时钟提醒mAlertDate > 0返回真否则返回假
return (mAlertDate > 0 ? true : false);
}
public String getContent() {//获取便签内容
return mContent;
}
public long getAlertDate() {//获取提醒时间
return mAlertDate;
}
public long getModifiedDate() {//获取修改时间
return mModifiedDate;
}
public int getBgColorResId() {//获取背景颜色来源id
return NoteBgResources.getNoteBgResource(mBgColorId);
}
public int getBgColorId() {//获取背景颜色id
return mBgColorId;
}
public int getTitleBgResId() {//获取标题背景颜色资源的id
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
public int getCheckListMode() {//获取清单模式
return mMode;
}
public long getNoteId() {//获取便签id
return mNoteId;
}
public long getFolderId() {//获取文件夹id
return mFolderId;
}
public int getWidgetId() {//获取窗口id
return mWidgetId;
}
public int getWidgetType() {//监听检测便签设置变化的接口
return mWidgetType;
}
public interface NoteSettingChangedListener {//监听便签设置是否改变
/**
* Called when the background color of current note has just changed
*/
void onBackgroundColorChanged();//背景颜色改变
/**
* Called when user set clock
*/
void onClockAlertChanged(long date, boolean set);//提醒时间按钮,可进行时间的更改和提醒的开关
/**
* Call when user create note from widget
*/
void onWidgetChanged();//窗口改变
/**
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
*/
void onCheckListModeChanged(int oldMode, int newMode);//便签检查列表模式改变
}
}

@ -1,343 +0,0 @@
/*
* 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.tool;//定义小米便签 功能类
import android.content.Context;//导入各种需要的类
import android.database.Cursor;//查询数据类型
import android.os.Environment;//导入安卓环境包
import android.text.TextUtils;//导入安卓文本功能包
import android.text.format.DateFormat;//用于转化日期格式
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.DataConstants;//常数类
import net.micode.notes.data.Notes.NoteColumns;//便签类
import java.io.File;//引入文件操作类
import java.io.FileNotFoundException;//文件未找到的错误处理
import java.io.FileOutputStream;//文件的输入
import java.io.IOException;//操作错误处理
import java.io.PrintStream;//导入需要的包
public class BackupUtils {//此处为备份工具包
private static final String TAG = "BackupUtils";//实化一个BackupUtils的对象
// Singleton stuff
private static BackupUtils sInstance;//初始化sInstance
public static synchronized BackupUtils getInstance(Context context) {//如果当前备份不在,则再新声明一个
if (sInstance == null) {
sInstance = new BackupUtils(context);
}
return sInstance;//返回当前的sInstance值
}
/**
* Following states are signs to represents backup or restore
* status
*/
// Currently, the sdcard is not mounted
public static final int STATE_SD_CARD_UNMOUONTED = 0;//备份文件夹不存在
// The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;//变量表示备份的文件不存在
// The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2;//超时异常
// Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3;//系统错误状态为3
// Backup or restore success
public static final int STATE_SUCCESS = 4;//变量表示备份成功
private TextExport mTextExport;//实例化一个为mTextExport的对象
private BackupUtils(Context context) {//初始化构造函数
mTextExport = new TextExport(context);
}
private static boolean externalStorageAvailable() {//判断外部存储设备是否有效
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
public int exportToText() {//输出至文本
return mTextExport.exportToText();
}
public String getExportedTextFileName() {//返回获取的文件名
return mTextExport.mFileName;
}
public String getExportedTextFileDir() {//返回文件的目录
return mTextExport.mFileDirectory;
}
private static class TextExport {//内部类:文本输出
private static final String[] NOTE_PROJECTION = {//定义了一个数组存储便签的信息
NoteColumns.ID,//ID
NoteColumns.MODIFIED_DATE,//日期
NoteColumns.SNIPPET,
NoteColumns.TYPE
};
private static final int NOTE_COLUMN_ID = 0;//初始化便签ID
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;//初始化修改时间
private static final int NOTE_COLUMN_SNIPPET = 2;//初始化小段消息状态
private static final String[] DATA_PROJECTION = {//定义字符串存储函数的基本信息
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
private static final int DATA_COLUMN_CONTENT = 0;//表示设定数据内容表示为0
private static final int DATA_COLUMN_MIME_TYPE = 1;//数据媒体类型标识为1
private static final int DATA_COLUMN_CALL_DATE = 2;//访问日期表示为2
private static final int DATA_COLUMN_PHONE_NUMBER = 4;//电话号码表示为4
private final String [] TEXT_FORMAT;//文档格式标识
private static final int FORMAT_FOLDER_NAME = 0;//文件命名格式表示为0
private static final int FORMAT_NOTE_DATE = 1;//便签日期格式表示为1
private static final int FORMAT_NOTE_CONTENT = 2;//便签目录格式
private Context mContext;//定义上下文类
private String mFileName;//定义文件名
private String mFileDirectory;//文件路径
public TextExport(Context context) {//从context类实例中花去信息给对应的属性赋初始值
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
}
private String getFormat(int id) {
return TEXT_FORMAT[id];
}//获取文本组成部分
/**
* Export the folder identified by folder id to text
*/
private void exportFolderToText(String folderId, PrintStream ps) {//通过文件夹目录ID将目录导出后成为文件
// Query notes belong to this folder
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
}, null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
}
notesCursor.close();//关闭游标
}
}
/**
* Export note identified by id to a print stream
*/
private void exportNoteToText(String noteId, PrintStream ps) {//函数:将便签的内容以文本的形式显示在屏幕上
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,//利用光标来扫描内容
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
if (dataCursor != null) {//如果光标不为空
if (dataCursor.moveToFirst()) {//游标已经在第一步就位
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);//获取便签媒体类型
if (DataConstants.CALL_NOTE.equals(mimeType)) {//判断便签的内容
// Print phone number
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);//获取电话号码
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);//获取通话时间
String location = dataCursor.getString(DATA_COLUMN_CONTENT);//获取地址
if (!TextUtils.isEmpty(phoneNumber)) {//判断是否为空字符
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat//输出电话号码
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
if (!TextUtils.isEmpty(location)) {//输出位置location
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {//如果便签的内容存在,则直接输出
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {//如果便签内容不为空
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content));
}
}
} while (dataCursor.moveToNext());//光标下移
}
dataCursor.close();//关闭光标
}
// print a line separator between note
try {//正常情况再note下面输出一条线
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
});
} catch (IOException e) {//获取错误信息
Log.e(TAG, e.toString());
}
}
/**
* Note will be exported as text which is user readable
*/
public int exportToText() {//以TEXT形式输出到外部设备
if (!externalStorageAvailable()) {//如果外部设备未安装好,返回对应状态
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
PrintStream ps = getExportToTextPrintStream();//获取存储信息
if (ps == null) {//如果没有得到正常的数据流,则输出错误信息
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
Cursor folderCursor = mContext.getContentResolver().query(//定位需要导出的文件夹
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
if (folderCursor != null) {//如果文件夹不为空,即存在文件夹
if (folderCursor.moveToFirst()) {//文件光标再第一行就位
do {
// Print folder's name
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {//找到文件名
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);//取便签为便签名字
}
if (!TextUtils.isEmpty(folderName)) {//判断folderName是否存在
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);//通过便签ID获得folderID
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());//文件夹的光标下移
}
folderCursor.close();//关闭光标
}
// Export notes in root's folder
Cursor noteCursor = mContext.getContentResolver().query(//输出根目录下面的笔记
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
if (noteCursor != null) {//如果笔记游标不为空
if (noteCursor.moveToFirst()) {//便签光标下移
do {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(//输出修改日期
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
String noteId = noteCursor.getString(NOTE_COLUMN_ID);//找到这块数据的ID
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());//便签光标下移
}
noteCursor.close();//关闭游标
}
ps.close();
return STATE_SUCCESS; //返回成功导出状态
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {//获取指向文件的打印流
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,//创建文件
R.string.file_name_txt_format);
if (file == null) {//如果文件夹为空,则创建失败
Log.e(TAG, "create file to exported failed");
return null;
}
mFileName = file.getName();//得到文件名
mFileDirectory = mContext.getString(R.string.file_path);//获取文件路径
PrintStream ps = null;//初始化ps
try {//将ps输出流输出到特定的文件目的是导出文件
FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {//给出错误信息
e.printStackTrace();
return null;
} catch (NullPointerException e) {//捕获空指针异常
e.printStackTrace();
return null;
}
return ps;
}
}
/**
* Generate the text file to store imported data
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
//产生用于存储输入信息的文件
StringBuilder sb = new StringBuilder();//构建一个动态字符串将外部信息加入其中
sb.append(Environment.getExternalStorageDirectory());//加入路径
sb.append(context.getString(filePathResId));//文件的存储路径
File filedir = new File(sb.toString());//存储路径信息
sb.append(context.getString(//格式化输出当前系统时间
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),//将当前的系统时间以预定的格式输出
System.currentTimeMillis())));
File file = new File(sb.toString());//将输出连接到一个文件里
try {
if (!filedir.exists()) {//如果文件不存在,则重建
filedir.mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
return file;//返回导出的文件
} catch (SecurityException e) {//处理碰到的异常
e.printStackTrace();
} catch (IOException e) {//捕获异常
e.printStackTrace();
}
return null;
}
}

@ -1,307 +0,0 @@
/*
* 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.tool;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
public class DataUtils {//数据的集成工具类
public static final String TAG = "DataUtils";
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
//方法:实现了批量删除便签
if (ids == null) {//判断笔记id是否为空
Log.d(TAG, "the ids is null");
return true;
}
if (ids.size() == 0) {//判断笔记大小是否为空
Log.d(TAG, "no id is in the hashset");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();//提供一个事件的列表
for (long id : ids) {//遍历数据,如果此数据为根目录则跳过此数据不删除,如果不是根目录则将此数据删除
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
ContentProviderOperation.Builder builder = ContentProviderOperation//使用newdelete进行删除
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build());
}
try {//这是一个错误处理机制,并分别针对两种不同的错误进行处理。
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
//数据库事项,由一系列的数据库操作序列构成,这个事项作为一个整体来处理
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {//对错误进行处理,并将错误存储到日志当中
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
}
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
//将标签移动到另一个目录下
ContentValues values = new ContentValues();//实例化一个contentValues类
values.put(NoteColumns.PARENT_ID, desFolderId);//将PARENT_ID更改为目标目录ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);//设置origin也即原本的父节点为原本的文件夹的id
values.put(NoteColumns.LOCAL_MODIFIED, 1);//设置修改符号为1
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
//对需要移动的便签进行数据更新然后用update实现
}
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {//批量的将标签移动到另一个目录下
if (ids == null) {//判断便签ID是否为空
Log.d(TAG, "the ids is null");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
//将ids里包含的每一列的数据逐次加入到operationList中等待最后的批量处理
for (long id : ids) {//遍历所有选中的便签的id
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());//将ids里的数据添加到operationlist中以便接下来批量处理
}
try {//利用Log输出信息来进行错误检测
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
//applyBatch一次性处理一个操作列表
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {//异常处理
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*/
public static int getUserFolderCount(ContentResolver resolver) {//获取用户文件夹数
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
//resolver.query()方法第二个参数是要返回的列第三个参数是Section查询where字句第四个是查询条件属性值第五个是筛选规则
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);//String.valueof将形参转成字符串返回
int count = 0;
if(cursor != null) {//尝试得到用户文件夹的数量
if(cursor.moveToFirst()) {
try {//异常处理
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {//索引序号超出界限
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();//关闭游标
}
}
}
return count;
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {//是否在便签数据库中可见
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),//通过withappendedid的方法为uri加上id
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
null);//sql语句表示筛选出列中type等于string数组中type且每一项的PARENT_ID不等于Notes.ID.TRAXH_FOLDER
boolean exist = false;//查询文件
if (cursor != null) {//用getcount函数判断cursor是否为空
if (cursor.getCount() > 0) {//如果有满足条件的条目那么就是可见exist为真否则不可见exist为假
exist = true;
}
cursor.close();//关闭游标
}
return exist;//在数据数据库中是否存在
}
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {//判断该note是否在数据库中存在
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
//相比于上面,这个只是存在性判定,因此不需要过多筛选条件
boolean exist = false;//初始化存在状态
if (cursor != null) {//根据getcount此时的值可以判断dataID的存在性
if (cursor.getCount() > 0) {//根据筛选出来的条数判断存在性
exist = true;
}
cursor.close();//关闭游标
}
return exist;
}
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {//检查文件名字是否可见
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
//通过URI与dataId在数据库中查找数据
null, null, null, null);
boolean exist = false;//根据数据的有无返回相应的布尔值
if (cursor != null) {
if (cursor.getCount() > 0) {//调用对应的uri的数据值进行查询
exist = true;
}
cursor.close();//关闭游标
}
return exist;//通过名字查询文件是否存在
}
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
//这个则是判断某个文件夹名字是否对应一个未被删除的文件夹
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,//筛选类型正确的、未被删除的和名字对应得上的
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);//通过名字查询文件是否存在
boolean exist = false;
if(cursor != null) {//判断找到的文件名返回文件是否存在的bool值
if(cursor.getCount() > 0) {
exist = true;
}
cursor.close();//关闭游标
}
return exist;
}
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
//使用hashset来存储不同窗口的id和type并且建立对应关系
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,//父id为传入的文件夹id
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },//hash集合为空的情况
null);
HashSet<AppWidgetAttribute> set = null;//根据窗口的记录一一添加对应的属性值
if (c != null) {//将app窗口的属性加入到HashSet中
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {//把每一个条目对应的窗口id和type记录下来放到set里面。每一行的第0个int和第1个int分别对应widgetId和widgetType
AppWidgetAttribute widget = new AppWidgetAttribute();//新建一个区块
widget.widgetId = c.getInt(0);//0对应的NoteColumns.WIDGET_ID
widget.widgetType = c.getInt(1);//1对应的NoteColumns.WIDGET_TYPE
set.add(widget);
} catch (IndexOutOfBoundsException e) {//当下标超过边界,那么返回错误
Log.e(TAG, e.toString());
}
} while (c.moveToNext());//访问下一条
}
c.close();//关闭游标
}
return set;
}
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {//通过笔记ID获取号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },//新建字符列表
null);
if (cursor != null && cursor.moveToFirst()) {// 获取电话号码,并处理异常。
try {//返回电话号码
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {//捕获字符
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
}
}
return "";
}
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
//同样的通过映射关系通过号码和日期获取ID
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);//通过数据库操作查询条件callDate和phoneNumber匹配传入参数的值找到对应的note
if (cursor != null) {//得到该note的系统属性并以Long值的形式来保存
if (cursor.moveToFirst()) {
try {
return cursor.getLong(0);//0对应的CallNote.NOTE_ID
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
cursor.close();//关闭游标
}
return 0;
}
public static String getSnippetById(ContentResolver resolver, long noteId) {//按ID获取片段
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,//通过ID查询
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) {//以string的形式获取该对象当前行指定列的值。
String snippet = "";//对字符串进行格式处理,将字符串两头的空格去掉同时将换行符去掉
if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
}
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
//IllegalArgumentException是非法传参异常也就是参数传的类型冲突属于RunTimeException运行时异常
}
public static String getFormattedSnippet(String snippet) {//对字符串进行格式处理,将字符串两头的空格去掉,同时将换行符去掉
if (snippet != null) {
snippet = snippet.trim();// trim()函数: 移除字符串两侧的空白字符或其他预定义字符
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);//截取到第一个换行符
}
}
return snippet;
}
}

@ -1,113 +0,0 @@
/*
* 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.tool;//定义了很多的静态字符串目的就是为了提供jsonObject中相应字符串的"key"
public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id";//行动ID
public final static String GTASK_JSON_ACTION_LIST = "action_list";//任务列表
public final static String GTASK_JSON_ACTION_TYPE = "action_type";//任务类型
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";//新建
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";//移动
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";//更新
public final static String GTASK_JSON_CREATOR_ID = "creator_id";//id
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";//子实体
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";//客户端
public final static String GTASK_JSON_COMPLETED = "completed";
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";//当前列表位置
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";//失败
public final static String GTASK_JSON_DELETED = "deleted";//删除
public final static String GTASK_JSON_DEST_LIST = "dest_list";
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
public final static String GTASK_JSON_ID = "id";
public final static String GTASK_JSON_INDEX = "index";//索引
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
public final static String GTASK_JSON_LIST_ID = "list_id";
public final static String GTASK_JSON_LISTS = "lists";
public final static String GTASK_JSON_NAME = "name";
public final static String GTASK_JSON_NEW_ID = "new_id";
public final static String GTASK_JSON_NOTES = "notes";
public final static String GTASK_JSON_PARENT_ID = "parent_id";//搭档ID
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
public final static String GTASK_JSON_RESULTS = "results";
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
public final static String GTASK_JSON_TASKS = "tasks";//任务栏
public final static String GTASK_JSON_TYPE = "type";
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
public final static String GTASK_JSON_TYPE_TASK = "TASK";//任务
public final static String GTASK_JSON_USER = "user";
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
public final static String FOLDER_DEFAULT = "Default";
public final static String FOLDER_CALL_NOTE = "Call_Note";//呼叫小米便签
public final static String FOLDER_META = "METADATA";
public final static String META_HEAD_GTASK_ID = "meta_gid";
public final static String META_HEAD_NOTE = "meta_note";
public final static String META_HEAD_DATA = "meta_data";//数据
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}

@ -1,181 +0,0 @@
/*
* 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.tool;
import android.content.Context;
import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
public class ResourceParser {//ResourceParser类获取程序资源如图片颜色等
public static final int YELLOW = 0;//为颜色常量和字体常量赋值,为字体默认大小赋值
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
public static final int BG_DEFAULT_COLOR = YELLOW;//默认背景颜色(黄)
public static final int TEXT_SMALL = 0;//为颜色常量和字体常量赋值,为字体默认大小赋值
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;//默认字体大小(中)
public static class NoteBgResources {// Note的背景颜色
private final static int [] BG_EDIT_RESOURCES = new int [] {//.调用drawable中的五种颜色的背景图片png文件
R.drawable.edit_yellow,//调用drawable中的五种颜色的标题背景图片png文件
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
};
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {//背景标题的资源常量数组
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
};
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}//获取便签背景资源id
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}//获取标题使用的资源的ID
public static int getDefaultBgId(Context context) {//获取默认背景颜色对应Id
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(//如果颜色设定为随机的颜色,那么就随机返回一个颜色
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
return BG_DEFAULT_COLOR;//否则返回默认背景颜色
}
}
public static class NoteItemBgResources {//便签项目背景资源子类,包括方法:获得首尾项目等背景资源
private final static int [] BG_FIRST_RESOURCES = new int [] {//不同drawable的变量声明
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
};
private final static int [] BG_NORMAL_RESOURCES = new int [] {//定义了背景的默认资源
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
};
private final static int [] BG_LAST_RESOURCES = new int [] {//定义背景的下方资源
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
};
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
};
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}//通过ID获取所需要的资源
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}//通过ID寻找last的颜色值
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}//通过ID获取单个便签背景颜色资源
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}//通过ID寻找normal的颜色值
public static int getFolderBgRes() {
return R.drawable.list_folder;
}//设置窗口的资源
}
public static class WidgetBgResources {//小窗口情况下的背景资源类
private final static int [] BG_2X_RESOURCES = new int [] {//2x小窗口背景资源初始化
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}//根据ID加载BG_2X_RESOURCES数组里的颜色资源序号。
private final static int [] BG_4X_RESOURCES = new int [] {//本条与下一条private定义与上两条相同只不过由2倍扩大成了4倍
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}//根据ID加载BG_4X_RESOURCES数组里的颜色资源序号。
}
public static class TextAppearanceResources {//文本外观资源,包括默认字体,以及获取资源大小
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {//定义外观资源
R.style.TextAppearanceNormal,//通过ID找到格式没有要求的话就设置为默认格式
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
public static int getTexAppearanceResource(int id) {//这是一个容错的函数防止输入的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 (id >= TEXTAPPEARANCE_RESOURCES.length) {//若输入id大于字体编号最大值则返回默认值
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
}
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}//直接返回为资源的长度
}
}

@ -1,159 +0,0 @@
/*
* 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;// 将音频播放器置为空
}
}
}

@ -1,67 +0,0 @@
/*
* 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();
}
}
}

@ -1,30 +0,0 @@
/*
* 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
}
}

@ -1,502 +0,0 @@
/*
* 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方法传递当前日期时间的各个参数
}
}

@ -1,90 +0,0 @@
/*
* 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方法
}
}
}

@ -1,62 +0,0 @@
/*
* 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);
}// 设置按钮的标题文字
}

@ -1,81 +0,0 @@
/*
* 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 上
}
}

@ -1,879 +0,0 @@
/*
* 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();
}
}

@ -1,214 +0,0 @@
/*
* 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.graphics.Rect;
import android.text.Layout;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.widget.EditText;
import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
public class NoteEditText extends EditText {//继承EditText设置便签设置文本框
private static final String TAG = "NoteEditText";//类的名称,可以用来输出日志文件
private int mIndex;//建立一个字符和整数的表,存放电话号码、网址、邮箱
private int mSelectionStartBeforeDelete;//声明整型变量,获取删除文本前的位置
private static final String SCHEME_TEL = "tel:" ;//声明字符串常量,标志电话、网址、邮件
private static final String SCHEME_HTTP = "http:" ;//文本中网页内容
private static final String SCHEME_EMAIL = "mailto:" ;//文本中邮件内容
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();//设置映射,将文本内容(电话、网址、邮件)做链接处理
static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
}//在NoteEditActivity进行文本的操作删除进入编辑
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
*/
public interface OnTextViewChangeListener {//接口OnTextViewChangeListener会被NoteEditActivity大量调用其中定义了在编辑文本中delete、点击enter、text改变时的方法
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*/
void onEditTextDelete(int index, String text);//当delete键按下时删除当前编辑的文字块
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*/
void onEditTextEnter(int index, String text);//当触发输入文本KeyEvent时增添文本
/**
* Hide or show item option when text change
*/
void onTextChange(int index, boolean hasText);//文字更改时隐藏或显示项目选项
}
private OnTextViewChangeListener mOnTextViewChangeListener;//新建私有变量:文本改变的监听器
public NoteEditText(Context context) {//根据context设置文本
super(context, null);//用super引用父类变量
mIndex = 0;//设置当前光标
}
public void setIndex(int index) {
mIndex = index;
}//初始化文本修改标记,更新光标指向的索引值
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}//设置文本视图变化监听器
public NoteEditText(Context context, AttributeSet attrs) {//自定义空控件属性,用于维护便签动态变化,这个函数功能为初始化便签
super(context, attrs, android.R.attr.editTextStyle);
}
// public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);\
// TODO Auto-generated constructor stub
}//自定义控件,用于维护便签动态变化的属性。初始化便签
@Override
public boolean onTouchEvent(MotionEvent event) {//view里的函数处理手机屏幕的所有事件。参数event为手机屏幕触摸事件封装类的对象其中封装了该事件的所有信息例如触摸的位置、触摸的类型以及触摸的时间等。该对象会在用户触摸手机屏幕时被创建。
switch (event.getAction()) {//重写屏幕触发事件
case MotionEvent.ACTION_DOWN://更新坐标
int x = (int) event.getX();//更新x值为当前触摸处的x值
int y = (int) event.getY();//更新y值为当前触摸处的y值
x -= getTotalPaddingLeft();//减去左边控件的距离
y -= getTotalPaddingTop();//减去上方控件的距离
x += getScrollX();
y += getScrollY();//加上滚轮滚过的距离
Layout layout = getLayout();//用布局控件layout根据x,y的新值设置新的位置
int line = layout.getLineForVertical(y);//获取纵向行数
int off = layout.getOffsetForHorizontal(line, x);//获取横向偏移量
Selection.setSelection(getText(), off);//更新光标位置
break;
}
return super.onTouchEvent(event);//调用父类当屏幕有Touch事件时此方法就会被调用。
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {//处理用户按下一个键盘按键时会触发 的事件
switch (keyCode) {//根据按键的KeyCode来处理
case KeyEvent.KEYCODE_ENTER://按下回车时,如果mOnTextViewChangeListener存在则返回false
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL://删除按键
mSelectionStartBeforeDelete = getSelectionStart();//获取删除文本开始位置
break;
default://其他情况,返回父类的onKeyDown值
break;
}
return super.onKeyDown(keyCode, event);//继续执行父类的其他点击事件
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {//处理用户松开一个键盘按键时会触发的事件
switch(keyCode) {//根据按键的 Unicode 编码值来处理有删除和进入2种操作
case KeyEvent.KEYCODE_DEL://若触发修改且文档不为空则调用前面代码的onEditTextDelete函数进行文本删除
if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;//利用上文OnTextViewChangeListener对KEYCODE_DEL按键情况的删除函数进行删除
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");//其他情况报错,文档的改动监听器并没有建立
}
break;
case KeyEvent.KEYCODE_ENTER://若文档改动监听器已建立则获取当前位置和文本并根据获取的信息调用onEditTextEnter函数进行文本增添
if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString();//获取选择区域后面的文本信息
setText(getText().subSequence(0, selectionStart));//实现文本换行的功能
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);//将选择区域内的文字移到下一行
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");//其他情况报错监听器OnTextViewChangeListener并没有建立。
}
break;
default:
break;
}
return super.onKeyUp(keyCode, event);//继续执行父类的其他按键弹起的事件
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {//这个函数规定了编辑文本焦点改变时的系统响应
if (mOnTextViewChangeListener != null) {//若监听器已建立
if (!focused && TextUtils.isEmpty(getText())) {//获取到焦点并且文本不为空
mOnTextViewChangeListener.onTextChange(mIndex, false);//置false隐藏事件选项
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);//置true显示事件选项
}
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);//执行父类的其他焦点变化的事件
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {//生成上下文菜单
if (getText() instanceof Spanned) {//若有文本存在
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();////获取文本开始结尾位置
int min = Math.min(selStart, selEnd);
// int max = Math.max(selStart, selEnd);//获取开始到结尾的最大、最小值
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);//设置url的信息的范围值
if (urls.length == 1) {
int defaultResId = 0;// 默认的资源ID值为0
for(String schema: sSchemaActionResMap.keySet()) {//获取计划表中所有的key值
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
break;
}//若url可以添加则在添加后将defaultResId置为key所映射的值
}
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}//defaultResId == 0则说明url并没有添加任何东西所以置为连接其他SchemaActionResMap的值
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(//建立菜单
new OnMenuItemClickListener() {//新建按键监听器
public boolean onMenuItemClick(MenuItem item) {//如果点击菜单执行操作
// goto a new intent
urls[0].onClick(NoteEditText.this);//根据相应的文本设置菜单的按键
return true;
}
});
}
}
super.onCreateContextMenu(menu);//创建文本菜单
}
}

@ -1,223 +0,0 @@
/*
* 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.text.TextUtils;
import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
public class NoteItemData {//便签数据的记录,包括各种常量,参数
static final String [] PROJECTION = new String [] {//将便签id提醒时间背景颜色id创建时间关联桌面挂件修改时间便签数量父文件夹id文件夹id便签的一段内容便签的种类桌面挂件的id桌面挂件的类型的名称放在一个PROJECTION的字符串数组里
NoteColumns.ID,//每个便签的序号ID
NoteColumns.ALERTED_DATE,//提醒日期
NoteColumns.BG_COLOR_ID,//背景颜色的序号id
NoteColumns.CREATED_DATE,//创建日期
NoteColumns.HAS_ATTACHMENT,//是否含有附件
NoteColumns.MODIFIED_DATE,//修改日期
NoteColumns.NOTES_COUNT,//便签数量
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,//文件夹名称或者文本注释内容
NoteColumns.TYPE,//note的种类
NoteColumns.WIDGET_ID,//挂件id
NoteColumns.WIDGET_TYPE,//挂件的类型
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;//PROJECT的字符串名称对应的值
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;//对方ID
private String mSnippet;
private int mType;
private int mWidgetId;//宽度
private int mWidgetType;//宽度形式
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;//判断是否为最后一项
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;//判断文件夹下是否只有一个便签
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;//判断文件夹下是否有多个便签
public NoteItemData(Context context, Cursor cursor) {//初始化NoteItemData,利用光标和context获取的内容
mId = cursor.getLong(ID_COLUMN);//获取指定数据并以type类型传回
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;//判断行列
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);//获得字符串
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(//把每项前的方框符号和✔符号去掉
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = "";//初始化电话号码的信息
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {//如果父文件的id是call_record_folder
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);//使用DataUtils类中定义的函数获取电话号码信息
if (!TextUtils.isEmpty(mPhoneNumber)) {//若mphonenumber里有符合字符串则用contart功能连接
mName = Contact.getContact(context, mPhoneNumber);//通过phonenumber调用getContact利用键值对获取对应的name
if (mName == null) {
mName = mPhoneNumber;//若未保存名字,以号码命名
}
}
}
if (mName == null) {
mName = "";
}//若没有对name复制成功则把name设置为空值
checkPostion(cursor);//检查光标位置
}
private void checkPostion(Cursor cursor) {//根据光标位置设置标记
mIsLastItem = cursor.isLast() ? true : false;//分别为各种描述状态的变量进行赋值
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;//初始化“多重子文件”“单一子文件”2个标记
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {//如果对象的类型为便签且不为第一个项
int position = cursor.getPosition();//获得光标位置
if (cursor.moveToPrevious()) {//如果光标移动
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER//若光标满足SYSTEM或FOLDER格式
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) {//若光标位置大于当前位置,置多便签子文件夹标记为真
mIsMultiNotesFollowingFolder = true;//设置为多重便签
} else {
mIsOneNoteFollowingFolder = true;
}
}
if (!cursor.moveToNext()) {//若光标不能重新向下走则报错
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}//判断是否只有一个便签
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}//若数据父id为保存至文件夹模式的id且满足电话号码单元不为空则isCallRecord为true
public boolean isLast() {
return mIsLastItem;
}//判断是否为最后一个项
public String getCallName() {
return mName;
}//获得便签的姓名
public boolean isFirst() {
return mIsFirstItem;
}//判断是否是第一个项
public boolean isSingle() {
return mIsOnlyOneItem;
}//判断是否只有一个项
public long getId() {
return mId;
}//获得对应的ID值
public long getAlertDate() {
return mAlertDate;
}//获取设置的提醒时间
public long getCreatedDate() {
return mCreatedDate;
}//获取创建时间
public boolean hasAttachment() {
return mHasAttachment;
}//判断是否关联桌面挂件
public long getModifiedDate() {
return mModifiedDate;
}//获得修改后时间
public int getBgColorId() {
return mBgColorId;
}//获取背景颜色
public long getParentId() {
return mParentId;
}//获取父进程id
public int getNotesCount() {
return mNotesCount;
}//获取便签数量
public long getFolderId () {
return mParentId;
}//获取文件夹id
public int getType() {
return mType;
}//获得项的类型
public int getWidgetType() {
return mWidgetType;
}//获取挂件类型
public int getWidgetId() {
return mWidgetId;
}//获取挂件id
public String getSnippet(){
return mSnippet;
}//获取便签的外观片段
public boolean hasAlert() {
return (mAlertDate > 0);
}//判读此便签是否有提醒功能
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}//如果父类id保存至文件夹模式并且电话号码单元不为空
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}//获取便签类型
}

@ -1,954 +0,0 @@
/*
* 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.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
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.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.tool.BackupUtils;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {//在类的声明中通过关键字extends来创建一个类的子类。一个类通过关键字implements声明自己使用一个或者多个接口。
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;//声明并赋值一些不可更改的私有属性
private static final int FOLDER_LIST_QUERY_TOKEN = 1;//查询记号
private static final int MENU_FOLDER_DELETE = 0;//删除菜单文件
private static final int MENU_FOLDER_VIEW = 1;//菜单中的查看文件夹对应值
private static final int MENU_FOLDER_CHANGE_NAME = 2;//修改菜单文件名称功能
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";//第一次使用小米便签时的介绍语句
private enum ListEditState {//列表编辑状态类
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
};
private ListEditState mState;
private BackgroundQueryHandler mBackgroundQueryHandler;//后台疑问处理功能
private NotesListAdapter mNotesListAdapter;//便签列表配适器
private ListView mNotesListView;//主界面的视图
private Button mAddNewNote;//最下方添加便签的按钮
private boolean mDispatch;//是否调度的判断变量
private int mOriginY;//首次触摸时屏幕上的垂直距离y值
private int mDispatchY;//重新调度时的触摸的在屏幕上的垂直距离
private TextView mTitleBar;//子文件夹下标头
private long mCurrentFolderId;//当前文件夹的ID
private ContentResolver mContentResolver;//提供内容分析
private ModeCallback mModeCallBack;//返回调用方法
private static final String TAG = "NotesListActivity";//名称(可用于日志文件调试)
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;//列表滚动速度
private NoteItemData mFocusNoteDataItem;//光标指向的物件的数据内容
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";//用于表明处于非父文件夹的其他文件夹下
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"//用于表明处于父文件夹下(主列表)
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)";
private final static int REQUEST_CODE_OPEN_NODE = 102;//打开某个便签时,创建活动的请求码
private final static int REQUEST_CODE_NEW_NODE = 103;//打开某个便签时,创建活动的请求码
@Override//功能为Activity生命周期开始时调用的函数用来保存读取状态设置界面
protected void onCreate(Bundle savedInstanceState) {//创建类
super.onCreate(savedInstanceState);//引用父类对象
setContentView(R.layout.note_list);//设置内容的视图
initResources();//初始化类的资源
/**
* Insert an introduction when user firstly use this application
*/
setAppInfoFromRawRes();//当用户第一次访问APP时提供相关信息
}
@Override// 代表执行这个方法时,重写并调用了父类的方法
protected void onActivityResult(int requestCode, int resultCode, Intent data) {//返回一些子模块完成的数据交给主Activity处理
if (resultCode == RESULT_OK//当被销毁的活动是打开便签或者新建便签且结果码匹配时,把从编辑界面的光标数据删除
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
mNotesListAdapter.changeCursor(null);
} else {//如果条件不满足则将数据返回给父类即调用父类的onActivityResult()。
super.onActivityResult(requestCode, resultCode, data);//调用父类Activity的onActivityResult方法 将数据返回给父类处理
}
}
private void setAppInfoFromRawRes() {//利用原始资源文件设置APP的相关信息
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);//保存配置参数
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {//判断偏好,增加说明
StringBuilder sb = new StringBuilder();//读取原生资源信息
InputStream in = null;//输入流初始设置为空
try {//使用getResources获取资源后,以openRawResource方法不带后缀的资源文件名打开这个文件。
in = getResources().openRawResource(R.raw.introduction);//加载Welcome to use MIUI notes
if (in != null) {//如果信息不为空
InputStreamReader isr = new InputStreamReader(in);//使用指定的字符集读取字节并将它们解码为字符
BufferedReader br = new BufferedReader(isr);//分配缓冲区读取空间
char [] buf = new char[1024];
int len = 0;
while ((len = br.read(buf)) > 0) {//不断在buf中读取数据放入sb里
sb.append(buf, 0, len);//使用append函数在指定元素的结尾插入内容
}
} else {
Log.e(TAG, "Read introduction file error");//报错,读取文件错误
return;
}
} catch (IOException e) {//IO出错打印异常信息
e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因
return;
} finally {//必然执行部分
if(in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();//输出栈轨迹
}
}
}
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,//创建新便签
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED);
note.setWorkingText(sb.toString());//设置文本数据
if (note.saveNote()) {//若存储条件成立,保存该便签
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();//更新保存note的信息
} else {
Log.e(TAG, "Save introduction note error");
return;
}//若便签保存不成功,则把错误信息打印到日志里
}
}
@Override
protected void onStart() {//代表activity生命周期开始
super.onStart();//调用父类,启动活动
startAsyncNotesListQuery();//同步列表中的便签信息
}
private void initResources() {//初始化资源
mContentResolver = this.getContentResolver();//获取应用程序的数据
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());//动态创建后台请求处理器的实例
mCurrentFolderId = Notes.ID_ROOT_FOLDER;//设置当前文件夹ID是根目录ID
mNotesListView = (ListView) findViewById(R.id.notes_list);//根据R文件中的id值查询到相应的View,然后返回
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false);
mNotesListView.setOnItemClickListener(new OnListItemClickListener());//设置项目点击监听
mNotesListView.setOnItemLongClickListener(this);//设置长按监听器
mNotesListAdapter = new NotesListAdapter(this);//创建便签视图配置器
mNotesListView.setAdapter(mNotesListAdapter);
mAddNewNote = (Button) findViewById(R.id.btn_new_note);//在activity中要获取该按钮
mAddNewNote.setOnClickListener(this);//点击监听
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());//屏幕监听
mDispatch = false;//用于新建便签模块
mDispatchY = 0;//初始y值设置为0
mOriginY = 0;//加载文件夹下的标头资源
mTitleBar = (TextView) findViewById(R.id.tv_title_bar);//加载文件夹下的标头资源
mState = ListEditState.NOTE_LIST;//设置状态为主界面
mModeCallBack = new ModeCallback();//对便签的方法调用,包括删除和移动
}
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {//implements声明自己使用一个或多个接口
private DropdownMenu mDropDownMenu;//下拉菜单
private ActionMode mActionMode;//动作方式
private MenuItem mMoveMenu;//移动菜单
public boolean onCreateActionMode(ActionMode mode, Menu menu) {//根据菜单和动作创建新动作
getMenuInflater().inflate(R.menu.note_list_options, menu);//配置menu的布局
menu.findItem(R.id.delete).setOnMenuItemClickListener(this);//为便签删除模块设定监听器
mMoveMenu = menu.findItem(R.id.move);//获取菜单项目
if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER//若父类id在文件夹中保存或者用户文件数量为零设置移动菜单为不可见否者设为可见
|| DataUtils.getUserFolderCount(mContentResolver) == 0) {
mMoveMenu.setVisible(false);
} else {
mMoveMenu.setVisible(true);
mMoveMenu.setOnMenuItemClickListener(this);//长按某一标签时,执行这个移动到文件夹按键变得可见
}
mActionMode = mode;
mNotesListAdapter.setChoiceMode(true);//进入选择模式
mNotesListView.setLongClickable(false);//关闭长按列表项发生事件功能
mAddNewNote.setVisibility(View.GONE);//隐藏了新增便签按钮
View customView = LayoutInflater.from(NotesListActivity.this).inflate(//设置用户可视化界面
R.layout.note_list_dropdown_menu, null);//加载下拉菜单的布局
mode.setCustomView(customView);
mDropDownMenu = new DropdownMenu(NotesListActivity.this,//创建下拉菜单的实例对象
(Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown);//为view添加dropDownMenu
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) {//点击菜单时,设置为全选并更新菜单
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());//对应下拉菜单里的全选按键
updateMenu();//更新菜单
return true;
}
});
return true;
}
private void updateMenu() {//用于用户在进行了勾选之后,更新列表
int selectedCount = mNotesListAdapter.getSelectedCount();//获取被勾选的条目数量
// Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount);//从原始资源中读取信息更改下拉菜单内容
mDropDownMenu.setTitle(format);//更改标题
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);//全选操作
if (item != null) {//当全选成功,则将“全选”菜单项改为“取消全选”菜单,否则仍保持“全选”菜单项
if (mNotesListAdapter.isAllSelected()) {//如果便签列表适配器处于全选状态,设置为已勾选,并提供取消全选操作;否则设置为未勾选,提供全选操作
item.setChecked(true);//取消全选
item.setTitle(R.string.menu_deselect_all);
} else {
item.setChecked(false);
item.setTitle(R.string.menu_select_all);
}
}
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {//准备活动模式
// TODO Auto-generated method stub
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {//菜单动作触发标记
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(ActionMode mode) {//销毁动作模式,设置便签可见
mNotesListAdapter.setChoiceMode(false);//设置笔记列表适配器选择方式
mNotesListView.setLongClickable(true);//长按操作
mAddNewNote.setVisibility(View.VISIBLE);//设置新建的笔记为可见
}
public void finishActionMode() {
mActionMode.finish();
}//动作模式结束,菜单勾选状态改变
public void onItemCheckedStateChanged(ActionMode mode, int position, long id,//勾选状态改变时,更改勾选标志,更新菜单
boolean checked) {//点击菜单选项触发操作
mNotesListAdapter.setCheckedItem(position, checked);//改变勾选的状态
updateMenu();//更新菜单
}
public boolean onMenuItemClick(MenuItem item) {//判断菜单是否被点击
if (mNotesListAdapter.getSelectedCount() == 0) {// 当勾选数为零时(即未点击),创建文本并显示
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
Toast.LENGTH_SHORT).show();
return true;
}
switch (item.getItemId()) {//根据id号判断是删除还是移动
case R.id.delete://删除菜单项
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);//警告对话框
builder.setTitle(getString(R.string.alert_title_delete));//设置“删除选中的便签”的title
builder.setIcon(android.R.drawable.ic_dialog_alert);//设置提醒删除的图片
builder.setMessage(getString(R.string.alert_message_delete_notes,
mNotesListAdapter.getSelectedCount()));//设置警告对话框的图标
builder.setPositiveButton(android.R.string.ok,//设置否定按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
batchDelete();//执行批量删除操作
}
});
builder.setNegativeButton(android.R.string.cancel, null);//取消按键的视图
builder.show();
break;
case R.id.move://移动便签到文件夹
startQueryDestinationFolders();//开始查询目标文件
break;
default:
return false;
}
return true;
}
}
private class NewNoteOnTouchListener implements OnTouchListener {//触摸便签监听器
public boolean onTouch(View v, MotionEvent event) {//触摸处理函数
switch (event.getAction()) {//事件调用获取行为函数,根据不同动作,对应不同操作
case MotionEvent.ACTION_DOWN: {//若是创建新便签,通过计算调整界面大小
Display display = getWindowManager().getDefaultDisplay();
int screenHeight = display.getHeight();//获取屏幕高度
int newNoteViewHeight = mAddNewNote.getHeight();//获取新增便签的高度
int start = screenHeight - newNoteViewHeight;
int eventY = start + (int) event.getY();
/**
* Minus TitleBar's height
*/
if (mState == ListEditState.SUB_FOLDER) {
eventY -= mTitleBar.getHeight();
start -= mTitleBar.getHeight();
}
/**
* HACKME:When click the transparent part of "New Note" button, dispatch
* the event to the list view behind this button. The transparent part of
* "New Note" button could be expressed by formula y=-0.12x+94Unit:pixel
* and the line top of the button. The coordinate based on left of the "New
* Note" button. The 94 represents maximum height of the transparent part.
* Notice that, if the background of the button changes, the formula should
* also change. This is very bad, just for the UI designer's strong requirement.
*/
if (event.getY() < (event.getX() * (-0.12) + 94)) {
View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1
- mNotesListView.getFooterViewsCount());
if (view != null && view.getBottom() > start
&& (view.getTop() < (start + 94))) {
mOriginY = (int) event.getY();
mDispatchY = eventY;
event.setLocation(event.getX(), mDispatchY);
mDispatch = true;
return mNotesListView.dispatchTouchEvent(event);
}
}
break;
}
case MotionEvent.ACTION_MOVE: {
if (mDispatch) {
mDispatchY += (int) event.getY() - mOriginY;
event.setLocation(event.getX(), mDispatchY);
return mNotesListView.dispatchTouchEvent(event);
}
break;
}
default: {
if (mDispatch) {
event.setLocation(event.getX(), mDispatchY);
mDispatch = false;
return mNotesListView.dispatchTouchEvent(event);
}
break;
}
}
return false;
}
};
private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION;
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
}
private final class BackgroundQueryHandler extends AsyncQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) {
case FOLDER_NOTE_LIST_QUERY_TOKEN:
mNotesListAdapter.changeCursor(cursor);
break;
case FOLDER_LIST_QUERY_TOKEN:
if (cursor != null && cursor.getCount() > 0) {
showFolderListMenu(cursor);
} else {
Log.e(TAG, "Query folder failed");
}
break;
default:
return;
}
}
}
private void showFolderListMenu(Cursor cursor) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder);
final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DataUtils.batchMoveToFolder(mContentResolver,
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
Toast.makeText(
NotesListActivity.this,
getString(R.string.format_move_notes_to_folder,
mNotesListAdapter.getSelectedCount(),
adapter.getFolderName(NotesListActivity.this, which)),
Toast.LENGTH_SHORT).show();
mModeCallBack.finishActionMode();
}
});
builder.show();
}
private void createNewNote() {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
}
private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
if (!isSyncMode()) {
// if not synced, delete notes directly
if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
.getSelectedItemIds())) {
} else {
Log.e(TAG, "Delete notes error, should not happens");
}
} else {
// in sync mode, we'll move the deleted note into the trash
// folder
if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
.getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
Log.e(TAG, "Move notes to trash folder error, should not happens");
}
}
return widgets;
}
@Override
protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {
if (widgets != null) {
for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
updateWidget(widget.widgetId, widget.widgetType);
}
}
}
mModeCallBack.finishActionMode();
}
}.execute();
}
private void deleteFolder(long folderId) {
if (folderId == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Wrong folder id, should not happen " + folderId);
return;
}
HashSet<Long> ids = new HashSet<Long>();
ids.add(folderId);
HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
folderId);
if (!isSyncMode()) {
// if not synced, delete folder directly
DataUtils.batchDeleteNotes(mContentResolver, ids);
} else {
// in sync mode, we'll move the deleted folder into the trash folder
DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
}
if (widgets != null) {
for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
updateWidget(widget.widgetId, widget.widgetType);
}
}
}
}
private void openNode(NoteItemData data) {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, data.getId());
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
}
private void openFolder(NoteItemData data) {
mCurrentFolderId = data.getId();
startAsyncNotesListQuery();
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mState = ListEditState.CALL_RECORD_FOLDER;
mAddNewNote.setVisibility(View.GONE);
} else {
mState = ListEditState.SUB_FOLDER;
}
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mTitleBar.setText(R.string.call_record_folder_name);
} else {
mTitleBar.setText(data.getSnippet());
}
mTitleBar.setVisibility(View.VISIBLE);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_new_note:
createNewNote();
break;
default:
break;
}
}
private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private void showCreateOrModifyFolderDialog(final boolean create) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
showSoftInput();
if (!create) {
if (mFocusNoteDataItem != null) {
etName.setText(mFocusNoteDataItem.getSnippet());
builder.setTitle(getString(R.string.menu_folder_change_name));
} else {
Log.e(TAG, "The long click data item is null");
return;
}
} else {
etName.setText("");
builder.setTitle(this.getString(R.string.menu_create_folder));
}
builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
hideSoftInput(etName);
}
});
final Dialog dialog = builder.setView(view).show();
final Button positive = (Button)dialog.findViewById(android.R.id.button1);
positive.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
hideSoftInput(etName);
String name = etName.getText().toString();
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
Toast.LENGTH_LONG).show();
etName.setSelection(0, etName.length());
return;
}
if (!create) {
if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId())
});
}
} else if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
}
dialog.dismiss();
}
});
if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
}
/**
* When the name edit text is null, disable the positive button
*/
etName.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
} else {
positive.setEnabled(true);
}
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
@Override
public void onBackPressed() {
switch (mState) {
case SUB_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST;
startAsyncNotesListQuery();
mTitleBar.setVisibility(View.GONE);
break;
case CALL_RECORD_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST;
mAddNewNote.setVisibility(View.VISIBLE);
mTitleBar.setVisibility(View.GONE);
startAsyncNotesListQuery();
break;
case NOTE_LIST:
super.onBackPressed();
break;
default:
break;
}
}
private void updateWidget(int appWidgetId, int appWidgetType) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) {
intent.setClass(this, NoteWidgetProvider_2x.class);
} else if (appWidgetType == 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[] {
appWidgetId
});
sendBroadcast(intent);
setResult(RESULT_OK, intent);
}
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) {
menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());
menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);
menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);
menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name);
}
}
};
@Override
public void onContextMenuClosed(Menu menu) {
if (mNotesListView != null) {
mNotesListView.setOnCreateContextMenuListener(null);
}
super.onContextMenuClosed(menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (mFocusNoteDataItem == null) {
Log.e(TAG, "The long click data item is null");
return false;
}
switch (item.getItemId()) {
case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem);
break;
case MENU_FOLDER_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_folder));
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteFolder(mFocusNoteDataItem.getId());
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
break;
case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false);
break;
default:
break;
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if (mState == ListEditState.NOTE_LIST) {
getMenuInflater().inflate(R.menu.note_list, menu);
// set sync or sync_cancel
menu.findItem(R.id.menu_sync).setTitle(
GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
} else if (mState == ListEditState.SUB_FOLDER) {
getMenuInflater().inflate(R.menu.sub_folder, menu);
} else if (mState == ListEditState.CALL_RECORD_FOLDER) {
getMenuInflater().inflate(R.menu.call_record_folder, menu);
} else {
Log.e(TAG, "Wrong state:" + mState);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_new_folder: {
showCreateOrModifyFolderDialog(true);
break;
}
case R.id.menu_export_text: {
exportNoteToText();
break;
}
case R.id.menu_sync: {
if (isSyncMode()) {
if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
GTaskSyncService.startSync(this);
} else {
GTaskSyncService.cancelSync(this);
}
} else {
startPreferenceActivity();
}
break;
}
case R.id.menu_setting: {
startPreferenceActivity();
break;
}
case R.id.menu_new_note: {
createNewNote();
break;
}
case R.id.menu_search:
onSearchRequested();
break;
default:
break;
}
return true;
}
@Override
public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false);
return true;
}
private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... unused) {
return backup.exportToText();
}
@Override
protected void onPostExecute(Integer result) {
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_unmounted));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
} else if (result == BackupUtils.STATE_SUCCESS) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.success_sdcard_export));
builder.setMessage(NotesListActivity.this.getString(
R.string.format_exported_file_location, backup
.getExportedTextFileName(), backup.getExportedTextFileDir()));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
} else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_export));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
}
}
}.execute();
}
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1);
}
private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) {
NoteItemData item = ((NotesListItem) view).getItemData();
if (mNotesListAdapter.isInChoiceMode()) {
if (item.getType() == Notes.TYPE_NOTE) {
position = position - mNotesListView.getHeaderViewsCount();
mModeCallBack.onItemCheckedStateChanged(null, position, id,
!mNotesListAdapter.isSelectedItem(position));
}
return;
}
switch (mState) {
case NOTE_LIST:
if (item.getType() == Notes.TYPE_FOLDER
|| item.getType() == Notes.TYPE_SYSTEM) {
openFolder(item);
} else if (item.getType() == Notes.TYPE_NOTE) {
openNode(item);
} else {
Log.e(TAG, "Wrong note type in NOTE_LIST");
}
break;
case SUB_FOLDER:
case CALL_RECORD_FOLDER:
if (item.getType() == Notes.TYPE_NOTE) {
openNode(item);
} else {
Log.e(TAG, "Wrong note type in SUB_FOLDER");
}
break;
default:
break;
}
}
}
}
private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection:
"(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
null,
Notes.CONTENT_NOTE_URI,
FoldersListAdapter.PROJECTION,
selection,
new String[] {
String.valueOf(Notes.TYPE_FOLDER),
String.valueOf(Notes.ID_TRASH_FOLER),
String.valueOf(mCurrentFolderId)
},
NoteColumns.MODIFIED_DATE + " DESC");
}
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData();
if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
if (mNotesListView.startActionMode(mModeCallBack) != null) {
mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
} else {
Log.e(TAG, "startActionMode fails");
}
} else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
}
}
return false;
}
}

@ -1,184 +0,0 @@
/*
* 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;//引入tools包
import android.content.Context;//导入各种类
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
public class NotesListAdapter extends CursorAdapter {//继承自CursorAdapter它为cursor和ListView提供了连接的桥梁。因此该类为cursor和便签编辑提供了沟通渠道
private static final String TAG = "NotesListAdapter";
private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount;
private boolean mChoiceMode;
public static class AppWidgetAttribute {//表示桌面widget的属性包括编号和类型
public int widgetId;
public int widgetType;
};
public NotesListAdapter(Context context) {//初始化便签链接
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context;
mNotesCount = 0;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {//利用NotesListLtem类创建新布局
return new NotesListItem(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {//将光标指向的数据与创建的视图捆绑起来
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
public void setCheckedItem(final int position, final boolean checked) {//设置勾选框
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
}
public boolean isInChoiceMode() {//判断是否被勾选
return mChoiceMode;
}
public void setChoiceMode(boolean mode) {//重置勾选框
mSelectedIndex.clear();
mChoiceMode = mode;
}
public void selectAll(boolean checked) {//设置全部勾选
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
}
}
}
public HashSet<Long> getSelectedItemIds() {// 获取已经被勾选的项目的id号加入到散列表itemSet中
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
itemSet.add(id);
}
}
}
return itemSet;
}
public HashSet<AppWidgetAttribute> getSelectedWidget() {//获取桌面组件选项表
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {//遍历被选中的列表
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*/
} else {
Log.e(TAG, "Invalid cursor");//设置标签非法的cursor
return null;
}
}
}
return itemSet;
}
public int getSelectedCount() {//获取选项个数
Collection<Boolean> values = mSelectedIndex.values();//获取选项下标的值
if (null == values) {
return 0;
}
Iterator<Boolean> iter = values.iterator();//初始化叠加器
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
}
}
return count;
}
public boolean isAllSelected() {//判断是否全选
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
}
public boolean isSelectedItem(final int position) {//判断是否为选项表
if (null == mSelectedIndex.get(position)) {
return false;
}
return mSelectedIndex.get(position);
}
@Override
protected void onContentChanged() {//在activity发生变化时重新计算便签数量
super.onContentChanged();
calcNotesCount();
}
@Override
public void changeCursor(Cursor cursor) {//光标变动时重新计算便签数量
super.changeCursor(cursor);
calcNotesCount();
}
private void calcNotesCount() {//计算当前界面便签的数量
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {//遍历所有数据
Cursor c = (Cursor) getItem(i);
if (c != null) {//判断语句如果光标不是null那么便得到信息便签数目加1
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {//若选项的数据类型为便签类型,那么计数+1
mNotesCount++;
}
} else {//设置为无效的光标
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}

@ -1,122 +0,0 @@
/*
* 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.text.format.DateUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout {//构建便签列表的各个项目的详细具体信息
private ImageView mAlert;//闹钟图片
private TextView mTitle;//文本标题
private TextView mTime;//时间
private TextView mCallName;//名称
private NoteItemData mItemData;//标签数据
private CheckBox mCheckBox;//勾选框
public NotesListItem(Context context) {//初始化基本信息
super(context);//调整调用父类构造函数的顺序
inflate(context, R.layout.note_item, this);//将xml定义的一个布局找出来
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);//从contentView中查找指定ID的View
mTitle = (TextView) findViewById(R.id.tv_title);//获取题目
mTime = (TextView) findViewById(R.id.tv_time);//获取创建或修改时间
mCallName = (TextView) findViewById(R.id.tv_name);//获取联系人姓名
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);//获取复选框
}
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {//根据data的属性对各个控件的属性的控制
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {//如果当前处于选择模式下且数据类型为便签
mCheckBox.setVisibility(View.VISIBLE);//设置View可见
mCheckBox.setChecked(checked);//设置勾选
} else {
mCheckBox.setVisibility(View.GONE);//设置复选框不可见
}
mItemData = data;//把数据传给标签
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//设置控件属性通过判断保存到文件夹的ID、当前ID以及父ID之间关系决定
mCallName.setVisibility(View.GONE);//设置联系人名字不可见
mAlert.setVisibility(View.VISIBLE);//设置闹钟图标可见
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);//设置外观风格
mTitle.setText(context.getString(R.string.call_record_folder_name)//设置标题内容为文件夹名字、文件数和便签数
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);//设置图片来源
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {//关于闹钟的设置
mCallName.setVisibility(View.VISIBLE);//设置联系人姓名可见
mCallName.setText(data.getCallName());//设置联系人姓名的文本内容
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);//设置title文本风格
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));//设置title的文本内容为便签内容的前面片段
if (data.hasAlert()) {//如果时间提醒存在,设置图片来源,将时间提醒图标定为可见
mAlert.setImageResource(R.drawable.clock);//图片来源的设置
mAlert.setVisibility(View.VISIBLE);//将提醒图标设置为可见
} else {//否则将提醒图标设置为不可见
mAlert.setVisibility(View.GONE);
}
} else {//如果父类和当前id均与保存在文件夹中的id不同
mCallName.setVisibility(View.GONE);//设置联系人姓名不可见
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);//设置title的文本格式
if (data.getType() == Notes.TYPE_FOLDER) {//设置Type格式
mTitle.setText(data.getSnippet()//设置便签标题内容为便签的前面部分的内容+文件数+便签数
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));//设置内容从data编辑的日期中获取时间
mAlert.setVisibility(View.GONE);//设置时间提醒图标为不可见
} else {//如果不是文件夹类型,设置便签的title为便签内容的前面片段
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {//若当前便签存在提醒闹钟时间,则显示相应的图片
mAlert.setImageResource(R.drawable.clock);//将提醒图标设置为闹钟样式
mAlert.setVisibility(View.VISIBLE);//设置提醒闹钟可见
} else {//否则设置提醒图标不可见
mAlert.setVisibility(View.GONE);
}
}
}
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));//将时间设置为编辑便签的时间
setBackground(data);//从data里编辑的日期中获取内容和相关时间
}
private void setBackground(NoteItemData data) {//根据data的文件属性来设置背景
int id = data.getBgColorId();//获取id用此id用来获取背景颜色
if (data.getType() == Notes.TYPE_NOTE) {//根据data的属性来是否为Note属性分为4种情况
if (data.isSingle() || data.isOneFollowingFolder()) {//单个数据或只有一个子文件夹
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));//设置背景来源为id的单个数据
} else if (data.isLast()) {//若当前便签为最后一个,设置背景来源为id的最后一个数据
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {//若是第一个数据或者有很多个子文件夹, 设置背景来源为id的第一个数据
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));//将便签设置为普通类型便签的背景
}
} else {//则将背景设置为文件夹的背景
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
public NoteItemData getItemData() {
return mItemData;
}//返回当前便签的数据信息
}

@ -1,389 +0,0 @@
/*
* 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.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
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.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity {//实现对背景颜色和字体大小的数据储存
public static final String PREFERENCE_NAME = "notes_preferences";//优先名
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";//同步账号
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";//同步时间
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";//背景颜色设置按键
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";//账户同步密码
private static final String AUTHORITIES_FILTER_KEY = "authorities";//本地密码
private PreferenceCategory mAccountCategory;//账户分组
private GTaskReceiver mReceiver;//同步任务接收器
private Account[] mOriAccounts;//账户
private boolean mHasAddedAccount;//账户的hash标记
@Override
protected void onCreate(Bundle icicle) {//创建一个activity在函数里完成所有的正常静态设置
super.onCreate(icicle);//执行父类创建函数
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);//给左上角图标的左边加上一个返回的图标
addPreferencesFromResource(R.xml.preferences);//从资源里添加布局文件
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);//根据同步账户密码进行账户分组
mReceiver = new GTaskReceiver();//设置同步任务接收器
IntentFilter filter = new IntentFilter();//设置过滤项
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);//
registerReceiver(mReceiver, filter);
mOriAccounts = null;//初始化同步组件
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);//从xml获取Listview
getListView().addHeaderView(header, null, true);//列出所有选择
}
@Override//功能描述:重启活动
protected void onResume() {
super.onResume();//activity交互功能的实现用于接受用户的输入
// need to set sync account automatically if user has added a new
// account
if (mHasAddedAccount) {//若用户新加了账户则自动设置同步账户
Account[] accounts = getGoogleAccounts();//获取google同步账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {//若原账户不为空且当前账户有增加
for (Account accountNew : accounts) {//遍历账户
boolean found = false;//更新账户
for (Account accountOld : mOriAccounts) {//循环判断当前账户列表中的账户是否与新建账户名相同
if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true;
break;
}//若没找到旧账户则只设置新账户为同步账户
}
if (!found) {//如果当前新建账户不存在
setSyncAccount(accountNew.name);//保存该账户
break;
}
}
}
}
refreshUI();//刷新标签界面
}
@Override//功能描述:销毁活动
protected void onDestroy() {//销毁Activity
if (mReceiver != null) {
unregisterReceiver(mReceiver);//取消广播器的监听
}//销毁接收器
super.onDestroy();//执行销毁动作
}
private void loadAccountPreference() {//重新设置账户信息
mAccountCategory.removeAll();//销毁所有的分组
Preference accountPref = new Preference(this);//建立首选项
final String defaultAccount = getSyncAccountName(this);//默认账户为当前账户
accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {//设置首选项的大标题和小标题
public boolean onPreferenceClick(Preference preference) {//建立监听器
if (!GTaskSyncService.isSyncing()) {//不在同步状态下,如果没有默认的账户,显示选择账户的对话框,否则显示需要改变账户的对话框
if (TextUtils.isEmpty(defaultAccount)) {//第一次设置账户
// the first time to set account
showSelectAccountAlertDialog();//第一次建立账户,显示选择账户提示对话框
} else {
// if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog();//展示改变账户确认提醒对话框
}
} else {//若在没有同步的情况下则在toast中显示不能修改
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();//正在同步,不能切换同步的账号
}
return true;
}
});
mAccountCategory.addPreference(accountPref);//根据新建首选项编辑新的账户分组
}
private void loadSyncButton() {//设置同步按键和最近同步时间
Button syncButton = (Button) findViewById(R.id.preference_sync_button);//配置资源设置一个button
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
//获取同步按钮控件和最终同步时间的的窗口
// set button state
if (GTaskSyncService.isSyncing()) {//如果在同步状态下,则按钮设置为“取消同步”
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {//设置点击监听器
public void onClick(View v) {//设置取消同步的响应方法
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else {//若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {//点击行为
GTaskSyncService.startSync(NotesPreferenceActivity.this);//开始同步
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));//如果没有账户,则不可选“立即同步”的按键
// set last sync time设置上次同步时间
if (GTaskSyncService.isSyncing()) {//如果正在同步则读取正在同步的进度,否则显示最后同步的时间
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {//若是非同步情况
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {//若最近同步时间不为0则显示最近同步时间
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {//若时间为空直接设置为不可见状态
lastSyncTimeView.setVisibility(View.GONE);
}
}
}//根据当前同步服务器设置时间显示框的文本以及可见性
private void refreshUI() {//刷新标签界面
loadAccountPreference();
loadSyncButton();//加载“保存”按钮
}
private void showSelectAccountAlertDialog() {//显示账户选择的对话框并进行账户的设置
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);//文本视图设置
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);//设置标题以及子标题的内容
dialogBuilder.setPositiveButton(null, null);//不设置“确定”的按钮
Account[] accounts = getGoogleAccounts();//获取当前谷歌账户
String defAccount = getSyncAccountName(this);//获得同步账户
mOriAccounts = accounts;
mHasAddedAccount = false;//获取同步账户信息
if (accounts.length > 0) {//如果有谷歌账户,则显示所有账户的名称,并设置为选项
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
int checkedItem = -1;
int index = 0;
for (Account account : accounts) {//通过循环检查账户列表
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
}//在账户列表中查询到所需账户
items[index++] = account.name;
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,//在对话框建立一个单选的复选框
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {//响应对话框的点击
setSyncAccount(itemMapping[which].toString());//点击则开始设置同步账户
dialog.dismiss();//取消对话框
refreshUI();//刷新界面
}
});
}//设置点击后执行的事件,包括检录新同步账户和刷新标签界面
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);//添加新的账户
dialogBuilder.setView(addAccountView);//给新加账户对话框设置自定义样式
final AlertDialog dialog = dialogBuilder.show();//显示对话框
addAccountView.setOnClickListener(new View.OnClickListener() {//设置监听器
public void onClick(View v) {//响应点击添加账户的请求
mHasAddedAccount = true;//将新加账户的hash置为true
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");//建立网络组件
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
});
startActivityForResult(intent, -1);//跳回上一个选项
dialog.dismiss();
}
});
}
private void showChangeAccountConfirmAlertDialog() {//刷新标签界面
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);//根据同步修改的账户信息设置标题以及子标题的内容
CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel)
};//设置对话框的自定义标题
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {//定义一些标记字符串
public void onClick(DialogInterface dialog, int which) {//响应对话框的点击
if (which == 0) {//如果是改变同步账户,则显示可选择的账户
showSelectAccountAlertDialog();
} else if (which == 1) {
removeSyncAccount();
refreshUI();
}//删除同步账户
}
});
dialogBuilder.show();//显示对话框
}
private Account[] getGoogleAccounts() {//获取谷歌账户
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
private void setSyncAccount(String account) {//设置同步账户
if (!getSyncAccountName(this).equals(account)) {//如果该账号不在同步账号列表中
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();//编辑共享首选项
if (account != null) {//如果账户不为空
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}//将该账号加入到首选项中
editor.commit();//提交修改的数据
// clean up last sync time
setLastSyncTime(this, 0);//将最后同步时间清零
// clean up local gtask related info
new Thread(new Runnable() {//新线程的创建
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}//清除本地的gtask关联的信息
}).start();//重置当地同步任务的信息
Toast.makeText(NotesPreferenceActivity.this,//设置一个toast提示信息提示用户成功设置同步
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();//将toast的文本信息置为“设置账户成功”并显示出来
}
}
private void removeSyncAccount() {//删除同步账户
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);//存放数据和读取数据
SharedPreferences.Editor editor = settings.edit();//设置共享首选项
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}//若当前首选项中有账户就删除
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
}//删除当前首选项中有账户时间
editor.commit();//提交更新后的数据
// clean up local gtask related info
new Thread(new Runnable() {//新线程的创建
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}//清除本地的gtask关联的信息将一些参数设置为0或NULL
}).start();
}
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}//获取同步账户名称
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();//从共享首选项中找到相关账户并获取其编辑器
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();//编辑最终同步时间并提交更新
}//设置最终同步的时间
public static long getLastSyncTime(Context context) {//获取最终同步时间
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);//通过共享,获取时间
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
private class GTaskReceiver extends BroadcastReceiver {//接受同步信息
@Override
public void onReceive(Context context, Intent intent) {//响应接收广播的情况
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));////通过获取的数据在设置系统的状态
}//获取随广播而来的Intent中的同步服务的数据
}
}
public boolean onOptionsItemSelected(MenuItem item) {//处理菜单的选项
switch (item.getItemId()) {//根据选项的id选择
case android.R.id.home://返回主界面
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);//创建活动
return true;
default://在主页情况下在创建连接组件intent发出清空的信号并开始一个相应的activity
return false;
}
}
}

@ -1,136 +0,0 @@
/*
* 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();//获取小部件的类型
}

@ -1,47 +0,0 @@
/*
* 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() 方法,返回小部件的类型

@ -1,46 +0,0 @@
/*
* 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
Loading…
Cancel
Save