branch_chen
chenwenjie 7 months ago
parent 2a8e049f64
commit 75b1149c08

Binary file not shown.

@ -1,284 +0,0 @@
这段代码主要是定义了一个节点类 Node其中包含了一些常量、成员变量和方法用于表示节点的属性和同步操作。
package net.micode.notes.gtask.data; //指定了该类所在的java包为gtask.data
import android.database.Cursor; //导入了 Android 框架中的 Cursor 类,用于在数据库中进行数据检索。
import org.json.JSONObject; //导入了 JSON 库中的 JSONObject 类,用于处理 JSON 数据。
public abstract class Node { //定义了一个抽象类 Node表示一个节点。
public static final int SYNC_ACTION_NONE = 0;
//定义了一个名为 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; //声明了一个私有成员变量 mGid用于存储节点的全局唯一标识符。
private String mName; //声明了一个私有成员变量 mName用于存储节点的名称。
private long mLastModified; //声明了一个私有成员变量 mLastModified用于存储节点的最后修改时间。
private boolean mDeleted; //声明了一个私有成员变量 mDeleted用于表示节点是否被删除。
public Node() { //定义了 Node 类的构造函数,初始化成员变量。
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
}
public abstract JSONObject getCreateAction(int actionId);
//声明了一个抽象方法 getCreateAction(),用于获取创建节点的同步操作。
public abstract JSONObject getUpdateAction(int actionId);
//声明 getUpdateAction(),用于获取更新节点的同步操作。
public abstract void setContentByRemoteJSON(JSONObject js);
//声明 setContentByRemoteJSON(),用于根据远程 JSON 数据设置节点内容。
public abstract void setContentByLocalJSON(JSONObject js);
//声明了 setContentByLocalJSON(),用于根据本地 JSON 数据设置节点内容。
public abstract JSONObject getLocalJSONFromContent();
//声明了一个抽象方法 getLocalJSONFromContent(),用于从节点内容获取本地 JSON 数据。
public abstract int getSyncAction(Cursor c);
//声明了一个抽象方法 getSyncAction(),用于从 Cursor 中获取同步操作。
public void setGid(String gid) { //定义了一个公有方法 setGid(),用于设置节点的全局唯一标识符。
this.mGid = gid;
}
public void setName(String name) { //定义了一个公有方法 setName(),用于设置节点的名称。
this.mName = name;
}
public void setLastModified(long lastModified) { //定义了一个公有方法 setLastModified(),用于设置节点的最后修改时间。
this.mLastModified = lastModified;
}
public void setDeleted(boolean deleted) { //定义了一个公有方法 setDeleted(),用于设置节点是否被删除。
this.mDeleted = deleted;
}
public String getGid() { //定义了一个公有方法 getGid(),用于获取节点的全局唯一标识符。
return this.mGid;
}
public String getName() { //定义了一个公有方法 getName(),用于获取节点的名称。
return this.mName;
}
public long getLastModified() { //定义了一个公有方法 getLastModified(),用于获取节点的最后修改时间。
return this.mLastModified;
}
public boolean getDeleted() { //定义了一个公有方法 getDeleted(),用于获取节点是否被删除。
return this.mDeleted;
}
}
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;
//以上import导入了所需的Android类和自定义异常以及用于处理JSON数据的类。
public class SqlData { //定义了一个名为 SqlData 的类。
private static final String TAG = SqlData.class.getSimpleName();
//声明了一个私有静态常量 TAG用于在日志中标识类的名称。
private static final int INVALID_ID = -99999;
//声明了一个私有静态常量 INVALID_ID用于表示无效的ID值。
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
}; //这是一个字符串数组 PROJECTION_DATA用于指定要在查询数据时返回的列。
public static final int DATA_ID_COLUMN = 0;
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;
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 类的构造函数,接受一个 Context 参数。
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();
} //在第二个构造函数中对成员变量进行初始化,并调用 loadFromCursor() 方法加载数据。
private void loadFromCursor(Cursor c) { //定义了一个私有方法 loadFromCursor(),接受一个 Cursor 参数。
mDataId = c.getLong(DATA_ID_COLUMN);
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);
} //从 Cursor 中读取数据,并将其存储到相应的成员变量中。
public void setContent(JSONObject js) throws JSONException {
//定义了一个公有方法 setContent(),接受一个 JSONObject 参数,并可能抛出 JSONException 异常。
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
mDataId = dataId;
//从 JSON 对象中读取数据,并将其存储到相应的成员变量中。
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: 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)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}
mDataContent = dataContent;
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.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;
} //从 JSON 对象中读取数据,并将其存储到相应的成员变量中。
public JSONObject getContent() throws JSONException { //定义了一个公有方法 getContent(),可能抛出 JSONException 异常。
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
JSONObject js = new 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;
} //根据成员变量的值创建一个 JSON 对象,并返回
public void commit(long noteId, boolean validateVersion, long version) { //定义了一个公有方法 commit(),接受三个参数。
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
}
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try {
mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
} else {
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {
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;
}
//清除变更数据并将 mIsCreate 设置为 false。
public long getId() {
return mDataId;
}
}

@ -1,96 +0,0 @@
**********************MetaData***********
/*
* 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; //处理数据库查询的Cursor类
import android.util.Log; //日志记录类Log
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class MetaData extends Task //声明MetaData类这个类extends了Task类即继承了Task类的所有属性和方法
{
private final static String TAG = MetaData.class.getSimpleName();
//定义了一个私有静态常量字符串 TAG用于标识日志记录的来源。TAG 的值是 MetaData 类的简单名称
private String mRelatedGid = null;
//声明了一个私有字符串变量 mRelatedGid用于存储关联的 GIDGoogle 任务 ID
public void setMeta(String gid, JSONObject metaInfo) {
//定义了一个公共方法 setMeta接受两个参数一个字符串 gid 和一个 JSONObject metaInfo
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
}
//通过调用 JSONObject 的 put 方法,将 GID 存储到传入的 metaInfo 中。如果出现 JSON 解析异常则记录错误日志failed to put related gid
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);
}
//然后,将转换后的 metaInfo 对象转换为字符串并将其设置为任务的注释notes同时设置任务的名称为预定义的 META_NOTE_NAME。
public String getRelatedGid() {
return mRelatedGid; //定义公共方法 getRelatedGid用于获取关联的 GID
}
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
//重写了父类的方法 isWorthSaving用于判断任务是否值得保存。如果任务的注释不为 null则返回 true
@Override
public void setContentByRemoteJSON(JSONObject js) {
//重写了父类的方法 setContentByRemoteJSON用于从远程 JSON 数据设置任务的内容
super.setContentByRemoteJSON(js); //首先调用父类的方法来设置任务的内容
if (getNotes() != null) {
try {
JSONObject metaInfo = new JSONObject(getNotes().trim());
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}
} //然后,从任务的注释中提取关联的 GID如果提取失败则记录警告日志"failed to get related gid"
}
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
//重写了父类的方法 setContentByLocalJSON但是抛出了一个非法访问错误表示这个方法不应该被调用
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
//重写了父类的方法 getLocalJSONFromContent也抛出了一个非法访问错误。
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}
//重写了父类的方法 getSyncAction同样抛出了一个非法访问错误。
}

@ -1,68 +0,0 @@
@startuml
'https://plantuml.com/class-diagram
public class Contact {
// 缓存联系人信息,键为电话 号码,值为联系人姓名
private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact";
// 定义字符串CALLER_ID_SELECTION
// 用于查询联系人信息的选择条件
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
// 获取联系人姓名
public static String getContact(Context context, String phoneNumber) {
// 如果联系人缓存为空,进行初始化
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 如果缓存中已包含该电话号码对应的联系人姓名,则直接返回姓名
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
// 构建查询条件
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 查询联系人信息
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
// 处理查询结果
// moveToFirst()返回第一条
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取联系人姓名
String name = cursor.getString(0);
// 将姓名加入缓存
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
// 捕获异常,记录错误日志
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close();
}
} else {
// 如果没有找到匹配的联系人,记录日志并返回空
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}
@enduml

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="SonarLintModuleSettings">
<option name="uniqueId" value="b8be3ba6-ba63-47ff-8a14-cf8ffb550ccb" />
</component>
</module>

@ -14,10 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.data; package net.micode.notes.data;//包
import android.content.Context; //导入所需的类
import android.database.Cursor; import android.database.Cursor; //处理数据库查询的Cursor类
import android.util.Log; //日志记录类Log
import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils; import android.telephony.PhoneNumberUtils;

@ -16,7 +16,6 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.app.SearchManager; import android.app.SearchManager;
import android.content.ContentProvider; import android.content.ContentProvider;
import android.content.ContentUris; import android.content.ContentUris;
@ -33,17 +32,21 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns; import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据
//ContentProvider提供的方法
//query查询
//insert插入
//update更新
//delete删除
//getType得到数据类型
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
// UriMatcher用于匹配Uri
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper; private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
private static final String URL = "Unknown URI ";
private static final int URI_NOTE = 1; private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2; private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3; private static final int URI_DATA = 3;
@ -53,7 +56,9 @@ public class NotesProvider extends ContentProvider {
private static final int URI_SEARCH_SUGGEST = 6; private static final int URI_SEARCH_SUGGEST = 6;
static { static {
// 创建UriMatcher时调用UriMatcher(UriMatcher.NO_MATCH)表示不匹配任何路径的返回码
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 把需要匹配Uri路径全部给注册上
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
@ -67,33 +72,40 @@ public class NotesProvider extends ContentProvider {
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * 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. * we will trim '\n' and white space in order to show more information.
*/ */
// 声明 NOTES_SEARCH_PROJECTION
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + 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 + "," + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 声明NOTES_SNIPPET_SEARCH_QUERY
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override @Override
// Context只有在onCreate()中才被初始化
// 对mHelper进行实例化
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
@Override @Override
// 查询uri在数据库中对应的位置
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
Cursor c = null; Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
// 匹配查找uri
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
// 对于不同的匹配值,在数据库中查找相应的条目
case URI_NOTE: case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
@ -115,6 +127,7 @@ public class NotesProvider extends ContentProvider {
case URI_SEARCH: case URI_SEARCH:
case URI_SEARCH_SUGGEST: case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
// 不合法的参数异常
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
} }
@ -122,6 +135,8 @@ public class NotesProvider extends ContentProvider {
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
// getPathSegments()方法得到一个String的List
// 在uri.getPathSegments().get(1)为第2个元素
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1);
} }
} else { } else {
@ -141,7 +156,8 @@ public class NotesProvider extends ContentProvider {
} }
break; break;
default: default:
throw new IllegalArgumentException(URL+ uri); // 抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (c != null) { if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); c.setNotificationUri(getContext().getContentResolver(), uri);
@ -150,13 +166,17 @@ public class NotesProvider extends ContentProvider {
} }
@Override @Override
// 插入一个uri
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0; long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
// 新增一个条目
case URI_NOTE: case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break; break;
// 如果存在查找NOTE_ID
case URI_DATA: case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
@ -166,9 +186,10 @@ public class NotesProvider extends ContentProvider {
insertedId = dataId = db.insert(TABLE.DATA, null, values); insertedId = dataId = db.insert(TABLE.DATA, null, values);
break; break;
default: default:
throw new IllegalArgumentException(URL + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri // Notify the note uri
// notifyChange获得一个ContextResolver对象并且更新里面的内容
if (noteId > 0) { if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
@ -180,13 +201,17 @@ public class NotesProvider extends ContentProvider {
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
// 返回插入的uri的路径
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId);
} }
@Override @Override
// 删除一个uri
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
//Uri代表要操作的数据Android上可用的每种资源 -包括 图像、视频片段、音频资源等都可以用Uri来表示。
int count = 0; int count = 0;
String id = null; String id = null;
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false; boolean deleteData = false;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
@ -230,6 +255,7 @@ public class NotesProvider extends ContentProvider {
} }
@Override @Override
// 更新一个uri
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
@ -269,10 +295,12 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
// 将字符串解析成规定格式
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
} }
//增加一个noteVersion
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
@ -285,7 +313,7 @@ public class NotesProvider extends ContentProvider {
sql.append(" WHERE "); sql.append(" WHERE ");
} }
if (id > 0) { if (id > 0) {
sql.append(NoteColumns.ID + "=" + id); sql.append(NoteColumns.ID + "=" + String.valueOf(id));
} }
if (!TextUtils.isEmpty(selection)) { if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection; String selectString = id > 0 ? parseSelection(selection) : selection;
@ -295,6 +323,7 @@ public class NotesProvider extends ContentProvider {
sql.append(selectString); sql.append(selectString);
} }
// execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString());
} }

@ -16,19 +16,22 @@
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; //导入所需的类
import android.util.Log; import android.database.Cursor; //处理数据库查询的Cursor类
import android.util.Log; //日志记录类Log
import net.micode.notes.tool.GTaskStringUtils; import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
//声明MetaData类这个类extends了Task类即继承了Task类的所有属性和方法
public class MetaData extends Task { public class MetaData extends Task {
private static final String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName();
//定义了一个私有静态常量字符串 TAG用于标识日志记录的来源。TAG 的值是 MetaData 类的简单名称
private String mRelatedGid = null; private String mRelatedGid = null;
//声明了一个私有字符串变量 mRelatedGid用于存储关联的 GIDGoogle 任务 ID
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {

@ -16,7 +16,7 @@
*/ */
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
//异步操作类实现GTask的异步操作过程
import android.app.Notification; import android.app.Notification;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
@ -56,13 +56,13 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
// 发布进度单位系统将会调用onProgressUpdate()方法更新这些值
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
} }
//向用户提示当前同步的状态,是一个用于交互的方法
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis()); .getString(tickerId), System.currentTimeMillis());
@ -72,32 +72,32 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); NotesPreferenceActivity.class), 0);
// 调用系统自带灯光
} else { } else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); NotesListActivity.class), 0);
} }// 点击清除按钮或点击通知后会自动消失
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent); pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
//一个描述了想要启动一个Activity、Broadcast或是Service的意图
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
//用于在执行完后台任务后更新UI,显示结果
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {//设置最新同步的时间
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
} }
//如果同步不成功那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象
@Override @Override//几种不同情况下的结果显示
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
@ -110,11 +110,11 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled));
} }//这里好像是方法内的一个线程,但是并不太懂什么意思
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {//完成后的操作使用onComplete()将所有值都重新初始化,相当于完成一次操作
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete();
} }
}).start(); }).start();

@ -1,70 +1,13 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.accounts.Account; /*
import android.accounts.AccountManager; * GTASKGTASK
import android.accounts.AccountManagerFuture; * 使accountManager JSONObject HttpParams authToken Gid
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 { public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/"; //这个是指定的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
@ -102,6 +45,10 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
/*
* 使 getInstance()
* mInstance
*/
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -109,42 +56,50 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
/*Activity
*
* 使URL使URL
* truefalse
*/
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // we suppose that the cookie would expire after 5 minutes
// then we need to re-login // then we need to re-login
final long interval = 1000 * 60 * 5; //判断距离最后一次登录操作是否超过5分钟
final long interval = 1000 * 60 * 5; //1000毫秒×60×5
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// need to re-login after account switch // need to re-login after account switch 重新登录操作
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
//如果没超过时间,则不需要重新登录
if (mLoggedin) { if (mLoggedin) {
Log.d(TAG, "already logged in"); Log.d(TAG, "already logged in");
return true; return true;
} }
mLastLoginTime = System.currentTimeMillis(); mLastLoginTime = System.currentTimeMillis();//更新最后登录时间,改为系统当前的时间
String authToken = loginGoogleAccount(activity, false); String authToken = loginGoogleAccount(activity, false);//判断是否登录到谷歌账户
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false;
} }
// login with custom domain if necessary // login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() //尝试使用用户自己的域名登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() //将用户账号名改为统一格式(小写)后判断是否为一个谷歌账号地址
.endsWith("googlemail.com"))) { .endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index);
url.append(suffix + "/"); url.append(suffix + "/");
mGetUrl = url.toString() + "ig"; mGetUrl = url.toString() + "ig"; //设置用户对应的getUrl
mPostUrl = url.toString() + "r/ig"; mPostUrl = url.toString() + "r/ig"; //设置用户对应的postUrl
if (tryToLoginGtask(activity, authToken)) { if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true; mLoggedin = true;
@ -152,6 +107,7 @@ public class GTaskClient {
} }
// try to login with google official url // try to login with google official url
//如果用户账户无法登录则使用谷歌官方的URI进行登录
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -164,10 +120,15 @@ public class GTaskClient {
return true; return true;
} }
/*
* 使
* 使AccountManager
*
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken; //令牌,是登录操作保证安全性的一个方法
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);//AccountManager这个类给用户提供了集中注册账号的接口
Account[] accounts = accountManager.getAccountsByType("com.google"); Account[] accounts = accountManager.getAccountsByType("com.google");//获取全部以com.google结尾的account
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account");
@ -176,6 +137,7 @@ public class GTaskClient {
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null; Account account = null;
//遍历获得的accounts信息寻找已经记录过的账户信息
for (Account a : accounts) { for (Account a : accounts) {
if (a.name.equals(accountName)) { if (a.name.equals(accountName)) {
account = a; account = a;
@ -190,11 +152,13 @@ public class GTaskClient {
} }
// get the token now // get the token now
//获取选中账号的令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
try { try {
Bundle authTokenBundle = accountManagerFuture.getResult(); Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
//如果是invalidateToken那么需要调用invalidateAuthToken(String, String)方法废除这个无效token
if (invalidateToken) { if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken); accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false); loginGoogleAccount(activity, false);
@ -207,10 +171,12 @@ public class GTaskClient {
return authToken; return authToken;
} }
//尝试登陆Gtask这只是一个预先判断令牌是否是有效以及是否能登上GTask的方法,而不是具体实现登陆的方法
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the // maybe the auth token is out of authTokedate, now let's invalidate the
// token and try again // token and try again
//删除过一个无效的authToken申请一个新的后再次尝试登陆
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
@ -225,25 +191,27 @@ public class GTaskClient {
return true; return true;
} }
//实现登录GTask的具体操作
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000; //socket是一种通信连接实现数据的交换的端口
HttpParams httpParameters = new BasicHttpParams(); HttpParams httpParameters = new BasicHttpParams(); //实例化一个新的HTTP参数类
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//设置连接超时时间
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);//设置设置端口超时时间
mHttpClient = new DefaultHttpClient(httpParameters); mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); BasicCookieStore localBasicCookieStore = new BasicCookieStore(); //设置本地cookie
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask // login gtask
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken; //设置登录的url
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl); //通过登录的uri实例化网页上资源的查找
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the cookie now // get the cookie now
//获取CookieStore里存放的cookie,看如果存有“GTL(不知道什么意思)”则说明有验证成功的有效的cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -256,6 +224,7 @@ public class GTaskClient {
} }
// get the client version // get the client version
//获取client的内容具体操作是在返回的Content中截取从_setup(开始到)}</script>中间的字符串内容也就是gtask_url的内容
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -284,6 +253,10 @@ public class GTaskClient {
return mActionId++; return mActionId++;
} }
/*
* 使HttpPost
* httpPost
*/
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,29 +264,30 @@ public class GTaskClient {
return httpPost; return httpPost;
} }
/*URL
* 使getContentEncoding()
*
*/
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {//通过URL得到HttpEntity对象如果不为空则使用getContent方法创建一个流将数据从网络都过来
contentEncoding = entity.getContentEncoding().getValue(); contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding); Log.d(TAG, "encoding: " + contentEncoding);
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {//GZIP是使用DEFLATE进行压缩数据的另一个压缩库
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent()); input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {//DEFLATE是一个无专利的压缩算法它可以实现无损数据压缩
Inflater inflater = new Inflater(true); Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater); input = new InflaterInputStream(entity.getContent(), inflater);
} }
try {
InputStreamReader isr = new InputStreamReader(input); InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr);//是一个包装类,它可以包装字符流,将字符流放入缓存里,先把字符读到缓存里,到缓存满了时候,再读入内存,是为了提供读的效率而设计的
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
try {
while (true) { while (true) {
String buff = br.readLine(); String buff = br.readLine();
if (buff == null) { if (buff == null) {
@ -326,20 +300,28 @@ public class GTaskClient {
} }
} }
/*JSON
* jsonjs
* UrlEncodedFormEntity entityhttpPost.setEntity(entity)jshttpPost
* 使getResponseContent
* json
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {//未登录
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in"); throw new ActionFailureException("not logged in");
} }
//实例化一个httpPost的对象用来向服务器传输数据在这里就是发送请求而请求的内容在js里
HttpPost httpPost = createHttpPost(); HttpPost httpPost = createHttpPost();
try { try {
LinkedList<BasicNameValuePair> list = new LinkedList<>(); LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString())); list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); //UrlEncodedFormEntity()的形式比较单一,是普通的键值对
httpPost.setEntity(entity); httpPost.setEntity(entity);
// execute the post // execute the post
//执行这个请求
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString); return new JSONObject(jsString);
@ -363,6 +345,12 @@ public class GTaskClient {
} }
} }
/*
* .gtask.data.TaskTask
* jsonTask,jsPost
* postRequest
* 使task.setGidtasknew_ID
*/
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -389,6 +377,9 @@ public class GTaskClient {
} }
} }
/*
* createTasktasklistgid
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -415,6 +406,11 @@ public class GTaskClient {
} }
} }
/*
*
* 使JSONObject使jsPost.putPutUpdateArrayClientVersion
* 使postRequestjspost,
*/
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
@ -436,6 +432,10 @@ public class GTaskClient {
} }
} }
/*
*
* commitUpdate()
*/
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // too many update items may result in an error
@ -450,6 +450,12 @@ public class GTaskClient {
} }
} }
/*
* task,tasktask
* getGidtaskgid
* JSONObject.put(String name, Object value)task
* postRequest
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
@ -466,15 +472,17 @@ public class GTaskClient {
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and // put prioring_sibing_id only if moving within the tasklist and
// it is not the first one // it is not the first one
//设置优先级ID只有当移动是发生在文件中
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); //设置移动前所属列表
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); //设置当前所属列表
if (preParent != curParent) { if (preParent != curParent) {
// put the dest_list only if moving between tasklists // put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action); actionList.put(action);
//最后将ACTION_LIST加入到jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // client_version
@ -489,6 +497,11 @@ public class GTaskClient {
} }
} }
/*
*
* JSON
* 使postRequest
*/
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -497,7 +510,7 @@ public class GTaskClient {
// action_list // action_list
node.setDeleted(true); node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId())); actionList.put(node.getUpdateAction(getActionId())); //这里会获取到删除操作的ID加入到actionLiast中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version // client_version
@ -512,6 +525,11 @@ public class GTaskClient {
} }
} }
/*
*
* GetURI使getResponseContent
* "_setup(")}</script>GTASK_JSON_LISTS
*/
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -524,6 +542,7 @@ public class GTaskClient {
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the task list // get the task list
//筛选工作把筛选出的字符串放入jsString
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -534,6 +553,7 @@ public class GTaskClient {
jsString = resString.substring(begin + jsBegin.length(), end); jsString = resString.substring(begin + jsBegin.length(), end);
} }
JSONObject js = new JSONObject(jsString); JSONObject js = new JSONObject(jsString);
//获取GTASK_JSON_LISTS
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS); return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) { } catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
@ -550,6 +570,9 @@ public class GTaskClient {
} }
} }
/*
* TASKListgid,
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -561,7 +584,7 @@ public class GTaskClient {
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); //这里设置为传入的listGid
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
actionList.put(action); actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
@ -582,6 +605,7 @@ public class GTaskClient {
return mAccount; return mAccount;
} }
//重置更新的内容
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }

@ -1,47 +1,27 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Activity; // Service是在一段不定的时间运行在后台不和用户交互的应用组件
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 { public class GTaskSyncService extends Service {
public static final String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
public static final int ACTION_START_SYNC = 0; public final static int ACTION_START_SYNC = 0;
public static final int ACTION_CANCEL_SYNC = 1; public final static int ACTION_CANCEL_SYNC = 1;
public static final int ACTION_INVALID = 2; public final static int ACTION_INVALID = 2;
public static final String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
public static final String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
public static final String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
private GTaskASyncTask mSyncTask = null; private static GTaskASyncTask mSyncTask = null;
private String mSyncProgress = ""; private static String mSyncProgress = "";
//开始一个同步的工作
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -52,10 +32,11 @@ public class GTaskSyncService extends Service {
} }
}); });
sendBroadcast(""); sendBroadcast("");
mSyncTask.execute(); mSyncTask.execute(); //这个函数让任务是以单线程队列方式或线程池队列方式运行
} }
} }
//取消同步的方法
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
@ -63,15 +44,18 @@ public class GTaskSyncService extends Service {
} }
@Override @Override
public void onCreate() { public void onCreate() { //初始化一个service
mSyncTask = null; mSyncTask = null;
} }
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {////service生命周期的组成部分相当于重启service比如在被暂停之后而不是创建一个新的
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
//两种情况,开始同步或者取消同步
case ACTION_START_SYNC: case ACTION_START_SYNC:
startSync(); startSync();
break; break;
@ -81,13 +65,14 @@ public class GTaskSyncService extends Service {
default: default:
break; break;
} }
return START_STICKY; return START_STICKY; //等待新的intent来是这个service继续运行
} }
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
@Override @Override
public void onLowMemory() { public void onLowMemory() { //在没有内存的情况下如果存在service则结束掉这的service
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
@ -97,32 +82,33 @@ public class GTaskSyncService extends Service {
return null; return null;
} }
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) { //发送同步的相关通知
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); //创建一个新的Intent
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); //附加INTENT中的相应参数的值
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
sendBroadcast(intent); sendBroadcast(intent); //发送这个通知
} }
public static void startSync(Activity activity) { public static void startSync(Activity activity) {//执行一个serviceservice的内容里的同步动作就是开始同步
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent); activity.startService(intent);
} }
public static void cancelSync(Context context) { public static void cancelSync(Context context) {//执行一个serviceservice的内容里的同步动作就是取消同步
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);
} }
public static boolean isSyncing() { public static boolean isSyncing() { //判读是否在进行同步
return mSyncTask != null; return mSyncTask != null;
} }
public static String getProgressString() { public static String getProgressString() { // 获取当前进度的信息
return mSyncProgress; return mSyncProgress;
} }
} }

@ -14,16 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
package net.micode.notes.model; import android.content.ContentProviderOperation;//批量的更新、插入、删除数据。
import android.content.ContentProviderOperation; import android.content.ContentProviderResult;//操作的结果
import android.content.ContentProviderResult; import android.content.ContentUris;//用于添加和获取Uri后面的ID
import android.content.ContentUris; import android.content.ContentValues;//一种用来存储基本数据类型数据的存储机制
import android.content.ContentValues; import android.content.Context;//需要用该类来弄清楚调用者的实例
import android.content.Context; import android.content.OperationApplicationException;//操作应用程序容错
import android.content.OperationApplicationException; import android.net.Uri;//表示待操作的数据
import android.net.Uri; import android.os.RemoteException;//远程容错
import android.os.RemoteException; import android.util.Log;//输出日志,比如说出错、警告等
import android.util.Log;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote; import net.micode.notes.data.Notes.CallNote;
@ -49,16 +48,17 @@ public class Note {
values.put(NoteColumns.MODIFIED_DATE, createdTime); values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId); values.put(NoteColumns.PARENT_ID, folderId);//将数据写入数据库表格
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);//ContentResolver()主要是实现外部应用对ContentProvider中的数据
//实现添加、删除、修改和查询操作
long noteId = 0; long noteId = 0;
try { try {
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0; noteId = 0;
} }//异常处理
if (noteId == -1) { if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId); throw new IllegalStateException("Wrong note id:" + noteId);
} }
@ -68,37 +68,37 @@ public class Note {
public Note() { public Note() {
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
} }//定义两个变量用来存储便签的数据,一个是存储便签属性、一个是存储便签内容
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }//设置数据库表格的标签属性数据
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
} }//设置数据库表格的标签文本内容的数据
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
} }//设置文本数据的ID
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
} }//得到文本数据的ID
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
} }//设置电话号码数据的ID
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
} }//得到电话号码数据的ID
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }//判断是否是本地修改
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
@ -128,16 +128,17 @@ public class Note {
} }
return true; return true;
} }//判断数据是否同步
//定义一个基本的便签内容的数据类,包含文本数据和电话号码数据
private class NoteData { private class NoteData {
private long mTextDataId; private long mTextDataId;
private ContentValues mTextDataValues; private ContentValues mTextDataValues;//文本数据
private long mCallDataId; private long mCallDataId;
private ContentValues mCallDataValues; private ContentValues mCallDataValues;//电话号码数据
private static final String TAG = "NoteData"; private static final String TAG = "NoteData";
@ -147,7 +148,7 @@ public class Note {
mTextDataId = 0; mTextDataId = 0;
mCallDataId = 0; mCallDataId = 0;
} }
//函数的具体实现
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
@ -177,18 +178,18 @@ public class Note {
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
//下面函数的作用是将新的数据通过Uri的操作存储到数据库
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety
*/ */
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }//判断数据是否合法
ArrayList<ContentProviderOperation> operationList = new ArrayList<>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
//数据库的操作列表
ContentProviderOperation.Builder builder = null; ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) { if (mTextDataId == 0) {
@ -209,7 +210,7 @@ public class Note {
operationList.add(builder.build()); operationList.add(builder.build());
} }
mTextDataValues.clear(); mTextDataValues.clear();
} }//把文本数据存入DataColumns
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
@ -231,7 +232,7 @@ public class Note {
operationList.add(builder.build()); operationList.add(builder.build());
} }
mCallDataValues.clear(); mCallDataValues.clear();
} }//把电话号码数据存入DataColumns
if (operationList.size() > 0) { if (operationList.size() > 0) {
try { try {
@ -246,7 +247,7 @@ public class Note {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null; return null;
} }
} }//存储过程中的异常处理
return null; return null;
} }
} }

@ -61,8 +61,8 @@ public class WorkingNote {
private boolean mIsDeleted; private boolean mIsDeleted;
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
// 声明 DATA_PROJECTION字符串数组
protected static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE,
@ -71,8 +71,8 @@ public class WorkingNote {
DataColumns.DATA3, DataColumns.DATA3,
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 声明 NOTE_PROJECTION字符串数组
protected static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
@ -114,6 +114,7 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
// WorkingNote的构造函数
// Existing note construct // Existing note construct
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
@ -124,11 +125,13 @@ public class WorkingNote {
loadNote(); loadNote();
} }
// 加载Note
// 通过数据库调用query函数找到第一个条目
private void loadNote() { private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
//若存在,储存相应信息
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
@ -139,6 +142,7 @@ public class WorkingNote {
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
} }
cursor.close(); cursor.close();
//若不存在,报错
} else { } else {
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
@ -146,14 +150,16 @@ public class WorkingNote {
loadNoteData(); loadNoteData();
} }
//加载NoteData
private void loadNoteData() { private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
}, null); }, null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { //查到信息不为空
if (cursor.moveToFirst()) {//查看第一项是否存在
do { do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
@ -165,7 +171,7 @@ public class WorkingNote {
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
} }
} while (cursor.moveToNext()); } while (cursor.moveToNext());//查询所有项,直到为空
} }
cursor.close(); cursor.close();
} else { } else {
@ -173,10 +179,12 @@ public class WorkingNote {
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId); throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
} }
} }
//创建空的Note
//传参context,文件夹id,widget,背景颜色
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
//设定相关属性
note.setBgColorId(defaultBgColorId); note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId); note.setWidgetId(widgetId);
note.setWidgetType(widgetType); note.setWidgetType(widgetType);
@ -186,10 +194,10 @@ public class WorkingNote {
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
//保存Note
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
if (isWorthSaving()) { if (isWorthSaving()) {//是否值得保存
if (!existInDatabase()) { if (!existInDatabase()) {//是否存在数据库中
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false; return false;
@ -211,12 +219,13 @@ public class WorkingNote {
return false; return false;
} }
} }
//是否存在数据库中
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
//是否值得保存
private boolean isWorthSaving() { private boolean isWorthSaving() {
//被删除,或(不在数据库中 内容为空) ,或本地已经保存过
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
return false; return false;
@ -224,11 +233,12 @@ public class WorkingNote {
return true; return true;
} }
} }
//设置mNoteSettingStatuListener
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
//设置AlertDate
//若mAlertDate与data不同则更改mAlertDate并设定NoteValue
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -238,17 +248,18 @@ public class WorkingNote {
mNoteSettingStatusListener.onClockAlertChanged(date, set); mNoteSettingStatusListener.onClockAlertChanged(date, set);
} }
} }
//设定删除标记
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
//设定标记
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();//调用mNoteSettingStatusListener的 onWidgetChanged方法
} }
} }
//设定背景颜色
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {//设定条件id!=mBgColorId
mBgColorId = id; mBgColorId = id;
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
@ -256,9 +267,10 @@ public class WorkingNote {
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
} }
} }
// 设定检查列表模式
// 参数mode
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {//设定条件
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
} }
@ -266,82 +278,92 @@ public class WorkingNote {
mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
} }
} }
// 设定WidgetType
// 参数type
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {//设定条件
mWidgetType = type; mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
// 调用Note的setNoteValue方法更改WidgetType
} }
} }
// 设定WidgetId
// 参数id
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {//设定条件
mWidgetId = id; mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
// 调用Note的setNoteValue方法更改WidgetId
} }
} }
// 设定WorkingTex
// 参数更改的text
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent); mNote.setTextData(DataColumns.CONTENT, mContent);
// 调用Note的setTextData方法更改WorkingText
} }
} }
// 转变mNote的CallData及CallNote信息
// 参数String phoneNumber, long callDate
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
//判断是否有时钟题型
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
//获取Content
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
//获取AlertDate
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
//获取ModifiedDate
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
//获取背景颜色来源id
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
//获取背景颜色id
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
//获取标题背景颜色id
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
//获取CheckListMode
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
//获取便签id
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
//获取文件夹id
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
//获取WidgetId
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
//获取WidgetType
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 创建接口 NoteSettingChangedListener,便签更新监视
// 为NoteEditActivity提供接口
// 提供函数有
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed

@ -39,10 +39,13 @@ import java.io.PrintStream;
public class BackupUtils { public class BackupUtils {
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils";
// Singleton stuff // Singleton stuff
private static BackupUtils sInstance; private static BackupUtils sInstance;//类里面为什么可以定义自身类对象?
//ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程例如线程A
//运行到这个方法时,都要检查有没有其它线程B或者C、 D等正在用这个方法(或者该类的其他同步方法)有的话要等正在使用synchronized方法的线程B或者C 、D运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。
//它包括两种用法synchronized 方法和 synchronized 块。
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) { if (sInstance == null) {
//如果当前备份不存在,则新声明一个
sInstance = new BackupUtils(context); sInstance = new BackupUtils(context);
} }
return sInstance; return sInstance;
@ -52,23 +55,23 @@ public class BackupUtils {
* Following states are signs to represents backup or restore * Following states are signs to represents backup or restore
* status * status
*/ */
// Currently, the sdcard is not mounted // Currently, the sdcard is not mounted SD卡没有被装入手机
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist // The backup file not exist 备份文件夹不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs // The data is not well formated, may be changed by other programs 数据已被破坏
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails // Some run-time exception which causes restore or backup fails 超时异常
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success // Backup or restore success 成功存储
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
private TextExport mTextExport; private TextExport mTextExport;
//初始化函数
private BackupUtils(Context context) { private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context);
} }
//外部储存功能是否可用
private static boolean externalStorageAvailable() { private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
@ -131,7 +134,7 @@ public class BackupUtils {
mFileName = ""; mFileName = "";
mFileDirectory = ""; mFileDirectory = "";
} }
//获取文本的组成部分
private String getFormat(int id) { private String getFormat(int id) {
return TEXT_FORMAT[id]; return TEXT_FORMAT[id];
} }
@ -140,23 +143,23 @@ public class BackupUtils {
* Export the folder identified by folder id to text * Export the folder identified by folder id to text
*/ */
private void exportFolderToText(String folderId, PrintStream ps) { private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder // Query notes belong to this folder 通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId folderId
}, null); }, null);
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { do {
// Print note's last modified date // Print note's last modified date ps里面保存有这份note的日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note // Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID); String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());//将文件导出到text
} }
notesCursor.close(); notesCursor.close();
} }
@ -168,9 +171,9 @@ public class BackupUtils {
private void exportNoteToText(String noteId, PrintStream ps) { private void exportNoteToText(String noteId, PrintStream ps) {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId noteId
}, null); }, null);
//利用光标来扫描内容区别为callnote和note两种靠ps.printline输出
if (dataCursor != null) { if (dataCursor != null) {
if (dataCursor.moveToFirst()) { if (dataCursor.moveToFirst()) {
do { do {
@ -180,7 +183,7 @@ public class BackupUtils {
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
//判断是否为空字符
if (!TextUtils.isEmpty(phoneNumber)) { if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber)); phoneNumber));
@ -218,6 +221,7 @@ public class BackupUtils {
/** /**
* Note will be exported as text which is user readable * Note will be exported as text which is user readable
*/ */
//总函数调用上面的exportFolder和exportNote
public int exportToText() { public int exportToText() {
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted"); Log.d(TAG, "Media was not mounted");
@ -229,7 +233,7 @@ public class BackupUtils {
Log.e(TAG, "get print stream error"); Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR;
} }
// First export folder and its notes // First export folder and its notes 导出文件夹,就是导出里面包含的便签
Cursor folderCursor = mContext.getContentResolver().query( Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
@ -257,7 +261,7 @@ public class BackupUtils {
folderCursor.close(); folderCursor.close();
} }
// Export notes in root's folder // Export notes in root's folder 将根目录里的便签导出(由于不属于任何文件夹,因此无法通过文件夹导出来实现这一部分便签的导出)
Cursor noteCursor = mContext.getContentResolver().query( Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
@ -297,6 +301,7 @@ public class BackupUtils {
PrintStream ps = null; PrintStream ps = null;
try { try {
FileOutputStream fos = new FileOutputStream(file); FileOutputStream fos = new FileOutputStream(file);
//将ps输出流输出到特定的文件目的就是导出到文件而不是直接输出
ps = new PrintStream(fos); ps = new PrintStream(fos);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
@ -314,15 +319,15 @@ public class BackupUtils {
*/ */
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory()); sb.append(Environment.getExternalStorageDirectory()); //外部SD卡的存储路径
sb.append(context.getString(filePathResId)); sb.append(context.getString(filePathResId)); //文件的存储路径
File filedir = new File(sb.toString()); File filedir = new File(sb.toString()); //filedir应该就是用来存储路径信息
sb.append(context.getString( sb.append(context.getString(
fileNameFormatResId, fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd), DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis()))); System.currentTimeMillis())));
File file = new File(sb.toString()); File file = new File(sb.toString());
//如果这些文件不存在,则新建
try { try {
if (!filedir.exists()) { if (!filedir.exists()) {
filedir.mkdir(); filedir.mkdir();
@ -336,7 +341,7 @@ public class BackupUtils {
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
// try catch 异常处理
return null; return null;
} }
} }

@ -52,13 +52,14 @@ public class DataUtils {
if(id == Notes.ID_ROOT_FOLDER) { if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root"); Log.e(TAG, "Don't delete system folder root");
continue; continue;
} } //如果发现是根文件夹,则不删除
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build()); operationList.add(builder.build());
} }//将ids里包含的每一列的数据逐次加入到operationList中等待最后的批量处理
try { try {
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
//数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
@ -81,7 +82,7 @@ public class DataUtils {
} }
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null");
return true; return true;
@ -119,7 +120,7 @@ public class DataUtils {
new String[] { "COUNT(*)" }, new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null); null);//筛选条件源文件不为trash folder
int count = 0; int count = 0;
if(cursor != null) { if(cursor != null) {
@ -141,11 +142,11 @@ public class DataUtils {
null, null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)}, new String [] {String.valueOf(type)},
null); null);//查询条件type符合且不属于垃圾文件夹
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空
exist = true; exist = true;
} }
cursor.close(); cursor.close();
@ -184,9 +185,10 @@ public class DataUtils {
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?", " AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null); new String[] { name }, null);
//通过名字查询文件是否存在
boolean exist = false; boolean exist = false;
if(cursor != null) { if(cursor != null) {
if(cursor.getCount() > 0) { if(cursor.getCount() > 0) {
@ -202,7 +204,7 @@ public class DataUtils {
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?", NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) }, new String[] { String.valueOf(folderId) },
null); null);//查询条件父ID是传入的folderId;
HashSet<AppWidgetAttribute> set = null; HashSet<AppWidgetAttribute> set = null;
if (c != null) { if (c != null) {
@ -211,13 +213,13 @@ public class DataUtils {
do { do {
try { try {
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0); widget.widgetId = c.getInt(0);//0对应的NoteColumns.WIDGET_ID
widget.widgetType = c.getInt(1); widget.widgetType = c.getInt(1);//1对应的NoteColumns.WIDGET_TYPE
set.add(widget); set.add(widget);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
} }
} while (c.moveToNext()); } while (c.moveToNext()); //查询下一条
} }
c.close(); c.close();
} }
@ -247,14 +249,14 @@ public class DataUtils {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)", + CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null); null);//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
try { try {
return cursor.getLong(0); return cursor.getLong(0);//0对应的CallNote.NOTE_ID
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString()); Log.e(TAG, "Get call note id fails " + e.toString());
} }
@ -269,7 +271,7 @@ public class DataUtils {
new String [] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?", NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)}, new String [] { String.valueOf(noteId)},
null); null);//查询条件noteId
if (cursor != null) { if (cursor != null) {
String snippet = ""; String snippet = "";
@ -282,7 +284,7 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId); throw new IllegalArgumentException("Note is not found with id: " + noteId);
} }
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {//对字符串进行格式处理,将字符串两头的空格去掉,同时将换行符去掉
if (snippet != null) { if (snippet != null) {
snippet = snippet.trim(); snippet = snippet.trim();
int index = snippet.indexOf('\n'); int index = snippet.indexOf('\n');

@ -13,9 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
//简介定义了很多的静态字符串目的就是为了提供jsonObject中相应字符串的"key"。把这些静态的定义单独写到了一个类里面,这是非常好的编程规范
package net.micode.notes.tool; package net.micode.notes.tool;
//这个类就是定义了一堆static string实际就是为jsonObject提供Key把这些定义全部写到一个类里方便查看管理是一个非常好的编程习惯
public class GTaskStringUtils { public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";

@ -16,6 +16,20 @@
package net.micode.notes.tool; package net.micode.notes.tool;
/*使
* R.java
* R.id
* R.drawable 使
* R.layout
* R.menu
* R.String
* R.style 使
* idgetXXX
*
*
* @BG_DEFAULT_COLOR
* BG_DEFAULT_FONT_SIZE
*/
import android.content.Context; import android.content.Context;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
@ -41,19 +55,19 @@ public class ResourceParser {
public static class NoteBgResources { public static class NoteBgResources {
private final static int [] BG_EDIT_RESOURCES = new int [] { private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow, R.drawable.edit_yellow,
R.drawable.edit_blue, R.drawable.edit_blue,
R.drawable.edit_white, R.drawable.edit_white,
R.drawable.edit_green, R.drawable.edit_green,
R.drawable.edit_red R.drawable.edit_red
}; };
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow, R.drawable.edit_title_yellow,
R.drawable.edit_title_blue, R.drawable.edit_title_blue,
R.drawable.edit_title_white, R.drawable.edit_title_white,
R.drawable.edit_title_green, R.drawable.edit_title_green,
R.drawable.edit_title_red R.drawable.edit_title_red
}; };
public static int getNoteBgResource(int id) { public static int getNoteBgResource(int id) {
@ -64,7 +78,7 @@ public class ResourceParser {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id];
} }
} }
//直接获取默认的背景颜色。
public static int getDefaultBgId(Context context) { public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
@ -76,35 +90,35 @@ public class ResourceParser {
public static class NoteItemBgResources { public static class NoteItemBgResources {
private final static int [] BG_FIRST_RESOURCES = new int [] { private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up, R.drawable.list_yellow_up,
R.drawable.list_blue_up, R.drawable.list_blue_up,
R.drawable.list_white_up, R.drawable.list_white_up,
R.drawable.list_green_up, R.drawable.list_green_up,
R.drawable.list_red_up R.drawable.list_red_up
}; };
private final static int [] BG_NORMAL_RESOURCES = new int [] { private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle, R.drawable.list_yellow_middle,
R.drawable.list_blue_middle, R.drawable.list_blue_middle,
R.drawable.list_white_middle, R.drawable.list_white_middle,
R.drawable.list_green_middle, R.drawable.list_green_middle,
R.drawable.list_red_middle R.drawable.list_red_middle
}; };
private final static int [] BG_LAST_RESOURCES = new int [] { private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down, R.drawable.list_yellow_down,
R.drawable.list_blue_down, R.drawable.list_blue_down,
R.drawable.list_white_down, R.drawable.list_white_down,
R.drawable.list_green_down, R.drawable.list_green_down,
R.drawable.list_red_down, R.drawable.list_red_down,
}; };
private final static int [] BG_SINGLE_RESOURCES = new int [] { private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single, R.drawable.list_yellow_single,
R.drawable.list_blue_single, R.drawable.list_blue_single,
R.drawable.list_white_single, R.drawable.list_white_single,
R.drawable.list_green_single, R.drawable.list_green_single,
R.drawable.list_red_single R.drawable.list_red_single
}; };
public static int getNoteBgFirstRes(int id) { public static int getNoteBgFirstRes(int id) {
@ -130,11 +144,11 @@ public class ResourceParser {
public static class WidgetBgResources { public static class WidgetBgResources {
private final static int [] BG_2X_RESOURCES = new int [] { private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow, R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue, R.drawable.widget_2x_blue,
R.drawable.widget_2x_white, R.drawable.widget_2x_white,
R.drawable.widget_2x_green, R.drawable.widget_2x_green,
R.drawable.widget_2x_red, R.drawable.widget_2x_red,
}; };
public static int getWidget2xBgResource(int id) { public static int getWidget2xBgResource(int id) {
@ -142,11 +156,11 @@ public class ResourceParser {
} }
private final static int [] BG_4X_RESOURCES = new int [] { private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow, R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue, R.drawable.widget_4x_blue,
R.drawable.widget_4x_white, R.drawable.widget_4x_white,
R.drawable.widget_4x_green, R.drawable.widget_4x_green,
R.drawable.widget_4x_red R.drawable.widget_4x_red
}; };
public static int getWidget4xBgResource(int id) { public static int getWidget4xBgResource(int id) {
@ -156,12 +170,12 @@ public class ResourceParser {
public static class TextAppearanceResources { public static class TextAppearanceResources {
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal, R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium, R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge, R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper R.style.TextAppearanceSuper
}; };
//这里有一个容错的函数防止输入的id大于资源总量若如此则自动返回默认的设置结果
public static int getTexAppearanceResource(int id) { public static int getTexAppearanceResource(int id) {
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: Fix bug of store the resource id in shared preference.

@ -39,7 +39,7 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
// 派生自Activity类并实现OnClickListener和OnDismissListener接口
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; private long mNoteId;
private String mSnippet; private String mSnippet;
@ -50,11 +50,14 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
// 请求无标题的窗口
final Window win = getWindow(); final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 在锁定的情况下显示
if (!isScreenOn()) {// 如果屏幕关闭,则设置一些窗口标志
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
@ -65,6 +68,9 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
try { try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 从Intent中获取noteId
// 截取文本片段并添加标识字符串
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
@ -76,24 +82,25 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
mPlayer = new MediaPlayer(); mPlayer = new MediaPlayer();
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog(); showActionDialog();// 显示操作对话框
playAlarmSound();
playAlarmSound();// 播放报警声音
} else { } else {
finish(); finish();// 关闭Activity
} }
} }
private boolean isScreenOn() { private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn(); return pm.isScreenOn();// 返回屏幕是否打开的状态
} }
private void playAlarmSound() { private void playAlarmSound() {// 获取默认的闹钟铃声
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取系统静音模式下影响的流
int silentModeStreams = Settings.System.getInt(getContentResolver(), int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 根据静音模式设置音频流类型
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams); mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
@ -118,6 +125,7 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
e.printStackTrace(); e.printStackTrace();
} }
} }
// 显示操作对话框
private void showActionDialog() { private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog.Builder dialog = new AlertDialog.Builder(this);
@ -129,7 +137,7 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
} }
dialog.show().setOnDismissListener(this); dialog.show().setOnDismissListener(this);
} }
// 点击“进入”按钮,启动编辑笔记页面
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
switch (which) { switch (which) {
case DialogInterface.BUTTON_NEGATIVE: case DialogInterface.BUTTON_NEGATIVE:
@ -144,12 +152,12 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
} }
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
stopAlarmSound(); stopAlarmSound();// 停止报警声音
finish(); finish();
} }
private void stopAlarmSound() { private void stopAlarmSound() {
if (mPlayer != null) { if (mPlayer != null) {// 停止播放报警声音
mPlayer.stop(); mPlayer.stop();
mPlayer.release(); mPlayer.release();
mPlayer = null; mPlayer = null;

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.AlarmManager; import android.app.AlarmManager;
@ -27,12 +11,11 @@ import android.database.Cursor;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
private static final String [] PROJECTION = new String [] { private static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE NoteColumns.ALERTED_DATE
}; };
private static final int COLUMN_ID = 0; private static final int COLUMN_ID = 0;
@ -40,7 +23,9 @@ public class AlarmInitReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 获取当前系统时间
long currentDate = System.currentTimeMillis(); long currentDate = System.currentTimeMillis();
// 查询具有提醒日期大于当前时间且类型为Notes.TYPE_NOTE的备忘录
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
@ -50,16 +35,20 @@ public class AlarmInitReceiver extends BroadcastReceiver {
if (c != null) { if (c != null) {
if (c.moveToFirst()) { if (c.moveToFirst()) {
do { do {
// 获取备忘录的提醒日期
long alertDate = c.getLong(COLUMN_ALERTED_DATE); long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建用于启动AlarmReceiver的Intent
Intent sender = new Intent(context, AlarmReceiver.class); Intent sender = new Intent(context, AlarmReceiver.class);
// 将备忘录的URI作为数据添加到sender中
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建PendingIntent以便在提醒时间到达时触发
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context // 获取AlarmManager服务设置提醒时间以及PendingIntent
.getSystemService(Context.ALARM_SERVICE); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); } while (c.moveToNext());
} }
c.close(); c.close(); // 关闭查询结果的游标
} }
} }
} }

@ -1,18 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
@ -20,11 +5,23 @@ import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
/**
* 广
*/
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
* @param context
* @param intent 广
*/
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 设置意图要启动的目标活动为AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
// 添加标志以指示启动新任务的活动
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动目标活动
context.startActivity(intent); context.startActivity(intent);
} }
} }

@ -29,7 +29,7 @@ import android.widget.FrameLayout;
import android.widget.NumberPicker; import android.widget.NumberPicker;
public class DateTimePicker extends FrameLayout { public class DateTimePicker extends FrameLayout {
// 常量定义
private static final boolean DEFAULT_ENABLE_STATE = true; private static final boolean DEFAULT_ENABLE_STATE = true;
private static final int HOURS_IN_HALF_DAY = 12; private static final int HOURS_IN_HALF_DAY = 12;
@ -45,13 +45,13 @@ public class DateTimePicker extends FrameLayout {
private static final int MINUT_SPINNER_MAX_VAL = 59; private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1; private static final int AMPM_SPINNER_MAX_VAL = 1;
// 控件变量声明
private final NumberPicker mDateSpinner; private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner; private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner; private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner; private final NumberPicker mAmPmSpinner;
private Calendar mDate; private Calendar mDate;
// 其他变量声明
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm; private boolean mIsAm;
@ -63,7 +63,7 @@ public class DateTimePicker extends FrameLayout {
private boolean mInitialising; private boolean mInitialising;
private OnDateTimeChangedListener mOnDateTimeChangedListener; private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 构造方法和接口定义
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
@ -72,7 +72,7 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
//初始化DateTimePicker控件关联布局文件并设置相关监听器
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
@ -114,7 +114,7 @@ public class DateTimePicker extends FrameLayout {
} }
} }
}; };
// 初始化各个NumberPicker控件
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
@ -143,7 +143,7 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
// 设置AmPmSpinner控件
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
@ -157,12 +157,12 @@ public class DateTimePicker extends FrameLayout {
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
// 更新控件到初始状态
public interface OnDateTimeChangedListener { public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month, void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute); int dayOfMonth, int hourOfDay, int minute);
} }
// 设置为当前时间
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
@ -213,6 +213,8 @@ public class DateTimePicker extends FrameLayout {
// set the content descriptions // set the content descriptions
mInitialising = false; mInitialising = false;
} }
//监听器实现:
// 日期变化监听器
@Override @Override
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
@ -226,12 +228,12 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setEnabled(enabled); mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled; mIsEnabled = enabled;
} }
// 处理日期变化事件
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return mIsEnabled; return mIsEnabled;
} }
// 小时变化监听器
/** /**
* Get the current date in millis * Get the current date in millis
* *
@ -240,7 +242,7 @@ public class DateTimePicker extends FrameLayout {
public long getCurrentDateInTimeMillis() { public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis(); return mDate.getTimeInMillis();
} }
// 处理小时变化事件
/** /**
* Set the current date * Set the current date
* *
@ -252,7 +254,7 @@ public class DateTimePicker extends FrameLayout {
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 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)); cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
} }
// 分钟变化监听器
/** /**
* Set the current date * Set the current date
* *
@ -270,7 +272,7 @@ public class DateTimePicker extends FrameLayout {
setCurrentHour(hourOfDay); setCurrentHour(hourOfDay);
setCurrentMinute(minute); setCurrentMinute(minute);
} }
// 处理分钟变化事件
/** /**
* Get current year * Get current year
* *
@ -279,7 +281,7 @@ public class DateTimePicker extends FrameLayout {
public int getCurrentYear() { public int getCurrentYear() {
return mDate.get(Calendar.YEAR); return mDate.get(Calendar.YEAR);
} }
// 上午/下午变化监听器
/** /**
* Set current year * Set current year
* *
@ -291,14 +293,14 @@ public class DateTimePicker extends FrameLayout {
} }
mDate.set(Calendar.YEAR, year); mDate.set(Calendar.YEAR, year);
updateDateControl(); updateDateControl();
onDateTimeChanged(); onDateTimeChanged();// 处理上午/下午变化事件
} }
/** /**
* Get current month in the year * Get current month in the year
* *
* @return The current month in the year * @return The current month in the year
*/ *///其他方法实现:
public int getCurrentMonth() { public int getCurrentMonth() {
return mDate.get(Calendar.MONTH); return mDate.get(Calendar.MONTH);
} }
@ -310,7 +312,7 @@ public class DateTimePicker extends FrameLayout {
*/ */
public void setCurrentMonth(int month) { public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) { if (!mInitialising && month == getCurrentMonth()) {
return; return; // 设置控件是否可用
} }
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
updateDateControl(); updateDateControl();
@ -330,7 +332,7 @@ public class DateTimePicker extends FrameLayout {
* Set current day of the month * Set current day of the month
* *
* @param dayOfMonth The day of the month * @param dayOfMonth The day of the month
*/ */// 获取控件是否可用状态
public void setCurrentDay(int dayOfMonth) { public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) { if (!mInitialising && dayOfMonth == getCurrentDay()) {
return; return;
@ -343,7 +345,7 @@ public class DateTimePicker extends FrameLayout {
/** /**
* Get current hour in 24 hour mode, in the range (0~23) * Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode * @return The current hour in 24 hour mode
*/ */// 获取当前日期的时间戳
public int getCurrentHourOfDay() { public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY); return mDate.get(Calendar.HOUR_OF_DAY);
} }
@ -360,7 +362,7 @@ public class DateTimePicker extends FrameLayout {
} }
} }
} }
// 设置当前日期
/** /**
* Set current hour in 24 hour mode, in the range (0~23) * Set current hour in 24 hour mode, in the range (0~23)
* *
@ -388,7 +390,7 @@ public class DateTimePicker extends FrameLayout {
mHourSpinner.setValue(hourOfDay); mHourSpinner.setValue(hourOfDay);
onDateTimeChanged(); onDateTimeChanged();
} }
// 设置具体的年、月、日、时、分
/** /**
* Get currentMinute * Get currentMinute
* *
@ -409,7 +411,7 @@ public class DateTimePicker extends FrameLayout {
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged(); onDateTimeChanged();
} }
// 如果不是初始化状态,并且输入的年份与当前年份相同,则直接返回
/** /**
* @return true if this is in 24 hour view else false. * @return true if this is in 24 hour view else false.
*/ */
@ -421,7 +423,7 @@ public class DateTimePicker extends FrameLayout {
* Set whether in 24 hour or AM/PM mode. * Set whether in 24 hour or AM/PM mode.
* *
* @param is24HourView True for 24 hour mode. False for AM/PM mode. * @param is24HourView True for 24 hour mode. False for AM/PM mode.
*/ */// 设置年份到日期对象中
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) { if (mIs24HourView == is24HourView) {
return; return;
@ -433,7 +435,7 @@ public class DateTimePicker extends FrameLayout {
setCurrentHour(hour); setCurrentHour(hour);
updateAmPmControl(); updateAmPmControl();
} }
// 更新日期控件
private void updateDateControl() { private void updateDateControl() {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
@ -447,7 +449,7 @@ public class DateTimePicker extends FrameLayout {
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate(); mDateSpinner.invalidate();
} }
// 触发日期时间改变回调
private void updateAmPmControl() { private void updateAmPmControl() {
if (mIs24HourView) { if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE); mAmPmSpinner.setVisibility(View.GONE);

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import java.util.Calendar; import java.util.Calendar;
@ -29,6 +13,9 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.text.format.DateUtils; import android.text.format.DateUtils;
/**
* AlertDialogOnClickListener
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
@ -36,17 +23,25 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
/**
*
*/
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
/**
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); super(context);
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker); setView(mDateTimePicker);
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month, public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
mDate.set(Calendar.YEAR, year); mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
@ -64,23 +59,38 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
/**
* 12/24
* @param is24HourView 24
*/
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
/**
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
/**
*
* @param date
*/
private void updateTitle(long date) { private void updateTitle(long date) {
int flag = int flag =
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME; DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
} }
/**
*
*/
public void onClick(DialogInterface arg0, int arg1) { public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) { if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());

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

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -28,26 +12,29 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
protected static final String [] PROJECTION = { // 定义投影表示从Cursor中读取的数据列
NoteColumns.ID, public static final String[] PROJECTION = {
NoteColumns.SNIPPET NoteColumns.ID,
NoteColumns.SNIPPET
}; };
public static final int ID_COLUMN = 0; // 定义数据列的索引
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1; public static final int NAME_COLUMN = 1;
// 构造函数接受上下文Context和游标Cursor作为参数
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// TODO Auto-generated constructor stub
} }
// 创建新的视图
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context); return new FolderListItem(context);
} }
// 绑定视图
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {
@ -57,24 +44,27 @@ public class FoldersListAdapter extends CursorAdapter {
} }
} }
// 获取文件夹名字
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
// 内部类,表示文件夹列表中的单个项
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
private TextView mName; private TextView mName;
// 构造函数,初始化视图
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.folder_list_item, this); inflate(context, R.layout.folder_list_item, this); // 填充布局
mName = (TextView) findViewById(R.id.tv_folder_name); mName = (TextView) findViewById(R.id.tv_folder_name); // 找到子视图
} }
// 绑定数据到视图
public void bind(String name) { public void bind(String name) {
mName.setText(name); mName.setText(name); // 设置文件夹名字到文本视图
} }
} }
} }

@ -1,218 +1,74 @@
/* //继承Activity类 实现点击监听 文本监听
* 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, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
private class HeadViewHolder { private class HeadViewHolder {
//文本框
public TextView tvModified; public TextView tvModified;
//图片
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
//文本框
public TextView tvAlertDate; public TextView tvAlertDate;
//图片
public ImageView ibSetBgColor; public ImageView ibSetBgColor;
public HeadViewHolder() {
}
public HeadViewHolder(TextView tvModified, ImageView ivAlertIcon, TextView tvAlertDate, ImageView ibSetBgColor) {
this.tvModified = tvModified;
this.ivAlertIcon = ivAlertIcon;
this.tvAlertDate = tvAlertDate;
this.ibSetBgColor = ibSetBgColor;
}
/**
*
* @return tvModified
*/
public TextView getTvModified() {
return tvModified;
}
/**
*
* @param tvModified
*/
public void setTvModified(TextView tvModified) {
this.tvModified = tvModified;
}
/**
*
* @return ivAlertIcon
*/
public ImageView getIvAlertIcon() {
return ivAlertIcon;
}
/**
*
* @param ivAlertIcon
*/
public void setIvAlertIcon(ImageView ivAlertIcon) {
this.ivAlertIcon = ivAlertIcon;
}
/**
*
* @return tvAlertDate
*/
public TextView getTvAlertDate() {
return tvAlertDate;
}
/**
*
* @param tvAlertDate
*/
public void setTvAlertDate(TextView tvAlertDate) {
this.tvAlertDate = tvAlertDate;
}
/**
*
* @return ibSetBgColor
*/
public ImageView getIbSetBgColor() {
return ibSetBgColor;
}
/**
*
* @param ibSetBgColor
*/
public void setIbSetBgColor(ImageView ibSetBgColor) {
this.ibSetBgColor = ibSetBgColor;
}
public String toString() {
return "HeadViewHolder{tvModified = " + tvModified + ", ivAlertIcon = " + ivAlertIcon + ", tvAlertDate = " + tvAlertDate + ", ibSetBgColor = " + ibSetBgColor + "}";
}
} }
//实例化HashMap对象 以键值对方式存储
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static { static {
//存放资源id
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED);
sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);
sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN);
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
} }
//实例化HashMap对象
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
//存放资源id
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select);
sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select);
sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
} }
//实例化HashMap对象
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static { static {
//存放资源id
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);
sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM);
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);
} }
//实例化HashMap对象
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
//存放资源id
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
} }
//定义一个静态的私密的不允许修改的TAG值
private static final String TAG = "NoteEditActivity"; private static final String TAG = "NoteEditActivity";
//适配器 配合listView使用
private HeadViewHolder mNoteHeaderHolder; private HeadViewHolder mNoteHeaderHolder;
//所有控件的基类
private View mHeadViewPanel; private View mHeadViewPanel;
//所有控件的基类
private View mNoteBgColorSelector; private View mNoteBgColorSelector;
//所有控件的基类
private View mFontSizeSelector; private View mFontSizeSelector;
//文本框
private EditText mNoteEditor; private EditText mNoteEditor;
//所有控件的基类
private View mNoteEditorPanel; private View mNoteEditorPanel;
//自定义类
private WorkingNote mWorkingNote; private WorkingNote mWorkingNote;
//轻量级的存储辅助类
private SharedPreferences mSharedPrefs; private SharedPreferences mSharedPrefs;
//
private int mFontSizeId; private int mFontSizeId;
private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
@ -221,21 +77,23 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public static final String TAG_CHECKED = String.valueOf('\u221A'); public static final String TAG_CHECKED = String.valueOf('\u221A');
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
//布局
private LinearLayout mEditTextList; private LinearLayout mEditTextList;
private String mUserQuery; private String mUserQuery;
//正则表达
private Pattern mPattern; private Pattern mPattern;
//重写方法 参数是保存了activity的状态
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
this.setContentView(R.layout.note_edit); this.setContentView(R.layout.note_edit);
//如果activity生命周期结束或者得不到intent 则销毁当前activity
if (savedInstanceState == null && !initActivityState(getIntent())) { if (savedInstanceState == null && !initActivityState(getIntent())) {
finish(); finish();
return; return;
} }
//初始化资源
initResources(); initResources();
} }
@ -243,12 +101,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* Current activity may be killed when the memory is low. Once it is killed, for another time * 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 * user load this activity, we should restore the former state
*/ */
//重写方法
@Override @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
//intent中存放UID信息
intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID));
//如果
if (!initActivityState(intent)) { if (!initActivityState(intent)) {
finish(); finish();
return; return;
@ -256,13 +117,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Log.d(TAG, "Restoring from killed activity"); Log.d(TAG, "Restoring from killed activity");
} }
} }
//初始化
private boolean initActivityState(Intent intent) { private boolean initActivityState(Intent intent) {
/** /**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
* then jump to the NotesListActivity * then jump to the NotesListActivity
*/ */
mWorkingNote = null; mWorkingNote = null;
//如果两者相等
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
mUserQuery = ""; mUserQuery = "";
@ -270,15 +132,20 @@ public class NoteEditActivity extends Activity implements OnClickListener,
/** /**
* Starting from the searched result * Starting from the searched result
*/ */
//如果intent的传递值存在
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
} }
if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
//创建从当前页面前往NotesListActivity的intent
Intent jump = new Intent(this, NotesListActivity.class); Intent jump = new Intent(this, NotesListActivity.class);
//启动意图
startActivity(jump); startActivity(jump);
//显示提示
showToast(R.string.error_note_not_exist); showToast(R.string.error_note_not_exist);
//结束当前页面生命周期
finish(); finish();
return false; return false;
} else { } else {
@ -289,11 +156,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return false; return false;
} }
} }
//弹出软键盘
getWindow().setSoftInputMode( getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
// New note // New note
//获取intent中的信息
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID); AppWidgetManager.INVALID_APPWIDGET_ID);
@ -305,7 +174,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
// Parse call-record note // Parse call-record note
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);
//callDate和phoneNumber不为空
if (callDate != 0 && phoneNumber != null) { if (callDate != 0 && phoneNumber != null) {
//判断电话是否为空
if (TextUtils.isEmpty(phoneNumber)) { if (TextUtils.isEmpty(phoneNumber)) {
Log.w(TAG, "The call record number is null"); Log.w(TAG, "The call record number is null");
} }
@ -339,28 +210,32 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote.setOnSettingStatusChangedListener(this); mWorkingNote.setOnSettingStatusChangedListener(this);
return true; return true;
} }
//重写方法
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
initNoteScreen(); initNoteScreen();
} }
//初始化
private void initNoteScreen() { private void initNoteScreen() {
//AndroidTextAppearance 属性是一个特殊的属性用于将特定的文本样式应用到你的View 组件
mNoteEditor.setTextAppearance(this, TextAppearanceResources mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId)); .getTexAppearanceResource(mFontSizeId));
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
switchToListMode(mWorkingNote.getContent()); switchToListMode(mWorkingNote.getContent());
} else { } else {
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
//setSelection可以让ListView跳转到某个item显示
mNoteEditor.setSelection(mNoteEditor.getText().length()); mNoteEditor.setSelection(mNoteEditor.getText().length());
} }
for (Integer id : sBgSelectorSelectionMap.keySet()) { for (Integer id : sBgSelectorSelectionMap.keySet()) {
//设置可见性
findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);
} }
//设置控件的背景图片
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
//对日期进行格式转换
mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
@ -375,13 +250,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
private void showAlertHeader() { private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
//获取当前的总毫秒数
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
//如果时间大于便签的时间
if (time > mWorkingNote.getAlertDate()) { if (time > mWorkingNote.getAlertDate()) {
mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired);
} else { } else {
//显示过去的相对时间
mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString(
mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));
} }
//设置可见性
mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE);
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE);
} else { } else {
@ -389,13 +268,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
}; };
} }
//重写方法
@Override @Override
protected void onNewIntent(Intent intent) { protected void onNewIntent(Intent intent) {
super.onNewIntent(intent); super.onNewIntent(intent);
initActivityState(intent); initActivityState(intent);
} }
//重写方法
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
@ -410,23 +289,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
} }
//重写方法
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {
//判断点击的位置是不是在指定的组件上
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mNoteBgColorSelector, ev)) { && !inRangeOfView(mNoteBgColorSelector, ev)) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
} }
//判断点击的位置是不是在指定的组件上
if (mFontSizeSelector.getVisibility() == View.VISIBLE if (mFontSizeSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mFontSizeSelector, ev)) { && !inRangeOfView(mFontSizeSelector, ev)) {
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
return true; return true;
} }
//触摸传递事件
return super.dispatchTouchEvent(ev); return super.dispatchTouchEvent(ev);
} }
//判断点击的位置是不是在指定的组件上
private boolean inRangeOfView(View view, MotionEvent ev) { private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2]; int []location = new int[2];
view.getLocationOnScreen(location); view.getLocationOnScreen(location);
@ -436,14 +317,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
|| ev.getX() > (x + view.getWidth()) || ev.getX() > (x + view.getWidth())
|| ev.getY() < y || ev.getY() < y
|| ev.getY() > (y + view.getHeight())) { || ev.getY() > (y + view.getHeight())) {
return false; return false;
} }
return true; return true;
} }
//初始化
private void initResources() { private void initResources() {
mHeadViewPanel = findViewById(R.id.note_title); mHeadViewPanel = findViewById(R.id.note_title);
//为listView快速设置值
mNoteHeaderHolder = new HeadViewHolder(); mNoteHeaderHolder = new HeadViewHolder();
//设置对应的一系列值
mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);
mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);
mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);
@ -452,17 +335,21 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mNoteEditor = (EditText) findViewById(R.id.note_edit_view); mNoteEditor = (EditText) findViewById(R.id.note_edit_view);
mNoteEditorPanel = findViewById(R.id.sv_note_edit); mNoteEditorPanel = findViewById(R.id.sv_note_edit);
mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);
//遍历key 设置图片
for (int id : sBgSelectorBtnsMap.keySet()) { for (int id : sBgSelectorBtnsMap.keySet()) {
ImageView iv = (ImageView) findViewById(id); ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this); iv.setOnClickListener(this);
} }
mFontSizeSelector = findViewById(R.id.font_size_selector); mFontSizeSelector = findViewById(R.id.font_size_selector);
//遍历key 设置view组件
for (int id : sFontSizeBtnsMap.keySet()) { for (int id : sFontSizeBtnsMap.keySet()) {
View view = findViewById(id); View view = findViewById(id);
view.setOnClickListener(this); view.setOnClickListener(this);
}; };
//轻量级的存储类
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
//获取存储的数据
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * HACKME: Fix bug of store the resource id in shared preference.
@ -472,9 +359,10 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
} }
//设置LinearLayout组件
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
} }
//重写方法
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
@ -485,6 +373,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private void updateWidget() { private void updateWidget() {
//创建intent实例
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
intent.setClass(this, NoteWidgetProvider_2x.class); intent.setClass(this, NoteWidgetProvider_2x.class);
@ -494,18 +383,20 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Log.e(TAG, "Unspported widget type"); Log.e(TAG, "Unspported widget type");
return; return;
} }
//在intent中存放信息
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
mWorkingNote.getWidgetId() mWorkingNote.getWidgetId()
}); });
//发送广播
sendBroadcast(intent); sendBroadcast(intent);
//回传数据
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
public void onClick(View v) { public void onClick(View v) {
int id = v.getId(); int id = v.getId();
if (id == R.id.btn_set_bg_color) { if (id == R.id.btn_set_bg_color) {
//设置组件可见性
mNoteBgColorSelector.setVisibility(View.VISIBLE); mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
- View.VISIBLE); - View.VISIBLE);
@ -517,91 +408,113 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} else if (sFontSizeBtnsMap.containsKey(id)) { } else if (sFontSizeBtnsMap.containsKey(id)) {
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE);
mFontSizeId = sFontSizeBtnsMap.get(id); mFontSizeId = sFontSizeBtnsMap.get(id);
//在存储类中存储信息
mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
getWorkingText(); getWorkingText();
switchToListMode(mWorkingNote.getContent()); switchToListMode(mWorkingNote.getContent());
} else { } else {
//设置view的特定文本格式
mNoteEditor.setTextAppearance(this, mNoteEditor.setTextAppearance(this,
TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
} }
//设置为不可见
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
} }
} }
//重写方法
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if(clearSettingState()) { if(clearSettingState()) {
return; return;
} }
//保存便签
saveNote(); saveNote();
super.onBackPressed(); super.onBackPressed();
} }
//
private boolean clearSettingState() { private boolean clearSettingState() {
//如果mNoteBgColorSelector为visible则设置为GONE 不占据空间
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
return true; return true;
//同上
} else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {
mFontSizeSelector.setVisibility(View.GONE); mFontSizeSelector.setVisibility(View.GONE);
return true; return true;
} }
return false; return false;
} }
//背景颜色变化
public void onBackgroundColorChanged() { public void onBackgroundColorChanged() {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE); View.VISIBLE);
//设置背景资源
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
//设置背景资源
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
} }
//重写方法
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
if (isFinishing()) { if (isFinishing()) {
return true; return true;
} }
clearSettingState(); clearSettingState();
//清理菜单
menu.clear(); menu.clear();
if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {
//将xml定义的一个布局找出来
getMenuInflater().inflate(R.menu.call_note_edit, menu); getMenuInflater().inflate(R.menu.call_note_edit, menu);
} else { } else {
//将xml定义的一个布局找出来
getMenuInflater().inflate(R.menu.note_edit, menu); getMenuInflater().inflate(R.menu.note_edit, menu);
} }
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
//通过id来得到munu item组件
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode);
} else { } else {
//通过id来得到munu item组件
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode);
} }
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
//通过id来得到munu item组件
menu.findItem(R.id.menu_alert).setVisible(false); menu.findItem(R.id.menu_alert).setVisible(false);
} else { } else {
//通过id来得到munu item组件
menu.findItem(R.id.menu_delete_remind).setVisible(false); menu.findItem(R.id.menu_delete_remind).setVisible(false);
} }
return true; return true;
} }
//重写方法
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
//根据itemid来分情况运行
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_new_note: case R.id.menu_new_note:
//创建新便签
createNewNote(); createNewNote();
break; break;
case R.id.menu_delete: case R.id.menu_delete:
//创建对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
//设置对话框基本信息
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_note)); builder.setMessage(getString(R.string.alert_message_delete_note));
//设置确认按钮点击事件
builder.setPositiveButton(android.R.string.ok, builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
//删除便签
deleteCurrentNote(); deleteCurrentNote();
//退出当前页面
finish(); finish();
} }
}); });
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
//显示对话框
builder.show(); builder.show();
break; break;
case R.id.menu_font_size: case R.id.menu_font_size:
@ -632,12 +545,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private void setReminder() { private void setReminder() {
//日期时间选择控件
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
//点击事件
d.setOnDateTimeSetListener(new OnDateTimeSetListener() { d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
public void OnDateTimeSet(AlertDialog dialog, long date) { public void OnDateTimeSet(AlertDialog dialog, long date) {
mWorkingNote.setAlertDate(date , true); mWorkingNote.setAlertDate(date , true);
} }
}); });
//显示控件
d.show(); d.show();
} }
@ -646,46 +562,57 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* and {@text/plain} type * and {@text/plain} type
*/ */
private void sendTo(Context context, String info) { private void sendTo(Context context, String info) {
//创建意图
Intent intent = new Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
//传递数据
intent.putExtra(Intent.EXTRA_TEXT, info); intent.putExtra(Intent.EXTRA_TEXT, info);
intent.setType("text/plain"); intent.setType("text/plain");
//启动
context.startActivity(intent); context.startActivity(intent);
} }
//创建新便签
private void createNewNote() { private void createNewNote() {
// Firstly, save current editing notes // Firstly, save current editing notes
saveNote(); saveNote();
// For safety, start a new NoteEditActivity // For safety, start a new NoteEditActivity
finish(); finish();
//创建意图
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
//设置行为
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
//存放信息
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId());
//启动
startActivity(intent); startActivity(intent);
} }
//删除
private void deleteCurrentNote() { private void deleteCurrentNote() {
if (mWorkingNote.existInDatabase()) { if (mWorkingNote.existInDatabase()) {
HashSet<Long> ids = new HashSet<Long>(); HashSet<Long> ids = new HashSet<Long>();
//获取NoteId
long id = mWorkingNote.getNoteId(); long id = mWorkingNote.getNoteId();
if (id != Notes.ID_ROOT_FOLDER) { if (id != Notes.ID_ROOT_FOLDER) {
ids.add(id); ids.add(id);
} else { } else {
//日志打印
Log.d(TAG, "Wrong note id, should not happen"); Log.d(TAG, "Wrong note id, should not happen");
} }
if (!isSyncMode()) { if (!isSyncMode()) {
if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
//日志打印
Log.e(TAG, "Delete Note error"); Log.e(TAG, "Delete Note error");
} }
} else { } else {
if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {
//日志打印
Log.e(TAG, "Move notes to trash folder error, should not happens"); Log.e(TAG, "Move notes to trash folder error, should not happens");
} }
} }
} }
mWorkingNote.markDeleted(true); mWorkingNote.markDeleted(true);
} }
//
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
@ -698,15 +625,22 @@ public class NoteEditActivity extends Activity implements OnClickListener,
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
//如果便签存在
if (mWorkingNote.getNoteId() > 0) { if (mWorkingNote.getNoteId() > 0) {
//创建意图
Intent intent = new Intent(this, AlarmReceiver.class); Intent intent = new Intent(this, AlarmReceiver.class);
//设置信息
intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));
//本质是intent的封装
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
//定时任务
AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));
showAlertHeader(); showAlertHeader();
if(!set) { if(!set) {
//如果没有设置则取消意图
alarmManager.cancel(pendingIntent); alarmManager.cancel(pendingIntent);
} else { } else {
//设置定时
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);
} }
} else { } else {
@ -716,6 +650,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* should input something * should input something
*/ */
Log.e(TAG, "Clock alert setting error"); Log.e(TAG, "Clock alert setting error");
//显示提示框
showToast(R.string.error_note_empty_for_clock); showToast(R.string.error_note_empty_for_clock);
} }
} }
@ -723,18 +658,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public void onWidgetChanged() { public void onWidgetChanged() {
updateWidget(); updateWidget();
} }
//删除编辑文本框
public void onEditTextDelete(int index, String text) { public void onEditTextDelete(int index, String text) {
int childCount = mEditTextList.getChildCount(); int childCount = mEditTextList.getChildCount();
if (childCount == 1) { if (childCount == 1) {
return; return;
} }
//遍历 设置index
for (int i = index + 1; i < childCount; i++) { for (int i = index + 1; i < childCount; i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i - 1); .setIndex(i - 1);
} }
//移除子控件
mEditTextList.removeViewAt(index); mEditTextList.removeViewAt(index);
NoteEditText edit = null; NoteEditText edit = null;
if(index == 0) { if(index == 0) {
@ -745,7 +680,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
R.id.et_edit_text); R.id.et_edit_text);
} }
int length = edit.length(); int length = edit.length();
//添加文本
edit.append(text); edit.append(text);
//获取聚焦
edit.requestFocus(); edit.requestFocus();
edit.setSelection(length); edit.setSelection(length);
} }
@ -754,14 +691,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
/** /**
* Should not happen, check for debug * Should not happen, check for debug
*/ */
//如果index超出了现有的数量则报错
if(index > mEditTextList.getChildCount()) { if(index > mEditTextList.getChildCount()) {
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
} }
//获取对应的view组件
View view = getListItem(text, index); View view = getListItem(text, index);
//动态添加view
mEditTextList.addView(view, index); mEditTextList.addView(view, index);
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
//请求获取焦点
edit.requestFocus(); edit.requestFocus();
//让list跳转到第一个组件显示
edit.setSelection(0); edit.setSelection(0);
for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
@ -770,6 +711,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
private void switchToListMode(String text) { private void switchToListMode(String text) {
mEditTextList.removeAllViews(); mEditTextList.removeAllViews();
String[] items = text.split("\n"); String[] items = text.split("\n");
int index = 0; int index = 0;
@ -779,17 +721,21 @@ public class NoteEditActivity extends Activity implements OnClickListener,
index++; index++;
} }
} }
//添加子控件
mEditTextList.addView(getListItem("", index)); mEditTextList.addView(getListItem("", index));
mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();
//设置可见性
mNoteEditor.setVisibility(View.GONE); mNoteEditor.setVisibility(View.GONE);
mEditTextList.setVisibility(View.VISIBLE); mEditTextList.setVisibility(View.VISIBLE);
} }
private Spannable getHighlightQueryResult(String fullText, String userQuery) { private Spannable getHighlightQueryResult(String fullText, String userQuery) {
//可以在字符序列基础上对指定的字符进行润饰
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
//如果userQuery不为空
if (!TextUtils.isEmpty(userQuery)) { if (!TextUtils.isEmpty(userQuery)) {
mPattern = Pattern.compile(userQuery); mPattern = Pattern.compile(userQuery);
//Matcher提供了对正则表达式的匹配
Matcher m = mPattern.matcher(fullText); Matcher m = mPattern.matcher(fullText);
int start = 0; int start = 0;
while (m.find(start)) { while (m.find(start)) {
@ -802,22 +748,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
return spannable; return spannable;
} }
//根据item index获取子控件
private View getListItem(String item, int index) { private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
//设置指定样式
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));
//监听复选框状态变化
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) { if (isChecked) {
//设置删除线
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else { } else {
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
} }
} }
}); });
//判断是否以指定字符串开头
if (item.startsWith(TAG_CHECKED)) { if (item.startsWith(TAG_CHECKED)) {
cb.setChecked(true); cb.setChecked(true);
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
@ -827,18 +776,21 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();
} }
//设置监听事件
edit.setOnTextViewChangeListener(this); edit.setOnTextViewChangeListener(this);
//设置相关属性
edit.setIndex(index); edit.setIndex(index);
edit.setText(getHighlightQueryResult(item, mUserQuery)); edit.setText(getHighlightQueryResult(item, mUserQuery));
return view; return view;
} }
//改变文本
public void onTextChange(int index, boolean hasText) { public void onTextChange(int index, boolean hasText) {
//判断index是否合法
if (index >= mEditTextList.getChildCount()) { if (index >= mEditTextList.getChildCount()) {
Log.e(TAG, "Wrong index, should not happen"); Log.e(TAG, "Wrong index, should not happen");
return; return;
} }
//如果存在文本 就获取相应的子控件
if(hasText) { if(hasText) {
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);
} else { } else {
@ -854,7 +806,9 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ",
"")); ""));
} }
//设置文本
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
//设置可见性
mEditTextList.setVisibility(View.GONE); mEditTextList.setVisibility(View.GONE);
mNoteEditor.setVisibility(View.VISIBLE); mNoteEditor.setVisibility(View.VISIBLE);
} }
@ -863,12 +817,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
private boolean getWorkingText() { private boolean getWorkingText() {
boolean hasChecked = false; boolean hasChecked = false;
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
//字符串类
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (int i = 0; i < mEditTextList.getChildCount(); i++) { for (int i = 0; i < mEditTextList.getChildCount(); i++) {
View view = mEditTextList.getChildAt(i); View view = mEditTextList.getChildAt(i);
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
//判断是否为空
if (!TextUtils.isEmpty(edit.getText())) { if (!TextUtils.isEmpty(edit.getText())) {
if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) {
//添加
sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");
hasChecked = true; hasChecked = true;
} else { } else {
@ -894,6 +851,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* new node requires to the top of the list. This code * new node requires to the top of the list. This code
* {@link #RESULT_OK} is used to identify the create/edit state * {@link #RESULT_OK} is used to identify the create/edit state
*/ */
//传回数据
setResult(RESULT_OK); setResult(RESULT_OK);
} }
return saved; return saved;
@ -906,13 +864,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* save it * save it
*/ */
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
//保存便签
saveNote(); saveNote();
} }
if (mWorkingNote.getNoteId() > 0) { if (mWorkingNote.getNoteId() > 0) {
//创建意图
Intent sender = new Intent(); Intent sender = new Intent();
Intent shortcutIntent = new Intent(this, NoteEditActivity.class); Intent shortcutIntent = new Intent(this, NoteEditActivity.class);
//设置启动对象
shortcutIntent.setAction(Intent.ACTION_VIEW); shortcutIntent.setAction(Intent.ACTION_VIEW);
//存放数据
shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId());
sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, sender.putExtra(Intent.EXTRA_SHORTCUT_NAME,
@ -930,6 +892,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
* should input something * should input something
*/ */
Log.e(TAG, "Send to desktop error"); Log.e(TAG, "Send to desktop error");
//显示消息提示框
showToast(R.string.error_note_empty_for_send_to_desktop); showToast(R.string.error_note_empty_for_send_to_desktop);
} }
} }

@ -1,18 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
@ -48,35 +33,35 @@ public class NoteEditText extends EditText {
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static { static {
// 不同的schema对应不同的操作提示
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
} }
/** /**
* Call by the {@link NoteEditActivity} to delete or add edit text * {@link NoteEditActivity}
*/ */
public interface OnTextViewChangeListener { public interface OnTextViewChangeListener {
/** /**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens * {@link KeyEvent#KEYCODE_DEL} null
* and the text is null
*/ */
void onEditTextDelete(int index, String text); void onEditTextDelete(int index, String text);
/** /**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} * {@link KeyEvent#KEYCODE_ENTER}
* happen
*/ */
void onEditTextEnter(int index, String text); void onEditTextEnter(int index, String text);
/** /**
* Hide or show item option when text change *
*/ */
void onTextChange(int index, boolean hasText); void onTextChange(int index, boolean hasText);
} }
private OnTextViewChangeListener mOnTextViewChangeListener; private OnTextViewChangeListener mOnTextViewChangeListener;
// 构造函数
public NoteEditText(Context context) { public NoteEditText(Context context) {
super(context, null); super(context, null);
mIndex = 0; mIndex = 0;
@ -90,13 +75,14 @@ public class NoteEditText extends EditText {
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
// 构造函数
public NoteEditText(Context context, AttributeSet attrs) { public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle); super(context, attrs, android.R.attr.editTextStyle);
} }
// 构造函数
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
} }
@Override @Override
@ -114,7 +100,7 @@ public class NoteEditText extends EditText {
Layout layout = getLayout(); Layout layout = getLayout();
int line = layout.getLineForVertical(y); int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x); int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off); Selection.setSelection(getText(), off); // 设置选中文本位置
break; break;
} }
@ -148,7 +134,7 @@ public class NoteEditText extends EditText {
return true; return true;
} }
} else { } else {
Log.d(TAG, "OnTextViewChangeListener was not seted"); Log.d(TAG, "OnTextViewChangeListener was not set");
} }
break; break;
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
@ -158,7 +144,7 @@ public class NoteEditText extends EditText {
setText(getText().subSequence(0, selectionStart)); setText(getText().subSequence(0, selectionStart));
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else { } else {
Log.d(TAG, "OnTextViewChangeListener was not seted"); Log.d(TAG, "OnTextViewChangeListener was not set");
} }
break; break;
default: default:
@ -205,7 +191,7 @@ public class NoteEditText extends EditText {
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() { new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
// goto a new intent // 转到新的意图
urls[0].onClick(NoteEditText.this); urls[0].onClick(NoteEditText.this);
return true; return true;
} }

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -25,23 +9,25 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
// 笔记项数据类
public class NoteItemData { public class NoteItemData {
// 查询列数组
static final String [] PROJECTION = new String [] { static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT, NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.SNIPPET, NoteColumns.SNIPPET,
NoteColumns.TYPE, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
// 列索引
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
@ -76,6 +62,7 @@ public class NoteItemData {
private boolean mIsOneNoteFollowingFolder; private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder; private boolean mIsMultiNotesFollowingFolder;
// 构造方法
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
@ -109,6 +96,7 @@ public class NoteItemData {
checkPostion(cursor); checkPostion(cursor);
} }
// 检查位置方法
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false;
@ -134,90 +122,112 @@ public class NoteItemData {
} }
} }
// 是否跟随文件夹中有一个笔记
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }
// 是否跟随文件夹中有多个笔记
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;
} }
// 是否最后一个
public boolean isLast() { public boolean isLast() {
return mIsLastItem; return mIsLastItem;
} }
// 获取通话联系人名字
public String getCallName() { public String getCallName() {
return mName; return mName;
} }
// 是否第一个
public boolean isFirst() { public boolean isFirst() {
return mIsFirstItem; return mIsFirstItem;
} }
// 是否仅为单个
public boolean isSingle() { public boolean isSingle() {
return mIsOnlyOneItem; return mIsOnlyOneItem;
} }
// 获取笔记项 ID
public long getId() { public long getId() {
return mId; return mId;
} }
// 获取提醒日期
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
// 获取创建日期
public long getCreatedDate() { public long getCreatedDate() {
return mCreatedDate; return mCreatedDate;
} }
// 是否有附件
public boolean hasAttachment() { public boolean hasAttachment() {
return mHasAttachment; return mHasAttachment;
} }
// 获取最近修改日期
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
// 获取背景颜色 ID
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 获取父项 ID
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
// 获取笔记数
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; return mNotesCount;
} }
// 获取文件夹 ID
public long getFolderId () { public long getFolderId () {
return mParentId; return mParentId;
} }
// 获取类型
public int getType() { public int getType() {
return mType; return mType;
} }
// 获取小部件类型
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 获取小部件 ID
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
// 获取摘要
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
// 是否有提醒
public boolean hasAlert() { public boolean hasAlert() {
return (mAlertDate > 0); return (mAlertDate > 0);
} }
// 是否为通话记录
public boolean isCallRecord() { public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
} }
// 根据游标获取笔记类型
public static int getNoteType(Cursor cursor) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }

@ -77,8 +77,12 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashSet; import java.util.HashSet;
//主界面,一进入就是这个界面
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { /**
* @author k
*
*/
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { //没有用特定的标签加注释。。。感觉没有什么用
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int FOLDER_LIST_QUERY_TOKEN = 1;
@ -89,7 +93,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final int MENU_FOLDER_CHANGE_NAME = 2;
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; //单行超过80个字符
private enum ListEditState { private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
@ -136,8 +140,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private final static int REQUEST_CODE_NEW_NODE = 103; private final static int REQUEST_CODE_NEW_NODE = 103;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { // 创建类
super.onCreate(savedInstanceState); protected void onCreate(final Bundle savedInstanceState) { //需要是final类型 根据程序上下文环境Java关键字final有“这是无法改变的”或者“终态的”含义它可以修饰非抽象类、非抽象类成员方法和变量。你可能出于两种理解而需要阻止改变设计或效率。
// final类不能被继承没有子类final类中的方法默认是final的。
//final方法不能被子类的方法覆盖但可以被继承。
//final成员变量表示常量只能被赋值一次赋值后值不再改变。
//final不能用于修饰构造方法。
super.onCreate(savedInstanceState); // 调用父类的onCreate函数
setContentView(R.layout.note_list); setContentView(R.layout.note_list);
initResources(); initResources();
@ -148,26 +157,32 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
@Override @Override
// 返回一些子模块完成的数据交给主Activity处理
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// 结果值 和 要求值 符合要求
if (resultCode == RESULT_OK if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
mNotesListAdapter.changeCursor(null); mNotesListAdapter.changeCursor(null);
} else { } else {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
// 调用 Activity 的onActivityResult
} }
} }
private void setAppInfoFromRawRes() { private void setAppInfoFromRawRes() {
// Android平台给我们提供了一个SharedPreferences类它是一个轻量级的存储类特别适合用于保存软件配置参数。
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
InputStream in = null; InputStream in = null;
try { try {
in = getResources().openRawResource(R.raw.introduction); // 把资源文件放到应用程序的/raw/raw下那么就可以在应用中使用getResources获取资源后,
// 以openRawResource方法不带后缀的资源文件名打开这个文件。
in = getResources().openRawResource(R.raw.introduction);
if (in != null) { if (in != null) {
InputStreamReader isr = new InputStreamReader(in); InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr);
char [] buf = new char[1024]; char [] buf = new char[1024]; // 自行定义的数值,使用者不知道有什么意义
int len = 0; int len = 0;
while ((len = br.read(buf)) > 0) { while ((len = br.read(buf)) > 0) {
sb.append(buf, 0, len); sb.append(buf, 0, len);
@ -180,7 +195,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
e.printStackTrace(); e.printStackTrace();
return; return;
} finally { } finally {
if(in != null) { if (in != null) {
try { try {
in.close(); in.close();
} catch (IOException e) { } catch (IOException e) {
@ -190,11 +205,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
// 创建空的WorkingNote
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED); ResourceParser.RED);
note.setWorkingText(sb.toString()); note.setWorkingText(sb.toString());
if (note.saveNote()) { if (note.saveNote()) {
// 更新保存note的信息
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else { } else {
Log.e(TAG, "Save introduction note error"); Log.e(TAG, "Save introduction note error");
@ -209,18 +226,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
startAsyncNotesListQuery(); startAsyncNotesListQuery();
} }
// 初始化资源
private void initResources() { private void initResources() {
mContentResolver = this.getContentResolver(); mContentResolver = this.getContentResolver(); // 获取应用程序的数据,得到类似数据表的东西
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mNotesListView = (ListView) findViewById(R.id.notes_list);
// findViewById 是安卓编程的定位函数,主要是引用.R文件里的引用名
mNotesListView = (ListView) findViewById(R.id.notes_list); // 绑定XML中的ListView作为Item的容器
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false); null, false);
mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemClickListener(new OnListItemClickListener());
mNotesListView.setOnItemLongClickListener(this); mNotesListView.setOnItemLongClickListener(this);
mNotesListAdapter = new NotesListAdapter(this); mNotesListAdapter = new NotesListAdapter(this);
mNotesListView.setAdapter(mNotesListAdapter); mNotesListView.setAdapter(mNotesListAdapter);
mAddNewNote = (Button) findViewById(R.id.btn_new_note); mAddNewNote = (Button) findViewById(R.id.btn_new_note);// 在activity中要获取该按钮
mAddNewNote.setOnClickListener(this); mAddNewNote.setOnClickListener(this);
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
mDispatch = false; mDispatch = false;
@ -231,6 +251,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mModeCallBack = new ModeCallback(); mModeCallBack = new ModeCallback();
} }
// 继承自ListView.MultiChoiceModeListener 和 OnMenuItemClickListener
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
private DropdownMenu mDropDownMenu; private DropdownMenu mDropDownMenu;
private ActionMode mActionMode; private ActionMode mActionMode;
@ -259,7 +280,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
(Button) customView.findViewById(R.id.selection_menu), (Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown); R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(final MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu(); updateMenu();
return true; return true;
@ -269,11 +290,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
// 更新菜单
private void updateMenu() { private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount(); int selectedCount = mNotesListAdapter.getSelectedCount();
// Update dropdown menu // Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount); String format = getResources().getString(R.string.menu_select_title, selectedCount);
mDropDownMenu.setTitle(format); mDropDownMenu.setTitle(format); // 更改标题
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
if (item != null) { if (item != null) {
if (mNotesListAdapter.isAllSelected()) { if (mNotesListAdapter.isAllSelected()) {
@ -307,7 +329,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) { boolean checked) {
mNotesListAdapter.setCheckedItem(position, checked); mNotesListAdapter.setCheckedItem(position, checked);
updateMenu(); updateMenu();
} }
@ -325,14 +347,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_notes, builder.setMessage(getString(R.string.alert_message_delete_notes,
mNotesListAdapter.getSelectedCount())); mNotesListAdapter.getSelectedCount()));
builder.setPositiveButton(android.R.string.ok, builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, public void onClick(DialogInterface dialog,
int which) { int which) {
batchDelete(); batchDelete();
} }
}); });
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();
break; break;
@ -366,7 +388,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
/** /**
* HACKME:When click the transparent part of "New Note" button, dispatch * HACKME:When click the transparent part of "New Note" button, dispatch
* the event to the list view behind this button. The transparent part of * 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 * "New Note" button could be expressed by formula y=-0.12x+94nit:pixel<EFBFBD>
* and the line top of the button. The coordinate based on left of the "New * 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. * Note" button. The 94 represents maximum height of the transparent part.
* Notice that, if the background of the button changes, the formula should * Notice that, if the background of the button changes, the formula should
@ -413,7 +435,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
: NORMAL_SELECTION; : NORMAL_SELECTION;
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
String.valueOf(mCurrentFolderId) String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
} }
@ -624,7 +646,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] { + "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId()) String.valueOf(mFocusNoteDataItem.getId())
}); });
} }
} else if (!TextUtils.isEmpty(name)) { } else if (!TextUtils.isEmpty(name)) {
@ -664,30 +686,38 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
} }
/* (non-Javadoc)
* @see android.app.Activity#onBackPressed()
*
*/
@Override @Override
public void onBackPressed() { public void onBackPressed() { switch (mState) {
switch (mState) { case SUB_FOLDER:
case SUB_FOLDER: mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST;
mState = ListEditState.NOTE_LIST; startAsyncNotesListQuery();
startAsyncNotesListQuery(); mTitleBar.setVisibility(View.GONE);
mTitleBar.setVisibility(View.GONE); break;
break; case CALL_RECORD_FOLDER:
case CALL_RECORD_FOLDER: mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST;
mState = ListEditState.NOTE_LIST; mAddNewNote.setVisibility(View.VISIBLE);
mAddNewNote.setVisibility(View.VISIBLE); mTitleBar.setVisibility(View.GONE);
mTitleBar.setVisibility(View.GONE); startAsyncNotesListQuery();
startAsyncNotesListQuery(); break;
break; case NOTE_LIST:
case NOTE_LIST: super.onBackPressed();
super.onBackPressed(); break;
break; default:
default: break;
break; }
}
} }
/**
* @param appWidgetId
* @param appWidgetType
* widgetintent
*/
private void updateWidget(int appWidgetId, int appWidgetType) { private void updateWidget(int appWidgetId, int appWidgetType) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) { if (appWidgetType == Notes.TYPE_WIDGET_2X) {
@ -700,13 +730,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
appWidgetId appWidgetId
}); });
sendBroadcast(intent); sendBroadcast(intent);
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
/**
*
*/
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
@ -726,6 +759,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
super.onContextMenuClosed(menu); super.onContextMenuClosed(menu);
} }
/* (non-Javadoc)
* @see android.app.Activity#onContextItemSelected(android.view.MenuItem)
* menu
*/
@Override @Override
public boolean onContextItemSelected(MenuItem item) { public boolean onContextItemSelected(MenuItem item) {
if (mFocusNoteDataItem == null) { if (mFocusNoteDataItem == null) {
@ -734,10 +771,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
switch (item.getItemId()) { switch (item.getItemId()) {
case MENU_FOLDER_VIEW: case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem); openFolder(mFocusNoteDataItem);//打开对应文件
break; break;
case MENU_FOLDER_DELETE: case MENU_FOLDER_DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);//设置确认是否删除的对话框
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setMessage(getString(R.string.alert_message_delete_folder));
@ -748,7 +785,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
}); });
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();//显示对话框
break; break;
case MENU_FOLDER_CHANGE_NAME: case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false); showCreateOrModifyFolderDialog(false);
@ -818,12 +855,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
/* (non-Javadoc)
* @see android.app.Activity#onSearchRequested()
* startSearch
*/
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false); startSearch(null, false, null /* appData */, false);
return true; return true;
} }
/**
* 便
*/
private void exportNoteToText() { private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() { new AsyncTask<Void, Void, Integer>() {
@ -866,16 +910,27 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute(); }.execute();
} }
/**
* @return
*
*/
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
/**
* PreferenceActivity
*/
private void startPreferenceActivity() { private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this; Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class); Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1); from.startActivityIfNeeded(intent, -1);
} }
/**
* @author k
* 便
*/
private class OnListItemClickListener implements OnItemClickListener { private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@ -917,10 +972,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
/**
*
*/
private void startQueryDestinationFolders() { private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection: selection = (mState == ListEditState.NOTE_LIST) ? selection:
"(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
null, null,
@ -935,6 +993,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
NoteColumns.MODIFIED_DATE + " DESC"); NoteColumns.MODIFIED_DATE + " DESC");
} }
/* (non-Javadoc)
* @see android.widget.AdapterView.OnItemLongClickListener#onItemLongClick(android.widget.AdapterView, android.view.View, int, long)
*
* 便ActionModeContextMenu
* ActionMOdeContextMenu
*/
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData(); mFocusNoteDataItem = ((NotesListItem) view).getItemData();
@ -952,3 +1016,4 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return false; return false;
} }
} }

@ -1,19 +1,3 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -30,19 +14,21 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
// 笔记列表适配器
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
private Context mContext; private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex; private HashMap<Integer, Boolean> mSelectedIndex; // 用于存储选中项的索引位置
private int mNotesCount; private int mNotesCount; // 笔记总数
private boolean mChoiceMode; private boolean mChoiceMode; // 选择模式标志
// 小部件属性类
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
public int widgetId; public int widgetId;
public int widgetType; public int widgetType;
}; };
// 构造方法
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); mSelectedIndex = new HashMap<Integer, Boolean>();
@ -64,20 +50,24 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
// 设置指定位置的项的选中状态
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked);
notifyDataSetChanged(); notifyDataSetChanged();
} }
// 是否处于选择模式
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }
// 设置选择模式
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
// 选择所有项
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
@ -89,13 +79,14 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
// 获取选中项的ID集合
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) { if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position); Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) { if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "错误的项ID不应该发生");
} else { } else {
itemSet.add(id); itemSet.add(id);
} }
@ -105,6 +96,7 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
// 获取选中的小部件集合
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
@ -116,11 +108,8 @@ public class NotesListAdapter extends CursorAdapter {
widget.widgetId = item.getWidgetId(); widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType(); widget.widgetType = item.getWidgetType();
itemSet.add(widget); itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*/
} else { } else {
Log.e(TAG, "Invalid cursor"); Log.e(TAG, "无效的游标");
return null; return null;
} }
} }
@ -128,6 +117,7 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
// 获取选中项数量
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
if (null == values) { if (null == values) {
@ -143,11 +133,13 @@ public class NotesListAdapter extends CursorAdapter {
return count; return count;
} }
// 是否全部选中
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount);
} }
// 判断指定位置的项是否被选中
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
@ -167,6 +159,7 @@ public class NotesListAdapter extends CursorAdapter {
calcNotesCount(); calcNotesCount();
} }
// 计算笔记总数
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
@ -176,7 +169,7 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount++; mNotesCount++;
} }
} else { } else {
Log.e(TAG, "Invalid cursor"); Log.e(TAG, "无效的游标");
return; return;
} }
} }

@ -1,122 +1,177 @@
/*
* 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; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
import android.text.format.DateUtils; import android.database.Cursor;
import android.util.Log;
import android.view.View; import android.view.View;
import android.widget.CheckBox; import android.view.ViewGroup;
import android.widget.ImageView; 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;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
public class NotesListItem extends LinearLayout { import java.util.Iterator;
private ImageView mAlert;
private TextView mTitle; // 笔记列表适配器
private TextView mTime; public class NotesListAdapter extends CursorAdapter {
private TextView mCallName; private static final String TAG = "NotesListAdapter";
private NoteItemData mItemData; private Context mContext;
private CheckBox mCheckBox; private HashMap<Integer, Boolean> mSelectedIndex; // 用于存储选中项的索引位置
private int mNotesCount; // 笔记总数
public NotesListItem(Context context) { private boolean mChoiceMode; // 选择模式标志
super(context);
inflate(context, R.layout.note_item, this); // 小部件属性类
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); public static class AppWidgetAttribute {
mTitle = (TextView) findViewById(R.id.tv_title); public int widgetId;
mTime = (TextView) findViewById(R.id.tv_time); public int widgetType;
mCallName = (TextView) findViewById(R.id.tv_name); };
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
// 构造方法
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context;
mNotesCount = 0;
} }
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { @Override
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
mCheckBox.setVisibility(View.VISIBLE); return new NotesListItem(context);
mCheckBox.setChecked(checked); }
} else {
mCheckBox.setVisibility(View.GONE); @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()));
} }
}
mItemData = data; // 设置指定位置的项的选中状态
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { public void setCheckedItem(final int position, final boolean checked) {
mCallName.setVisibility(View.GONE); mSelectedIndex.put(position, checked);
mAlert.setVisibility(View.VISIBLE); notifyDataSetChanged();
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); public boolean isInChoiceMode() {
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { return mChoiceMode;
mCallName.setVisibility(View.VISIBLE); }
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); // 设置选择模式
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); public void setChoiceMode(boolean mode) {
if (data.hasAlert()) { mSelectedIndex.clear();
mAlert.setImageResource(R.drawable.clock); mChoiceMode = mode;
mAlert.setVisibility(View.VISIBLE); }
} else {
mAlert.setVisibility(View.GONE); // 选择所有项
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);
}
} }
} else { }
mCallName.setVisibility(View.GONE); }
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 获取选中项的ID集合
if (data.getType() == Notes.TYPE_FOLDER) { public HashSet<Long> getSelectedItemIds() {
mTitle.setText(data.getSnippet() HashSet<Long> itemSet = new HashSet<Long>();
+ context.getString(R.string.format_folder_files_count, for (Integer position : mSelectedIndex.keySet()) {
data.getNotesCount())); if (mSelectedIndex.get(position) == true) {
mAlert.setVisibility(View.GONE); Long id = getItemId(position);
} else { if (id == Notes.ID_ROOT_FOLDER) {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); Log.d(TAG, "错误的项ID不应该发生");
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); itemSet.add(id);
} }
} }
} }
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data); return itemSet;
} }
private void setBackground(NoteItemData data) { // 获取选中的小部件集合
int id = data.getBgColorId(); public HashSet<AppWidgetAttribute> getSelectedWidget() {
if (data.getType() == Notes.TYPE_NOTE) { HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
if (data.isSingle() || data.isOneFollowingFolder()) { for (Integer position : mSelectedIndex.keySet()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); if (mSelectedIndex.get(position) == true) {
} else if (data.isLast()) { Cursor c = (Cursor) getItem(position);
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); if (c != null) {
} else if (data.isFirst() || data.isMultiFollowingFolder()) { AppWidgetAttribute widget = new AppWidgetAttribute();
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); NoteItemData item = new NoteItemData(mContext, c);
} else { widget.widgetId = item.getWidgetId();
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); widget.widgetType = item.getWidgetType();
itemSet.add(widget);
} else {
Log.e(TAG, "无效的游标");
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++;
} }
} else {
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
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() {
super.onContentChanged();
calcNotesCount();
}
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
} }
public NoteItemData getItemData() { // 计算笔记总数
return mItemData; private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
} else {
Log.e(TAG, "无效的游标");
return;
}
}
} }
} }

Loading…
Cancel
Save