diff --git a/doc b/doc deleted file mode 100644 index 66dc905..0000000 --- a/doc +++ /dev/null @@ -1 +0,0 @@ -undefined \ No newline at end of file diff --git a/doc/be5abc41718f641521841f593aef93e.png b/doc/be5abc41718f641521841f593aef93e.png new file mode 100644 index 0000000..c365b4c Binary files /dev/null and b/doc/be5abc41718f641521841f593aef93e.png differ diff --git a/doc/小米便签开源代码的泛读报告 (1).docx b/doc/小米便签开源代码的泛读报告 (1).docx new file mode 100644 index 0000000..5921b79 Binary files /dev/null and b/doc/小米便签开源代码的泛读报告 (1).docx differ diff --git a/src/注释.txt b/src/注释.txt new file mode 100644 index 0000000..e0a0e2b --- /dev/null +++ b/src/注释.txt @@ -0,0 +1,1463 @@ +/* + * 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 law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.app.Activity; +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.data.MetaData; +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.SqlNote; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + + +// GTaskManager 类用于管理 Google 任务的同步操作 +public class GTaskManager { + // 用于日志记录的类的简单名称 + private static final String TAG = GTaskManager.class.getSimpleName(); + + // 表示同步成功的状态码 + public static final int STATE_SUCCESS = 0; + // 表示网络错误的状态码 + public static final int STATE_NETWORK_ERROR = 1; + // 表示内部错误的状态码 + public static final int STATE_INTERNAL_ERROR = 2; + // 表示同步正在进行中的状态码 + public static final int STATE_SYNC_IN_PROGRESS = 3; + // 表示同步已取消的状态码 + public static final int STATE_SYNC_CANCELLED = 4; + + // 单例模式的 GTaskManager 实例 + private static GTaskManager mInstance = null; + + // 用于获取认证令牌等操作的关联 Activity + private Activity mActivity; + // 应用程序的上下文 + private Context mContext; + // 用于解析内容提供器数据的解析器 + private ContentResolver mContentResolver; + // 表示是否正在同步的标志 + private boolean mSyncing; + // 表示同步是否已取消的标志 + private boolean mCancelled; + // 存储 Google 任务列表的映射,键为任务列表的 ID,值为 TaskList 对象 + private HashMap mGTaskListHashMap; + // 存储 Google 任务的映射,键为任务的 ID,值为 Node 对象 + private HashMap mGTaskHashMap; + // 存储元数据的映射,键为元数据的 ID,值为 MetaData 对象 + private HashMap mMetaHashMap; + // 元数据列表 + private TaskList mMetaList; + // 存储本地删除项的 ID 集合 + private HashSet mLocalDeleteIdMap; + // 存储 Google 任务 ID 到本地任务 ID 的映射 + private HashMap mGidToNid; + // 存储本地任务 ID 到 Google 任务 ID 的映射 + private HashMap mNidToGid; + + // 私有构造函数,用于初始化 GTaskManager 的实例 + private GTaskManager() { + // 初始化同步状态为未同步 + mSyncing = false; + // 初始化取消状态为未取消 + mCancelled = false; + // 初始化存储 Google 任务列表的映射 + mGTaskListHashMap = new HashMap(); + // 初始化存储 Google 任务的映射 + mGTaskHashMap = new HashMap(); + // 初始化存储元数据的映射 + mMetaHashMap = new HashMap(); + // 初始化为空的元数据列表 + mMetaList = null; + // 初始化存储本地删除项的 ID 集合 + mLocalDeleteIdMap = new HashSet(); + // 初始化 Google 任务 ID 到本地任务 ID 的映射 + mGidToNid = new HashMap(); + // 初始化本地任务 ID 到 Google 任务 ID 的映射 + mNidToGid = new HashMap(); + } + + // 获取 GTaskManager 的单例实例 + public static synchronized GTaskManager getInstance() { + if (mInstance == null) { + mInstance = new GTaskManager(); + } + return mInstance; + } + + // 设置关联的 Activity 上下文,主要用于获取认证令牌 + public synchronized void setActivityContext(Activity activity) { + // 将传入的 Activity 赋值给成员变量,以便后续使用 + mActivity = activity; + } + + // 执行同步操作 + public int sync(Context context, GTaskASyncTask asyncTask) { + // 如果正在同步,记录日志并返回正在同步的状态码 + if (mSyncing) { + Log.d(TAG, "Sync is in progress"); + return STATE_SYNC_IN_PROGRESS; + } + // 存储传入的上下文 + mContext = context; + // 获取上下文的内容解析器 + mContentResolver = mContext.getContentResolver(); + // 标记为正在同步 + mSyncing = true; + // 标记为未取消同步 + mCancelled = false; + // 清空各种映射和集合,为同步做准备 + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + + try { + // 获取 GTaskClient 的实例 + GTaskClient client = GTaskClient.getInstance(); + // 重置更新数组 + client.resetUpdateArray(); + + // 如果未取消同步 + if (!mCancelled) { + // 尝试登录 Google 任务,如果登录失败则抛出网络异常 + if (!client.login(mActivity)) { + throw new NetworkFailureException("login google task failed"); + } + } + + // 发布同步进度:初始化任务列表 + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); + // 初始化 Google 任务列表 + initGTaskList(); + + // 发布同步进度:正在同步内容 + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); + // 执行内容同步操作 + syncContent(); + } catch (NetworkFailureException e) { + // 发生网络错误时记录错误日志并返回网络错误状态码 + Log.e(TAG, e.toString()); + return STATE_NETWORK_ERROR; + } catch (ActionFailureException e) { + // 发生操作失败异常时记录错误日志并返回内部错误状态码 + Log.e(TAG, e.toString()); + return STATE_INTERNAL_ERROR; + } catch (Exception e) { + // 其他异常时记录错误日志,打印堆栈信息并返回内部错误状态码 + Log.e(TAG, e.toString()); + e.printStackTrace(); + return STATE_INTERNAL_ERROR; + } finally { + // 无论同步是否成功,最终都要清空各种映射和集合,并标记为未同步 + mGTaskListHashMap.clear(); + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + mSyncing = false; + } + + // 根据是否取消同步返回相应的状态码 + return mCancelled? STATE_SYNC_CANCELLED : STATE_SUCCESS; + } + + // 初始化 Google 任务列表 + private void initGTaskList() throws NetworkFailureException { + // 如果同步已取消则直接返回 + if (mCancelled) + return; + // 获取 GTaskClient 的实例 + GTaskClient client = GTaskClient.getInstance(); + try { + // 获取 Google 任务列表的 JSON 数组 + JSONArray jsTaskLists = client.getTaskLists(); + + // 初始化为空的元数据列表 + mMetaList = null; + // 遍历任务列表的 JSON 数组 + for (int i = 0; i < jsTaskLists.length(); i++) { + // 获取每个任务列表的 JSON 对象 + JSONObject object = jsTaskLists.getJSONObject(i); + // 获取任务列表的 ID + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + // 获取任务列表的名称 + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + // 如果任务列表名称表示元数据文件夹 + if (name + .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { + // 创建新的任务列表对象 + mMetaList = new TaskList(); + // 根据远程 JSON 数据设置任务列表的内容 + mMetaList.setContentByRemoteJSON(object); + + // 获取元数据的 JSON 数组 + JSONArray jsMetas = client.getTaskList(gid); + // 遍历元数据的 JSON 数组 + for (int j = 0; j < jsMetas.length(); j++) { + // 获取元数据的 JSON 对象 + object = (JSONObject) jsMetas.getJSONObject(j); + // 创建元数据对象 + MetaData metaData = new MetaData(); + // 根据远程 JSON 数据设置元数据的内容 + metaData.setContentByRemoteJSON(object); + // 如果元数据值得保存 + if (metaData.isWorthSaving()) { + // 将元数据添加到元数据列表的子任务中 + mMetaList.addChildTask(metaData); + // 如果元数据有相关的 ID,则存储到元数据映射中 + if (metaData.getGid()!= null) { + mMetaHashMap.put(metaData.getRelatedGid(), metaData); + } + } + } + } + } + + // 如果元数据列表不存在,则创建一个新的元数据列表 + if (mMetaList == null) { + mMetaList = new TaskList(); + mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META); + GTaskClient.getInstance().createTaskList(mMetaList); + } + + // 遍历任务列表的 JSON 数组 + for (int i = 0; i < jsTaskLists.length(); i++) { + // 获取任务列表的 JSON 对象 + JSONObject object = jsTaskLists.getJSONObject(i); + // 获取任务列表的 ID + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + // 获取任务列表的名称 + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); + + // 如果任务列表名称以特定前缀开头且不是元数据文件夹 + if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) + &&!name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META)) { + // 创建新的任务列表对象 + TaskList tasklist = new TaskList(); + // 根据远程 JSON 数据设置任务列表的内容 + tasklist.setContentByRemoteJSON(object); + // 将任务列表存储到任务列表映射中 + mGTaskListHashMap.put(gid, tasklist); + // 将任务列表存储到任务映射中 + mGTaskHashMap.put(gid, tasklist); + + // 获取该任务列表下的任务的 JSON 数组 + JSONArray jsTasks = client.getTaskList(gid); + // 遍历任务的 JSON 数组 + for (int j = 0; j < jsTasks.length(); j++) { + // 获取任务的 JSON 对象 + object = (JSONObject) jsTasks.getJSONObject(j); + // 获取任务的 ID + gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); + // 创建新的任务对象 + Task task = new Task(); + // 根据远程 JSON 数据设置任务的内容 + task.setContentByRemoteJSON(object); + // 如果任务值得保存 + if (task.isWorthSaving()) { + // 设置任务的元数据信息 + task.setMetaInfo(mMetaHashMap.get(gid)); + // 将任务添加到任务列表的子任务中 + tasklist.addChildTask(task); + // 将任务存储到任务映射中 + mGTaskHashMap.put(gid, task); + } + } + } + } + } catch (JSONException e) { + // 处理 JSON 解析异常,记录错误日志,打印堆栈信息并抛出操作失败异常 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("initGTaskList: handing JSONObject failed"); + } + } + + // 同步内容操作 + private void syncContent() throws NetworkFailureException { + int syncType; + Cursor c = null; + String gid; + Node node; + + // 清空本地删除项的 ID 集合 + mLocalDeleteIdMap.clear(); + + // 如果同步已取消则返回 + if (mCancelled) { + return; + } + + // 处理本地已删除的笔记 + try { + // 查询本地已删除的笔记 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id=?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, null); + if (c!= null) { + while (c.moveToNext()) { + // 获取 Google 任务的 ID + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + // 根据任务 ID 获取任务节点 + node = mGTaskHashMap.get(gid); + if (node!= null) { + // 从任务映射中移除该任务节点 + mGTaskHashMap.remove(gid); + // 执行删除远程节点的内容同步操作 + doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c); + } + // 将本地笔记的 ID 添加到本地删除项的 ID 集合中 + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + } + } else { + Log.w(TAG, "failed to query trash folder"); + } + } finally { + // 关闭游标 + if (c!= null) { + c.close(); + c = null; + } + } + + // 同步文件夹 + syncFolder(); + + // 处理数据库中存在的笔记 + try { + // 查询数据库中存在的笔记 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type=? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c!= null) { + while (c.moveToNext()) { + // 获取 Google 任务的 ID + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + // 根据任务 ID 获取任务节点 + node = mGTaskHashMap.get(gid); + if (node!= null) { + // 从任务映射中移除该任务节点 + mGTaskHashMap.remove(gid); + // 将任务 ID 映射存储到本地任务 ID 到 Google 任务 ID 的映射中 + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); + // 将任务 ID 映射存储到 Google 任务 ID 到本地任务 ID 的映射中 + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); + // 获取同步操作类型 + syncType = node.getSyncAction(c); + } else { + // 如果 Google 任务 ID 为空,则是本地添加操作 + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { + syncType = Node.SYNC_ACTION_ADD_REMOTE; + } else { + // 否则是远程删除操作 + syncType = Node.SYNC_ACTION_DEL_LOCAL; + } + } + // 执行相应的内容同步操作 + doContentSync(syncType, node, c); + } + } else { + Log.w(TAG, "failed to query existing note in database"); + } + + } finally { + // 关闭游标 + if (c!= null) { + c.close(); + c = null; + } + } + + // 遍历剩余的任务节点 + Iterator> iter = mGTaskHashMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = iter.next(); + node = entry.getValue(); + // 执行添加本地节点的内容同步操作 + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); + } + + // 如果未取消同步 + if (!mCancelled) { + // 批量删除本地删除项,如果失败则抛出操作失败异常 + if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { + throw new ActionFailureException("failed to batch-delete local deleted notes"); + } + } + + // 如果未取消同步 + if (!mCancelled) { + // 提交更新 + GTaskClient.getInstance().commitUpdate(); + // 刷新本地同步 ID + refreshLocalSyncId(); + } + + } + + // 同步文件夹操作 + private void syncFolder() throws NetworkFailureException { + Cursor c = null; + String gid; + Node node; + int syncType; + + // 如果同步已取消则返回 + if (mCancelled) { + return; + } + + // 处理根文件夹 + try { + // 查询根文件夹 + c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); + if (c!= null) { + c.moveToNext(); + // 获取 Google 任务的 ID + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + // 根据任务 ID 获取任务节点 + node = mGTaskHashMap.get(gid); + if (node!= null) { + // 从任务映射中移除该任务节点 + mGTaskHashMap.remove(gid); + // 存储根文件夹的任务 ID 映射 + mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); + mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); + // 如果节点名称不是默认的系统文件夹名称,则更新远程名称 + if (!node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + // 执行添加远程节点的内容同步操作 + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } else { + Log.w(TAG, "failed to query root folder"); + } + } finally { + // 关闭游标 + if (c!= null) { + c.close(); + c = null; + } + } + + // 处理通话记录文件夹 + try { + // 查询通话记录文件夹 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", + new String[] { + String.valueOf(Notes.ID_CALL_RECORD_FOLDER) + }, null); + if (c!= null) { + if (c.moveToNext()) { + // 获取 Google 任务的 ID + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + // 根据任务 ID 获取任务节点 + node = mGTaskHashMap.get(gid); + if (node!= null) { + // 从任务映射中移除该任务节点 + mGTaskHashMap.remove(gid); + // 存储通话记录文件夹的任务 ID 映射 + mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); + mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); + // 如果节点名称不是通话记录文件夹的名称,则更新远程名称 + if (!node.getName().equals( + GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_CALL_NOTE)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + // 执行添加远程节点的内容同步操作 + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c); + } + } + } else { + Log.w(TAG, "failed to query call note folder"); + } + } finally { + // 关闭游标 + if (c!= null) { + c.close(); + c = null; + } + } + + // 处理本地存在的文件夹 +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.app.Activity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.ui.NotesPreferenceActivity; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.apache.http.protocol.HTTP; +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.io.UnsupportedEncodingException; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream; + + +// GTaskClient 类,负责与 Google 任务服务进行网络通信和相关操作 +public class GTaskClient { + // 日志标签,用于记录日志 + private static final String TAG = GTaskClient.class.getSimpleName(); + + // Google 任务的基本 URL + private static final String GTASK_URL = "https://mail.google.com/tasks/"; + // 获取任务的 URL + private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; + // 提交任务操作的 URL + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; + + // 单例实例 + private static GTaskClient mInstance = null; + + // HTTP 客户端 + private DefaultHttpClient mHttpClient; + // 获取任务的完整 URL + private String mGetUrl; + // 提交任务操作的完整 URL + private String mPostUrl; + // 客户端版本号 + private long mClientVersion; + // 登录状态 + private boolean mLoggedin; + // 最后登录时间 + private long mLastLoginTime; + // 操作 ID + private int mActionId; + // 关联的账户 + private Account mAccount; + // 存储更新操作的 JSON 数组 + private JSONArray mUpdateArray; + + // 私有构造函数,初始化各种成员变量 + private GTaskClient() { + // 初始化为空的 HTTP 客户端 + mHttpClient = null; + // 设置获取任务的默认 URL + mGetUrl = GTASK_GET_URL; + // 设置提交任务操作的默认 URL + mPostUrl = GTASK_POST_URL; + // 初始化为 -1 的客户端版本号 + mClientVersion = -1; + // 初始化为未登录状态 + mLoggedin = false; + // 初始化为 0 的最后登录时间 + mLastLoginTime = 0; + // 初始化为 1 的操作 ID + mActionId = 1; + // 初始化为空的账户 + mAccount = null; + // 初始化为空的更新操作数组 + mUpdateArray = null; + } + + // 获取 GTaskClient 的单例实例 + public static synchronized GTaskClient getInstance() { + if (mInstance == null) { + mInstance = new GTaskClient(); + } + return mInstance; + } + + // 登录操作 + public boolean login(Activity activity) { + // 假设 cookie 在 5 分钟后过期,需要重新登录 + final long interval = 1000 * 60 * 5; + if (mLastLoginTime + interval < System.currentTimeMillis()) { + mLoggedin = false; + } + + // 账户切换后需要重新登录 + if (mLoggedin + &&!TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity + .getSyncAccountName(activity))) { + mLoggedin = false; + } + + // 如果已经登录,记录日志并返回登录成功 + if (mLoggedin) { + Log.d(TAG, "already logged in"); + return true; + } + + // 更新最后登录时间 + mLastLoginTime = System.currentTimeMillis(); + // 登录 Google 账户,获取认证令牌 + String authToken = loginGoogleAccount(activity, false); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + // 如果是自定义域名,尝试登录 Google 任务 + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() + .endsWith("googlemail.com"))) { + StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); + int index = mAccount.name.indexOf('@') + 1; + String suffix = mAccount.name.substring(index); + url.append(suffix + "/"); + mGetUrl = url.toString() + "ig"; + mPostUrl = url.toString() + "r/ig"; + + if (tryToLoginGtask(activity, authToken)) { + mLoggedin = true; + } + } + + // 尝试使用 Google 官方 URL 登录 + if (!mLoggedin) { + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + if (!tryToLoginGtask(activity, authToken)) { + return false; + } + } + + // 标记为已登录 + mLoggedin = true; + return true; + } + + // 登录 Google 账户 + private String loginGoogleAccount(Activity activity, boolean invalidateToken) { + String authToken; + // 获取账户管理器 + AccountManager accountManager = AccountManager.get(activity); + // 获取所有 Google 账户 + Account[] accounts = accountManager.getAccountsByType("com.google"); + + if (accounts.length == 0) { + Log.e(TAG, "there is no available google account"); + return null; + } + + // 获取同步账户名称 + String accountName = NotesPreferenceActivity.getSyncAccountName(activity); + Account account = null; + // 查找与设置中相同名称的账户 + for (Account a : accounts) { + if (a.name.equals(accountName)) { + account = a; + break; + } + } + if (account!= null) { + mAccount = account; + } else { + Log.e(TAG, "unable to get an account with the same name in the settings"); + return null; + } + + // 获取认证令牌 + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account, + "goanna_mobile", null, activity, null, null); + try { + Bundle authTokenBundle = accountManagerFuture.getResult(); + authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); + if (invalidateToken) { + // 使认证令牌失效并重新登录 + accountManager.invalidateAuthToken("com.google", authToken); + loginGoogleAccount(activity, false); + } + } catch (Exception e) { + Log.e(TAG, "get auth token failed"); + authToken = null; + } + + return authToken; + } + + // 尝试登录 Google 任务 + private boolean tryToLoginGtask(Activity activity, String authToken) { + if (!loginGtask(authToken)) { + // 认证令牌可能过期,使其失效并重新登录 + authToken = loginGoogleAccount(activity, true); + if (authToken == null) { + Log.e(TAG, "login google account failed"); + return false; + } + + if (!loginGtask(authToken)) { + Log.e(TAG, "login gtask failed"); + return false; + } + } + return true; + } + + // 执行登录 Google 任务操作 + private boolean loginGtask(String authToken) { + // 设置连接和套接字超时时间 + int timeoutConnection = 10000; + int timeoutSocket = 15000; + HttpParams httpParameters = new BasicHttpParams(); + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); + mHttpClient = new DefaultHttpClient(httpParameters); + BasicCookieStore localBasicCookieStore = new BasicCookieStore(); + mHttpClient.setCookieStore(localBasicCookieStore); + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); + + // 登录 Google 任务 + try { + String loginUrl = mGetUrl + "?auth=" + authToken; + HttpGet httpGet = new HttpGet(loginUrl); + HttpResponse response = null; + response = mHttpClient.execute(httpGet); + + // 获取 cookie + List cookies = mHttpClient.getCookieStore().getCookies(); + boolean hasAuthCookie = false; + for (Cookie cookie : cookies) { + if (cookie.getName().contains("GTL")) { + hasAuthCookie = true; + } + } + if (!hasAuthCookie) { + Log.w(TAG, "it seems that there is no auth cookie"); + } + + // 获取客户端版本号 + String resString = getResponseContent(response.getEntity()); + String jsBegin = "_setup("; + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin!= -1 && end!= -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + return false; + } catch (Exception e) { + Log.e(TAG, "httpget gtask_url failed"); + return false; + } + + return true; + } + + // 获取操作 ID + private int getActionId() { + return mActionId++; + } + + // 创建 HTTP POST 请求 + private HttpPost createHttpPost() { + HttpPost httpPost = new HttpPost(mPostUrl); + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); + httpPost.setHeader("AT", "1"); + return httpPost; + } + + // 获取响应内容 + private String getResponseContent(HttpEntity entity) throws IOException { + String contentEncoding = null; + if (entity.getContentEncoding()!= null) { + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding); + } + + InputStream input = entity.getContent(); + if (contentEncoding!= null && contentEncoding.equalsIgnoreCase("gzip")) { + input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding!= null && contentEncoding.equalsIgnoreCase("deflate")) { + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater); + } + + try { + InputStreamReader isr = new InputStreamReader(input); + BufferedReader br = new BufferedReader(isr); + StringBuilder sb = new StringBuilder(); + + while (true) { + String buff = br.readLine(); + if (buff == null) { + return sb.toString(); + } + sb = sb.append(buff); + } + } finally { + input.close(); + } + } + + // 发送 POST 请求 + private JSONObject postRequest(JSONObject js) throws NetworkFailureException { + if (!mLoggedin) { + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + HttpPost httpPost = createHttpPost(); + try { + LinkedList list = new LinkedList(); + // 将 JSON 对象添加到 POST 请求中 + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); + httpPost.setEntity(entity); + + // 执行 POST 请求 + HttpResponse response = mHttpClient.execute(httpPost); + String jsString = getResponseContent(response.getEntity()); + return new JSONObject(jsString); + + } catch (ClientProtocolException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("unable to convert response content to jsonobject"); + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("error occurs when posting request"); + } + } + + // 创建任务 + public void createTask(Task task) throws NetworkFailureException { + // 提交更新 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // 添加创建任务的操作到操作列表 + actionList.put(task.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // 设置客户端版本号 + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // 发送 POST 请求 + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + // 设置任务的全局 ID + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create task: handing jsonobject failed"); + } + } + + // 创建任务列表 + public void createTaskList(TaskList tasklist) throws NetworkFailureException { + // 提交更新 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // 添加创建任务列表的操作到操作列表 + actionList.put(tasklist.getCreateAction(getActionId())); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // 设置客户端版本号 + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // 发送 POST 请求 + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + // 设置任务列表的全局 ID + tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create tasklist: handing jsonobject failed"); + } + } + + // 提交更新操作 + public void commitUpdate() throws NetworkFailureException { + if (mUpdateArray!= null) { + try { + JSONObject jsPost = new JSONObject(); + + // 添加操作列表 + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); + + // 设置客户端版本号 + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // 发送 POST 请求 + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("commit update: handing jsonobject failed"); + } + } + } + + // 添加或更新节点 + public void addUpdateNode(Node node) throws NetworkFailureException { + if (node!= null) { + // 为避免更新项过多导致错误,设置最大更新项为 10 个 + if (mUpdateArray!= null && mUpdateArray.length() > 10) { + commitUpdate(); + } + + if (mUpdateArray == null) + mUpdateArray = new JSONArray(); + // 添加节点的更新操作 + mUpdateArray.put(node.getUpdateAction(getActionId())); + } + } + + // 移动任务 + public void moveTask(Task task, TaskList preParent, TaskList curParent) + throws NetworkFailureException { + // 提交更新 + commitUpdate(); + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // 设置移动任务的操作类型 + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling()!= null) { + // 如果在任务列表内移动且不是第一个任务,设置前置兄弟任务 ID + action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); + } + action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); + action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); + if (preParent!= curParent) { + // 如果在任务列表间移动,设置目标列表 ID + action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); + } + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // 设置客户端版本号 + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + // 发送 POST 请求 + postRequest(jsPost); + + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("move task: handing jsonobject failed"); + } +/* + * 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.app.Widget.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; + + +// NoteEditActivity 类是一个用于编辑笔记的 Activity 类 +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + // 用于存储头部视图组件的内部类 + private class HeadViewHolder { + public TextView tvModified; + public ImageView ivAlertIcon; + public TextView tvAlertDate; + public ImageView ibSetBgColor; + } + + // 存储背景颜色选择按钮和对应颜色资源 ID 的映射 + private static final Map sBgSelectorBtnsMap = new HashMap(); + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); + } + + // 存储背景颜色选择按钮和对应选中标识视图 ID 的映射 + private static final Map sBgSelectorSelectionMap = new HashMap(); + static { + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); + } + + // 存储字体大小选择按钮和对应字体大小资源 ID 的映射 + private static final Map sFontSizeBtnsMap = new HashMap(); + static { + 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_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + } + + // 存储字体大小选择按钮和对应选中标识视图 ID 的映射 + private static final Map sFontSelectorSelectionMap = new HashMap(); + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_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_SUPER, R.id.iv_super_select); + } + + // 日志标签 + private static final String TAG = "NoteEditActivity"; + + // 头部视图的持有者 + private HeadViewHolder mNoteHeaderHolder; + // 头部视图面板 + private View mHeadViewPanel; + // 笔记背景颜色选择器 + private View mNoteBgColorSelector; + // 字体大小选择器 + private View mFontSizeSelector; + // 笔记编辑的 EditText 组件 + private EditText mNoteEditor; + // 笔记编辑面板 + private View mNoteEditorPanel; + // 正在编辑的笔记对象 + private WorkingNote mWorkingNote; + // 共享偏好设置 + private SharedPreferences mSharedPrefs; + // 字体大小 ID + private int mFontSizeId; + // 偏好设置中存储字体大小的键 + private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; + // 勾选标记 + public static final String TAG_CHECKED = String.valueOf('\u221A'); + // 未勾选标记 + public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); + // 存储 EditText 列表的 LinearLayout + private LinearLayout mEditTextList; + // 用户搜索查询内容 + private String mUserQuery; + // 用于搜索匹配的模式 + private Pattern mPattern; + + // 当 Activity 被创建时调用 + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + // 设置布局 + this.setContentView(R.layout.note_edit); + + // 初始化 Activity 状态,如果初始化失败则结束 Activity + if (savedInstanceState == null &&!initActivityState(getIntent())) { + finish(); + return; + } + // 初始化资源 + initResources(); + } + + // 当从低内存状态恢复时调用 + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + // 如果存在保存的状态且包含 UID,则根据该状态恢复 Activity 状态 + if (savedInstanceState!= null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + // 初始化 Activity 状态 + private boolean initActivityState(Intent intent) { + mWorkingNote = null; + // 当动作为查看时 + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + // 从搜索结果开始 + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); + } + + // 检查笔记是否在数据库中可见,如果不可见则跳转并显示错误信息 + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { + Intent jump = new Intent(this, NotesListActivity.class); + startActivity(jump); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + // 加载笔记,如果加载失败则结束 Activity + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load note failed with note id" + noteId); + finish(); + return false; + } + } + // 设置软键盘显示模式 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + } else if (TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { + // 创建新笔记 + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this)); + + // 解析通话记录笔记 + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); + if (callDate!= 0 && phoneNumber!= null) { + if (TextUtils.isEmpty(phoneNumber)) { + Log.w(TAG, "The call record number is null"); + } + long noteId = 0; + // 根据电话号码和通话日期获取笔记 ID + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), + phoneNumber, callDate)) > 0) { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + // 创建空的通话记录笔记 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + // 创建空笔记 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + // 设置软键盘显示模式 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support"); + finish(); + return false; + } + // 设置笔记设置状态改变的监听器 + mWorkingNote.setOnSettingStatusChangedListener(this); + return true; + } + + // 当 Activity 恢复时调用 + @Override + protected void onResume() { + super.onResume(); + // 初始化笔记屏幕显示 + initNoteScreen(); + } + + // 初始化笔记屏幕显示 + private void initNoteScreen() { + // 设置笔记编辑器的字体外观 + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId)); + // 如果是清单模式,切换为列表模式显示内容 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(mWorkingNote.getContent()); + } else { + // 高亮显示搜索结果 + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mNoteEditor.setSelection(mNoteEditor.getText().length()); + } + // 隐藏所有背景颜色选择的选中标识 + for (Integer id : sBgSelectorSelectionMap.keySet()) { + findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); + } + // 设置背景颜色 + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + + // 设置修改日期显示 + mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, + mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE + | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME + | DateUtils.FORMAT_SHOW_YEAR)); + + // 显示提醒头部信息 + showAlertHeader(); + } + + // 显示提醒头部信息 + private void showAlertHeader() { + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis(); + if (time > mWorkingNote.getAlertDate()) { + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); + } else { + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); + } else { + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); + } + } + + // 当新的 Intent 被调用时 + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + // 重新初始化 Activity 状态 + initActivityState(intent); + } + + // 当 Activity 即将被销毁时保存状态 + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + // 对于新笔记先保存以生成 ID + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + // 分发触摸事件 + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + // 当背景颜色选择器可见且触摸事件不在其范围内时,隐藏选择器 + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE + &&!inRangeOfView(mNoteBgColorSelector, ev)) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } + + // 当字体大小选择器可见且触摸事件不在其范围内时,隐藏选择器 + if (mFontSizeSelector.getVisibility() == View.VISIBLE + &&!inRangeOfView(mFontSizeSelector, ev)) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return super.dispatchTouchEvent(ev); + } + + // 判断触摸事件是否在视图范围内 + private boolean inRangeOfView(View view, MotionEvent ev) { + int[] location = new int[2]; + view.getLocationOnScreen(location); + int x = location[0]; + int y = location[1]; + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + } + return true; + } + + // 初始化资源 + private void initResources() { + mHeadViewPanel = findViewById(R.id.note_title); + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); + mNoteEditor = (EditText) findViewById(R.id.note_edit_view); + mNoteEditorPanel = findViewById(R.id.sv_note_edit); + mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); + + \ No newline at end of file diff --git a/str b/str deleted file mode 100644 index 66dc905..0000000 --- a/str +++ /dev/null @@ -1 +0,0 @@ -undefined \ No newline at end of file