我将我之前所处理的部分提交到main里面来了

main
zhangjinhan 8 months ago
parent dc8ac4e874
commit f154c9b770

@ -33,7 +33,7 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
// 代表一个笔记,包含笔记的基本信息和笔记数据
public class Note { public class Note {
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
private NoteData mNoteData; private NoteData mNoteData;
@ -70,36 +70,44 @@ public class Note {
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);
} }
// 设置文本笔记的数据ID
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);
} }
// 设置通话笔记的数据
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
} }
// 判断笔记是否被本地修改过
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
// 同步笔记到数据库
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -130,6 +138,7 @@ public class Note {
return true; return true;
} }
// 笔记数据类,包含文本数据和通话数据
private class NoteData { private class NoteData {
private long mTextDataId; private long mTextDataId;
@ -148,10 +157,12 @@ public class Note {
mCallDataId = 0; mCallDataId = 0;
} }
// 判断笔记数据是否被本地修改过
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
// 设置文本数据ID
void setTextDataId(long id) { void setTextDataId(long id) {
if(id <= 0) { if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +170,7 @@ public class Note {
mTextDataId = id; mTextDataId = id;
} }
// 设置通话数据ID
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,18 +178,21 @@ public class Note {
mCallDataId = id; mCallDataId = id;
} }
// 设置通话数据
void setCallData(String key, String value) { void setCallData(String key, String value) {
mCallDataValues.put(key, value); mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
// 设置文本数据
void setTextData(String key, String value) { void setTextData(String key, String value) {
mTextDataValues.put(key, value); mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
// 将笔记数据推送到内容解析器
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety

@ -31,7 +31,7 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote; import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; import net.micode.notes.tool.ResourceParser.NoteBgResources;
// 表示正在编辑的笔记类
public class WorkingNote { public class WorkingNote {
// Note for the working note // Note for the working note
private Note mNote; private Note mNote;
@ -62,6 +62,7 @@ public class WorkingNote {
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据库查询笔记数据的列
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -72,6 +73,7 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 数据库查询笔记信息的列
public 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,
@ -101,7 +103,7 @@ public class WorkingNote {
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct // 新笔记构造方法
private WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0;
@ -114,7 +116,7 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
// Existing note construct // 已有笔记构造方法
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
mNoteId = noteId; mNoteId = noteId;
@ -124,6 +126,7 @@ public class WorkingNote {
loadNote(); loadNote();
} }
// 从数据库加载笔记信息
private void loadNote() { private void loadNote() {
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
@ -146,6 +149,7 @@ public class WorkingNote {
loadNoteData(); loadNoteData();
} }
// 从数据库加载笔记数据
private void loadNoteData() { private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
@ -174,6 +178,7 @@ public class WorkingNote {
} }
} }
// 创建一个空笔记
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
@ -183,10 +188,12 @@ public class WorkingNote {
return note; return note;
} }
// 从数据库加载笔记
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
// 保存笔记到数据库
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
if (isWorthSaving()) { if (isWorthSaving()) {
if (!existInDatabase()) { if (!existInDatabase()) {
@ -212,10 +219,12 @@ public class WorkingNote {
} }
} }
// 判断笔记是否存在于数据库中
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
// 判断笔记是否值得保存
private boolean isWorthSaving() { private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +234,12 @@ public class WorkingNote {
} }
} }
// 设置笔记信息改变监听器
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
// 设置闹钟提醒日期
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -239,6 +250,7 @@ public class WorkingNote {
} }
} }
// 标记笔记是否已删除
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
mIsDeleted = mark; mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
@ -247,6 +259,7 @@ public class WorkingNote {
} }
} }
// 设置笔记背景颜色ID
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
@ -257,6 +270,7 @@ public class WorkingNote {
} }
} }
// 设置笔记的检查列表模式
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
@ -267,6 +281,7 @@ public class WorkingNote {
} }
} }
// 设置笔记的窗口小部件类型
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
@ -274,6 +289,7 @@ public class WorkingNote {
} }
} }
// 设置笔记的窗口小部件ID
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
@ -281,6 +297,7 @@ public class WorkingNote {
} }
} }
// 设置工作文本内容
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
@ -288,60 +305,74 @@ public class WorkingNote {
} }
} }
// 将笔记转换为通话笔记
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
// 检查笔记是否有闹钟提醒
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
// 获取笔记内容
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
// 获取闹钟提醒日期
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
// 获取笔记修改日期
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
// 获取笔记背景颜色资源ID
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
// 获取笔记背景颜色ID
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 获取笔记标题背景颜色资源ID
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
// 获取检查列表模式
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
// 获取笔记ID
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
// 获取笔记所在的文件夹ID
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
// 获取窗口小部件ID
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
// 获取窗口小部件类型
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 笔记信息改变监听器接口
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed

@ -1,18 +1,17 @@
```java
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Apache License, Version 2.0 * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
@ -36,13 +35,13 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
// 备份工具类,用于将笔记数据备份到文本文件中。 // 备份工具类,用于将笔记数据导出为文本文件
public class BackupUtils { public class BackupUtils {
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils";
// 单例模式 // 单例实例
private static BackupUtils sInstance; private static BackupUtils sInstance;
// 获取BackupUtils的单例,如果不存在则创建。 // 获取BackupUtils的单例实例
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);
@ -51,49 +50,48 @@ public class BackupUtils {
} }
/** /**
* *
*/ */
// SD卡未挂载 // SD卡未挂载
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0;
// 备份文件不存在 // 备份文件不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// 数据格式不正确,可能被其他程序更改 // 数据损坏或格式不正确
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
// 运行时异常导致备份或恢复失败 // 系统错误导致备份或恢复失败
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
// 备份或恢复成功 // 备份或恢复成功
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
private TextExport mTextExport; private TextExport mTextExport;
// 私有构造函数用于创建BackupUtils实例。 // 构造函数初始化TextExport实例
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());
} }
// 导出笔记数据到文本文件。 // 导出笔记数据为文本文件
public int exportToText() { public int exportToText() {
return mTextExport.exportToText(); return mTextExport.exportToText();
} }
// 获取导出的文本文件名 // 获取导出的文本文件名
public String getExportedTextFileName() { public String getExportedTextFileName() {
return mTextExport.mFileName; return mTextExport.mFileName;
} }
// 获取导出的文本文件目录 // 获取导出的文本文件目录
public String getExportedTextFileDir() { public String getExportedTextFileDir() {
return mTextExport.mFileDirectory; return mTextExport.mFileDirectory;
} }
// 内部类,用于将笔记数据导出到文本。 // 文本导出类,用于将笔记数据导出为文本格式
private static class TextExport { private static class TextExport {
// 笔记数据投影数组。
private static final String[] NOTE_PROJECTION = { private static final String[] NOTE_PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
@ -101,12 +99,12 @@ public class BackupUtils {
NoteColumns.TYPE NoteColumns.TYPE
}; };
// 数据列索引。
private static final int NOTE_COLUMN_ID = 0; private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2; private static final int NOTE_COLUMN_SNIPPET = 2;
// 数据数据投影数组。
private static final String[] DATA_PROJECTION = { private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT, DataColumns.CONTENT,
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE,
@ -116,25 +114,24 @@ public class BackupUtils {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 数据列索引。
private static final int DATA_COLUMN_CONTENT = 0; private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1; private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2; private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 导出文本的格式数组。 private final String [] TEXT_FORMAT;
private final String[] TEXT_FORMAT; private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_FOLDER_NAME = 0; private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_DATE = 1; private static final int FORMAT_NOTE_CONTENT = 2;
private static final int FORMAT_NOTE_CONTENT = 2;
// 上下文对象,用于访问资源和内容解析器。
private Context mContext; private Context mContext;
// 导出文件的名称和目录。
private String mFileName; private String mFileName;
private String mFileDirectory; private String mFileDirectory;
// 构造函数,初始化上下文和格式数组。 // 构造函数,初始化导出格式和上下文
public TextExport(Context context) { public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; mContext = context;
@ -142,29 +139,27 @@ public class BackupUtils {
mFileDirectory = ""; mFileDirectory = "";
} }
// 根据ID获取对应的格式字符串。 // 根据ID获取导出格式字符串
private String getFormat(int id) { private String getFormat(int id) {
return TEXT_FORMAT[id]; return TEXT_FORMAT[id];
} }
/** // 导出指定文件夹下的笔记到文本文件
* ID
*/
private void exportFolderToText(String folderId, PrintStream ps) { private void exportFolderToText(String folderId, PrintStream ps) {
// 查询属于该文件夹的笔记 // 查询属于该文件夹的笔记
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 {
// 打印笔记最后修改日期 // 打印笔记最后修改日期
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))));
// 查询属于该笔记的数据 // 查询属于该笔记的数据
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());
@ -173,13 +168,11 @@ public class BackupUtils {
} }
} }
/** // 导出指定笔记到文本输出流
* ID
*/
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);
if (dataCursor != null) { if (dataCursor != null) {
@ -216,7 +209,7 @@ public class BackupUtils {
} }
dataCursor.close(); dataCursor.close();
} }
// 打印笔记之间的分隔线。 // 打印笔记之间的分隔
try { try {
ps.write(new byte[] { ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -226,35 +219,32 @@ public class BackupUtils {
} }
} }
/** // 将笔记数据导出为用户可读的文本文件
*
*/
public int exportToText() { public int exportToText() {
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "媒体未挂载"); Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED; return STATE_SD_CARD_UNMOUONTED;
} }
PrintStream ps = getExportToTextPrintStream(); PrintStream ps = getExportToTextPrintStream();
if (ps == null) { if (ps == null) {
Log.e(TAG, "获取打印流出错"); Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR;
} }
// 首先导出文件夹及其笔记 // 首先导出文件夹及其笔记
Cursor folderCursor = mContext.getContentResolver().query( Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
null, null);
if (folderCursor != null) { if (folderCursor != null) {
if (folderCursor.moveToFirst()) { if (folderCursor.moveToFirst()) {
do { do {
// 打印文件夹名称 // 打印文件夹名称
String folderName = ""; String folderName = "";
if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name); folderName = mContext.getString(R.string.call_record_folder_name);
} else { } else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
@ -269,21 +259,20 @@ public class BackupUtils {
folderCursor.close(); folderCursor.close();
} }
// 导出根文件夹中的笔记。 // 导出根文件夹下的笔记
// 导出根文件夹中的笔记
Cursor noteCursor = mContext.getContentResolver().query( Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0", null, null); NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
if (noteCursor != null) { if (noteCursor != null) {
if (noteCursor.moveToFirst()) { if (noteCursor.moveToFirst()) {
do { do {
// 打印笔记最后修改日期
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),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于这条笔记的数据 // 查询属于笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID); String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext()); } while (noteCursor.moveToNext());
@ -292,19 +281,15 @@ public class BackupUtils {
} }
ps.close(); ps.close();
// 返回成功状态码
return STATE_SUCCESS; return STATE_SUCCESS;
} }
/** // 获取指向导出文本文件的PrintStream
*
*/
private PrintStream getExportToTextPrintStream() { private PrintStream getExportToTextPrintStream() {
// 生成存储导出数据的文本文件
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format); R.string.file_name_txt_format);
if (file == null) { if (file == null) {
Log.e(TAG, "创建导出文件失败"); Log.e(TAG, "create file to exported failed");
return null; return null;
} }
mFileName = file.getName(); mFileName = file.getName();
@ -324,33 +309,32 @@ public class BackupUtils {
} }
} }
/** // 生成用于存储导入数据的文本文件
* SD private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
*/ StringBuilder sb = new StringBuilder();
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { sb.append(Environment.getExternalStorageDirectory());
StringBuilder sb = new StringBuilder(); sb.append(context.getString(filePathResId));
sb.append(Environment.getExternalStorageDirectory()); File filedir = new File(sb.toString());
sb.append(context.getString(filePathResId)); sb.append(context.getString(
File filedir = new File(sb.toString()); fileNameFormatResId,
sb.append(context.getString( DateFormat.format(context.getString(R.string.format_date_ymd),
fileNameFormatResId, System.currentTimeMillis())));
DateFormat.format(context.getString(R.string.format_date_ymd), File file = new File(sb.toString());
System.currentTimeMillis())));
File file = new File(sb.toString()); try {
if (!filedir.exists()) {
try { filedir.mkdir();
if (!filedir.exists()) { }
filedir.mkdir(); if (!file.exists()) {
} file.createNewFile();
if (!file.exists()) { }
file.createNewFile(); return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null; return null;
}
} }

@ -1,16 +1,17 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
* Apache License, Version 2.0 * 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 * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
@ -33,25 +34,25 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
// 数据工具类,提供对笔记数据的操作函数 // 数据工具类,提供批量删除笔记、移动笔记到文件夹等操作
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
// 批量删除笔记 // 批量删除笔记
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) { if (ids == null) {
Log.d(TAG, "id集合为空"); Log.d(TAG, "the ids is null");
return true; return true;
} }
if (ids.size() == 0) { if (ids.size() == 0) {
Log.d(TAG, "id集合中没有元素"); Log.d(TAG, "no id is in the hashset");
return true; return true;
} }
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) {
if (id == Notes.ID_ROOT_FOLDER) { if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "不要删除系统根文件夹"); Log.e(TAG, "Don't delete system folder root");
continue; continue;
} }
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
@ -61,7 +62,7 @@ public class DataUtils {
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, "删除笔记失败, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
} }
return true; return true;
@ -86,7 +87,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, "id集合为空"); Log.d(TAG, "the ids is null");
return true; return true;
} }
@ -102,7 +103,7 @@ public class DataUtils {
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, "移动笔记失败, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
} }
return true; return true;
@ -115,22 +116,22 @@ public class DataUtils {
} }
/** /**
* *
*/ */
public static int getUserFolderCount(ContentResolver resolver) { public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
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);
int count = 0; int count = 0;
if (cursor != null) { if(cursor != null) {
if (cursor.moveToFirst()) { if(cursor.moveToFirst()) {
try { try {
count = cursor.getInt(0); count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取文件夹数量失败:" + e.toString()); Log.e(TAG, "get folder count failed:" + e.toString());
} finally { } finally {
cursor.close(); cursor.close();
} }
@ -139,12 +140,12 @@ public class DataUtils {
return count; return count;
} }
// 检查笔记在数据库中是否可见 // 检查指定类型的笔记是否可见
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
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);
boolean exist = false; boolean exist = false;
@ -157,7 +158,7 @@ public class DataUtils {
return exist; return exist;
} }
// 检查笔记在数据库中是否存在 // 检查笔记是否存数据库中
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null); null, null, null, null);
@ -172,7 +173,7 @@ public class DataUtils {
return exist; return exist;
} }
// 检查数据在数据库中是否存在 // 检查数据是否存数据库中
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null); null, null, null, null);
@ -187,16 +188,16 @@ public class DataUtils {
return exist; return exist;
} }
// 检查文件夹名称是否可见 // 检查指定名称的用户文件夹是否存在
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) {
exist = true; exist = true;
} }
cursor.close(); cursor.close();
@ -204,7 +205,7 @@ public class DataUtils {
return exist; return exist;
} }
// 获取文件夹笔记的小部件属性 // 获取指定文件夹下的笔记小部件信息
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
@ -234,80 +235,74 @@ public class DataUtils {
// 根据笔记ID获取通话号码 // 根据笔记ID获取通话号码
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE }, new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null); null);
// 如果游标不为空并且移动到第一行,则尝试获取通话号码
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
return cursor.getString(0); // 返回获取到的字符串 return cursor.getString(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取通话号码失败:" + e.toString()); // 记录异常信息 Log.e(TAG, "Get call number fails " + e.toString());
} finally { } finally {
cursor.close(); // 确保游标被关闭 cursor.close();
} }
} }
return ""; // 如果失败,返回空字符串 return "";
}
// 根据电话号码和通话日期获取笔记ID // 根据通话号码和通话日期获取笔记ID
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
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);
// 如果游标不为空并且移动到第一行则尝试获取笔记ID
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
try { try {
return cursor.getLong(0); // 返回获取到的长整型数 return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取通话笔记ID失败" + e.toString()); // 记录异常信息 Log.e(TAG, "Get call note id fails " + e.toString());
} }
} }
cursor.close(); // 确保游标被关闭 cursor.close();
} }
return 0; // 如果失败返回0 return 0;
} }
// 根据笔记ID获取摘要 // 根据笔记ID获取笔记摘要
public static String getSnippetById(ContentResolver resolver, long noteId) { public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?", NoteColumns.ID + "=?",
new String[] { String.valueOf(noteId) }, new String [] { String.valueOf(noteId)},
null); null);
// 如果游标不为空并且移动到第一行,则尝试获取摘要
if (cursor != null) { if (cursor != null) {
String snippet = ""; String snippet = "";
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
snippet = cursor.getString(0); // 获取摘要 snippet = cursor.getString(0);
} }
cursor.close(); // 确保游标被关闭 cursor.close();
return snippet; // 返回摘要 return snippet;
} }
throw new IllegalArgumentException("未找到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');
if (index != -1) { if (index != -1) {
snippet = snippet.substring(0, index); // 截取换行符之前的字符串 snippet = snippet.substring(0, index);
} }
} }
return snippet; // 返回格式化后的摘要 return snippet;
} }
} }

@ -16,145 +16,99 @@
package net.micode.notes.tool; package net.micode.notes.tool;
// GTaskStringUtils类主要用于定义一些与Google Tasks相关操作中使用的字符串常量方便在代码中统一引用和管理 // 此类用于定义和存储GTask相关的JSON字段名常量
public class GTaskStringUtils { public class GTaskStringUtils {
// 表示操作的唯一ID的JSON键名用于在与Google Tasks交互的JSON数据中标识某个具体操作的ID
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";
// 表示操作列表的JSON键名用于在与Google Tasks交互的JSON数据中存放一组操作的集合通常是一个JSON数组
public final static String GTASK_JSON_ACTION_LIST = "action_list"; public final static String GTASK_JSON_ACTION_LIST = "action_list";
// 表示操作类型的JSON键名用于在与Google Tasks交互的JSON数据中指定某个操作具体是什么类型的操作比如创建、获取、移动等
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; public final static String GTASK_JSON_ACTION_TYPE = "action_type";
// 表示创建操作类型的具体值,对应创建相关的操作,例如创建任务、创建任务列表等操作时使用该值来标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
// 表示获取所有(任务等)操作类型的具体值,用于获取某个任务列表下的所有任务等情况时标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
// 表示移动操作类型的具体值,用于在移动任务、任务列表等位置时标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
// 表示更新操作类型的具体值,用于对任务、任务列表等进行更新操作时标识操作类型
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// 表示创建者ID的JSON键名用于在与Google Tasks交互的JSON数据中存放创建某个任务、任务列表等的用户ID信息
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// 表示子实体的JSON键名可能用于在涉及包含子元素的结构如任务列表包含多个任务等情况标识子实体相关信息
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// 表示客户端版本号的JSON键名用于在与Google Tasks交互的JSON数据中告知服务器当前客户端的版本信息便于进行兼容性等相关处理
public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// 表示是否完成的JSON键名可能用于任务等实体中标识该任务是否已经完成的状态信息
public final static String GTASK_JSON_COMPLETED = "completed"; public final static String GTASK_JSON_COMPLETED = "completed";
// 表示当前列表ID的JSON键名可能用于在涉及多列表切换、关联等场景时标识当前所在的任务列表的ID
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// 表示默认列表ID的JSON键名用于标识某个用户、某个应用场景下的默认任务列表的ID信息
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// 表示是否已删除的JSON键名用于在任务、任务列表等实体中标识其是否已经被删除的状态信息
public final static String GTASK_JSON_DELETED = "deleted"; public final static String GTASK_JSON_DELETED = "deleted";
// 表示目标列表的JSON键名在进行移动操作等涉及改变所属列表的操作时用于指定要移动到的目标任务列表的ID
public final static String GTASK_JSON_DEST_LIST = "dest_list"; public final static String GTASK_JSON_DEST_LIST = "dest_list";
// 表示目标父级的JSON键名在进行移动操作、关联操作等涉及改变父级元素的情况时用于指定要移动到或关联的目标父级元素的相关信息比如任务列表等
public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// 表示目标父级类型的JSON键名可能用于进一步明确目标父级元素的具体类型例如是任务列表类型还是其他类型等
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// 表示实体差异的JSON键名可能用于在对比、更新实体时标识实体之间发生变化的部分相关信息
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// 表示实体类型的JSON键名用于在与Google Tasks交互的JSON数据中明确某个实体如任务、任务列表等具体是什么类型
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// 表示是否获取已删除的JSON键名在进行查询操作时用于指定是否要获取已经被标记为删除的任务、任务列表等信息
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// 表示唯一ID的JSON键名通常用于标识任务、任务列表等实体在Google Tasks系统中的全局唯一标识符
public final static String GTASK_JSON_ID = "id"; public final static String GTASK_JSON_ID = "id";
// 表示索引的JSON键名可能用于在任务列表中标识某个任务的排列顺序等索引相关信息
public final static String GTASK_JSON_INDEX = "index"; public final static String GTASK_JSON_INDEX = "index";
// 表示最后修改时间的JSON键名用于记录任务、任务列表等实体最后一次被修改的时间信息便于进行同步、更新等操作时的判断
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// 表示最新同步点的JSON键名可能用于记录与Google Tasks进行数据同步时的最新同步时间点等相关信息便于后续判断同步范围、增量等情况
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// 表示列表ID的JSON键名常用于标识某个具体的任务列表的ID信息与其他相关操作配合使用比如获取某个列表下的任务等操作
public final static String GTASK_JSON_LIST_ID = "list_id"; public final static String GTASK_JSON_LIST_ID = "list_id";
// 表示任务列表复数形式的JSON键名用于在与Google Tasks交互的JSON数据中存放多个任务列表信息的集合通常是一个JSON数组
public final static String GTASK_JSON_LISTS = "lists"; public final static String GTASK_JSON_LISTS = "lists";
// 表示名称的JSON键名用于任务、任务列表等实体中存放它们的名称信息方便展示、识别等操作
public final static String GTASK_JSON_NAME = "name"; public final static String GTASK_JSON_NAME = "name";
// 表示新ID的JSON键名可能在某些创建、更新操作后用于存放新生成的实体ID信息比如创建任务后返回的新任务ID等情况
public final static String GTASK_JSON_NEW_ID = "new_id"; public final static String GTASK_JSON_NEW_ID = "new_id";
// 表示备注笔记的JSON键名可能用于存放与任务相关的一些备注、说明等文本信息
public final static String GTASK_JSON_NOTES = "notes"; public final static String GTASK_JSON_NOTES = "notes";
// 表示父级ID的JSON键名用于在任务、任务列表等实体中标识其所属的父级元素的ID信息建立层级关系
public final static String GTASK_JSON_PARENT_ID = "parent_id"; public final static String GTASK_JSON_PARENT_ID = "parent_id";
// 表示前一个兄弟节点任务等ID的JSON键名在任务列表中用于标识某个任务之前相邻的兄弟任务的ID常用于排序、移动等操作场景
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// 表示操作结果的JSON键名在执行某些操作如批量操作等用于存放操作的结果信息通常是一个JSON数组
public final static String GTASK_JSON_RESULTS = "results"; public final static String GTASK_JSON_RESULTS = "results";
// 表示源列表的JSON键名在进行移动操作等涉及改变所属列表的操作时用于指定操作前所在的原始任务列表的ID
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// 表示任务复数形式的JSON键名用于在与Google Tasks交互的JSON数据中存放多个任务信息的集合通常是一个JSON数组
public final static String GTASK_JSON_TASKS = "tasks"; public final static String GTASK_JSON_TASKS = "tasks";
// 表示类型的JSON键名用于在与Google
// Tasks交互的JSON数据中明确某个实体如任务、任务列表等具体是什么类型和GTASK_JSON_ENTITY_TYPE作用类似但使用场景可能稍有不同
public final static String GTASK_JSON_TYPE = "type"; public final static String GTASK_JSON_TYPE = "type";
// 表示分组类型的具体值,用于标识某个实体是分组类型(例如任务分组等情况)
public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
// 表示任务类型的具体值,用于明确某个实体是任务类型,方便在代码中进行类型判断等操作
public final static String GTASK_JSON_TYPE_TASK = "TASK"; public final static String GTASK_JSON_TYPE_TASK = "TASK";
// 表示用户的JSON键名可能用于存放与操作相关的用户信息比如执行操作的用户账号等情况
public final static String GTASK_JSON_USER = "user"; public final static String GTASK_JSON_USER = "user";
// MIUI系统中笔记相关的文件夹前缀字符串用于在名称等地方标识该文件夹是属于MIUI笔记应用相关的文件夹
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 表示默认文件夹名称的字符串常量,用于标识默认的任务列表、文件夹等的名称
public final static String FOLDER_DEFAULT = "Default"; public final static String FOLDER_DEFAULT = "Default";
// 表示通话记录笔记文件夹名称的字符串常量,用于明确该文件夹是存放通话记录相关笔记的
public final static String FOLDER_CALL_NOTE = "Call_Note"; public final static String FOLDER_CALL_NOTE = "Call_Note";
// 表示元数据文件夹名称的字符串常量,用于标识存放元数据相关内容的文件夹名称
public final static String FOLDER_META = "METADATA"; public final static String FOLDER_META = "METADATA";
// 表示元数据中Google Tasks ID的键名可能用于在元数据结构中关联对应的Google Tasks实体的ID信息
public final static String META_HEAD_GTASK_ID = "meta_gid"; public final static String META_HEAD_GTASK_ID = "meta_gid";
// 表示元数据中笔记相关内容的键名,用于在元数据结构中存放与笔记相关的具体信息
public final static String META_HEAD_NOTE = "meta_note"; public final static String META_HEAD_NOTE = "meta_note";
// 表示元数据中数据相关内容的键名,用于在元数据结构中存放一些额外的数据信息(可能是和任务、笔记等相关的数据集合等情况)
public final static String META_HEAD_DATA = "meta_data"; public final static String META_HEAD_DATA = "meta_data";
// 表示元数据笔记名称的字符串常量,同时提示不要更新和删除该元数据笔记(可能是具有特殊用途的固定元数据相关说明)
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
} }

@ -14,7 +14,6 @@
* limitations under the License. * limitations under the License.
*/ */
// 该类所属的包名表明这个类位于net.micode.notes.tool包下用于提供一些资源相关的解析和获取功能
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
@ -23,61 +22,57 @@ import android.preference.PreferenceManager;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
// ResourceParser类主要用于对应用中的各种资源如背景图片、文本样式等进行管理和提供获取方法方便在不同的界面等场景中使用
public class ResourceParser { public class ResourceParser {
// 定义颜色相关的常量,用整数表示不同的颜色选项,方便在代码中进行统一的颜色选择和判断,这里分别对应黄色、蓝色、白色、绿色、红色 // 定义笔记背景颜色的常量
public static final int YELLOW = 0; public static final int YELLOW = 0;
public static final int BLUE = 1; public static final int BLUE = 1;
public static final int WHITE = 2; public static final int WHITE = 2;
public static final int GREEN = 3; public static final int GREEN = 3;
public static final int RED = 4; public static final int RED = 4;
// 定义默认的背景颜色常量其值为黄色对应上面定义的颜色常量中的YELLOW表示在没有特殊设置时默认使用的背景颜色 // 默认笔记背景颜色
public static final int BG_DEFAULT_COLOR = YELLOW; public static final int BG_DEFAULT_COLOR = YELLOW;
// 定义文本大小相关的常量,用整数表示不同的文本大小选项,方便在代码中统一处理文本大小相关的设置和获取,这里分别对应小、中、大、超大文本尺寸 // 定义笔记文本大小的常量
public static final int TEXT_SMALL = 0; public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1; public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2; public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3; public static final int TEXT_SUPER = 3;
// 定义默认的字体大小常量其值为中等大小对应上面定义的文本大小常量中的TEXT_MEDIUM表示在没有特殊设置时默认使用的字体大小 // 默认笔记背景文本大小
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// 内部静态类NoteBgResources用于管理笔记编辑界面相关的背景资源图片资源 // 用于获取编辑笔记时的背景资源
public static class NoteBgResources { public static class NoteBgResources {
// 定义一个私有的静态整型数组存储笔记编辑界面背景图片资源的ID对应不同颜色的编辑界面背景图片顺序与前面定义的颜色常量顺序一致 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
}; };
// 定义一个私有的静态整型数组存储笔记编辑界面标题背景图片资源的ID对应不同颜色的编辑界面标题背景图片顺序与前面定义的颜色常量顺序一致 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
}; };
// 根据传入的颜色ID(对应前面定义的颜色常量)获取笔记编辑界面的背景图片资源ID方便在设置编辑界面背景时使用 // 根据ID获取编辑笔记的背景资源
public static int getNoteBgResource(int id) { public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id]; return BG_EDIT_RESOURCES[id];
} }
// 根据传入的颜色ID(对应前面定义的颜色常量)获取笔记编辑界面标题的背景图片资源ID方便在设置编辑界面标题背景时使用 // 根据ID获取编辑笔记标题的背景资源
public static int getNoteTitleBgResource(int id) { public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id];
} }
} }
// 根据传入的上下文Context获取默认的背景图片ID逻辑是先检查是否在偏好设置中设置了自定义背景颜色通过特定的偏好设置键来判断 // 获取默认笔记背景颜色ID
// 如果设置了则随机选择一个背景资源ID从NoteBgResources中定义的资源数组长度范围内随机否则返回默认的背景颜色IDBG_DEFAULT_COLOR
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)) {
@ -87,113 +82,105 @@ public class ResourceParser {
} }
} }
// 内部静态类NoteItemBgResources用于管理笔记列表项相关的背景资源图片资源 // 用于获取笔记列表项的背景资源
public static class NoteItemBgResources { public static class NoteItemBgResources {
// 定义一个私有的静态整型数组存储笔记列表项第一个元素可能是列表头部等情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 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
}; };
// 定义一个私有的静态整型数组存储笔记列表项中间元素正常的列表项情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 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
}; };
// 定义一个私有的静态整型数组存储笔记列表项最后一个元素可能是列表尾部等情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 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,
}; };
// 定义一个私有的静态整型数组存储单个笔记可能是独立展示等情况的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 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
}; };
// 根据传入的颜色ID对应前面定义的颜色常量获取笔记列表项第一个元素的背景图片资源ID方便在设置列表项背景时使用 // 根据ID获取笔记列表第一项的背景资源
public static int getNoteBgFirstRes(int id) { public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id]; return BG_FIRST_RESOURCES[id];
} }
// 根据传入的颜色ID对应前面定义的颜色常量获取笔记列表项最后一个元素的背景图片资源ID方便在设置列表项背景时使用 // 根据ID获取笔记列表最后一项的背景资源
public static int getNoteBgLastRes(int id) { public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id]; return BG_LAST_RESOURCES[id];
} }
// 根据传入的颜色ID(对应前面定义的颜色常量)获取单个笔记的背景图片资源ID方便在设置单个笔记背景时使用 // 根据ID获取单个笔记的背景资源
public static int getNoteBgSingleRes(int id) { public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id]; return BG_SINGLE_RESOURCES[id];
} }
// 根据传入的颜色ID(对应前面定义的颜色常量)获取笔记列表中间元素(正常列表的背景图片资源ID方便在设置列表项背景时使用 // 根据ID获取笔记列表中间项的背景资源
public static int getNoteBgNormalRes(int id) { public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id]; return BG_NORMAL_RESOURCES[id];
} }
// 获取文件夹背景图片资源ID用于设置文件夹在列表等展示场景中的背景图片 // 获取文件夹背景资源
public static int getFolderBgRes() { public static int getFolderBgRes() {
return R.drawable.list_folder; return R.drawable.list_folder;
} }
} }
// 内部静态类WidgetBgResources用于管理桌面小部件相关的背景资源图片资源 // 用于获取小部件的背景资源
public static class WidgetBgResources { public static class WidgetBgResources {
// 定义一个私有的静态整型数组存储2x尺寸桌面小部件的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 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,
}; };
// 根据传入的颜色ID(对应前面定义的颜色常量)获取2x尺寸桌面小部件的背景图片资源ID方便在设置小部件背景时使用 // 根据ID获取2x小部件的背景资源
public static int getWidget2xBgResource(int id) { public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id]; return BG_2X_RESOURCES[id];
} }
// 定义一个私有的静态整型数组存储4x尺寸桌面小部件的背景图片资源ID对应不同颜色的背景图片顺序与前面定义的颜色常量顺序一致 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
}; };
// 根据传入的颜色ID(对应前面定义的颜色常量)获取4x尺寸桌面小部件的背景图片资源ID方便在设置小部件背景时使用 // 根据ID获取4x小部件的背景资源
public static int getWidget4xBgResource(int id) { public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id]; return BG_4X_RESOURCES[id];
} }
} }
// 内部静态类TextAppearanceResources用于管理文本外观相关的资源主要是文本样式资源 // 用于获取文本外观资源
public static class TextAppearanceResources { public static class TextAppearanceResources {
// 定义一个私有的静态整型数组存储不同文本外观样式的资源ID对应不同大小的文本外观样式顺序与前面定义的文本大小常量顺序有一定关联 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获取对应的文本外观资源ID如果传入的ID大于资源数组的长度可能是由于存储或获取出现异常情况 // 根据ID获取文本外观资源
// 则返回默认的字体大小对应的资源IDBG_DEFAULT_FONT_SIZE以避免出现资源获取错误
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.
@ -206,7 +193,7 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id]; return TEXTAPPEARANCE_RESOURCES[id];
} }
// 获取文本外观资源数组长度,可用于判断资源数量或者进行一些边界相关的操作判断等 // 获取文本外观资源的数量
public static int getResourcesSize() { public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length; return TEXTAPPEARANCE_RESOURCES.length;
} }

@ -39,21 +39,29 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
/**
* ActivityOnClickListenerOnDismissListener
*
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; private long mNoteId; // 保存笔记的ID
private String mSnippet; private String mSnippet; // 保存笔记的摘要
private static final int SNIPPET_PREW_MAX_LEN = 60; private static final int SNIPPET_PREW_MAX_LEN = 60; // 笔记摘要的最大长度
MediaPlayer mPlayer; MediaPlayer mPlayer; // 用于播放闹钟声音的MediaPlayer实例
/**
*
* @param savedInstanceState
*/
@Override @Override
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
@ -61,98 +69,123 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
} }
Intent intent = getIntent(); Intent intent = getIntent(); // 获取启动该活动的Intent
try { try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 从Intent中提取笔记ID
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); // 根据笔记ID获取摘要
// 如果摘要长度超过最大限制则截取前SNIPPET_PREW_MAX_LEN个字符并添加省略号
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)
: mSnippet; : mSnippet;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace(); // 打印异常信息
return; return; // 如果发生异常,则结束该方法
} }
mPlayer = new MediaPlayer(); mPlayer = new MediaPlayer(); // 创建MediaPlayer实例
// 检查数据库中是否存在指定ID的笔记
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog(); showActionDialog(); // 显示操作对话框
playAlarmSound(); playAlarmSound(); // 播放闹钟声音
} else { } else {
finish(); finish(); // 如果笔记不存在,则结束该活动
} }
} }
/**
*
* @return truefalse
*/
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
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);
// 如果静音模式影响了闹钟音频流则设置MediaPlayer的音频流类型为silentModeStreams
// 否则设置为AudioManager.STREAM_ALARM
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams); mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
} }
try { try {
mPlayer.setDataSource(this, url); mPlayer.setDataSource(this, url); // 设置MediaPlayer的数据源为闹钟铃声URI
mPlayer.prepare(); mPlayer.prepare(); // 准备MediaPlayer
mPlayer.setLooping(true); mPlayer.setLooping(true); // 设置MediaPlayer循环播放
mPlayer.start(); mPlayer.start(); // 开始播放闹钟声音
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} catch (SecurityException e) { } catch (SecurityException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace(); // 打印异常信息
e.printStackTrace();
} }
} }
/**
*
*/
private void showActionDialog() { private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog.Builder dialog = new AlertDialog.Builder(this); // 创建AlertDialog.Builder实例
dialog.setTitle(R.string.app_name); dialog.setTitle(R.string.app_name); // 设置对话框标题为应用名称
dialog.setMessage(mSnippet); dialog.setMessage(mSnippet); // 设置对话框消息为笔记摘要
dialog.setPositiveButton(R.string.notealert_ok, this); dialog.setPositiveButton(R.string.notealert_ok, this); // 设置确定按钮及其监听器
// 如果屏幕已点亮,则添加进入按钮及其监听器
if (isScreenOn()) { if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this); dialog.setNegativeButton(R.string.notealert_enter, this);
} }
dialog.show().setOnDismissListener(this); dialog.show().setOnDismissListener(this); // 显示对话框并设置对话框消失监听器
} }
/**
* OnClickListener
* @param dialog
* @param which ID
*/
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:
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class); // 创建Intent准备跳转到笔记编辑活动
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW); // 设置Intent动作类型为ACTION_VIEW
intent.putExtra(Intent.EXTRA_UID, mNoteId); intent.putExtra(Intent.EXTRA_UID, mNoteId); // 添加笔记ID作为附加信息
startActivity(intent); startActivity(intent); // 启动笔记编辑活动
break; break;
default: default:
break; break;
} }
} }
/**
* OnDismissListener
* @param dialog
*/
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
stopAlarmSound(); stopAlarmSound(); // 停止播放闹钟声音
finish(); finish(); // 结束该活动
} }
/**
* MediaPlayer
*/
private void stopAlarmSound() { private void stopAlarmSound() {
if (mPlayer != null) { if (mPlayer != null) {
mPlayer.stop(); mPlayer.stop(); // 停止MediaPlayer播放
mPlayer.release(); mPlayer.release(); // 释放MediaPlayer资源
mPlayer = null; mPlayer = null; // 将mPlayer置为null
} }
} }
} }

@ -27,17 +27,20 @@ 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;
private static final int COLUMN_ALERTED_DATE = 1; private static final int COLUMN_ALERTED_DATE = 1;
// 接收广播时执行的方法,查询数据库并设置闹钟
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis(); long currentDate = System.currentTimeMillis();

@ -20,11 +20,16 @@ import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
// 一个继承自BroadcastReceiver的类用于接收闹钟触发的广播
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
// 当接收到广播时,该方法会被调用
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 设置Intent的目标Activity为AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
// 添加标志以允许启动新的Activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动AlarmAlertActivity
context.startActivity(intent); context.startActivity(intent);
} }
} }

@ -21,6 +21,263 @@ import java.util.Calendar;
import net.micode.notes.R; import net.micode.notes.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
// DateTimePicker类继承自FrameLayout用于显示日期和时间选择控件
public class DateTimePicker extends FrameLayout {
// 默认控件是否可用
private static final boolean DEFAULT_ENABLE_STATE = true;
// 半天中的小时数、全天中的小时数、一周中的天数等常量
private static final int HOURS_IN_HALF_DAY = 12;
private static final int HOURS_IN_ALL_DAY = 24;
private static final int DAYS_IN_ALL_WEEK = 7;
private static final int DATE_SPINNER_MIN_VAL = 0;
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
// 日期、小时、分钟、AM/PM选择器控件
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
// 当前日期时间
private Calendar mDate;
// 日期显示值数组
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 当前是否为AM
private boolean mIsAm;
// 是否为24小时制视图
private boolean mIs24HourView;
// 控件是否可用
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
// 初始化标志
private boolean mInitialising;
// 日期时间改变监听器
private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 日期选择器值改变监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
}
};
// 小时选择器值改变监听器
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
if (!mIs24HourView) {
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}
} else {
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
}
};
// 分钟选择器值改变监听器
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
}
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
}
};
// AM/PM选择器值改变监听器
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
}
updateAmPmControl();
onDateTimeChanged();
}
};
// 日期时间改变监听器接口
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
// 构造函数,默认使用当前时间
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
// 构造函数,使用指定时间
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
// 构造函数使用指定时间和是否为24小时制
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
mDate = Calendar.getInstance();
mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
inflate(context, R.layout.datetime_picker, this);
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// 更新控件到初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
set24HourView(is24HourView);
// 设置到当前时间
setCurrentDate(date);
setEnabled(isEnabled());
// 设置内容描述
mInitialising = false;
}
// 设置控件是否可用
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
}
super.setEnabled(enabled);
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled;
}
// 获取控件是否可用
@Override
public boolean isEnabled() {
return mIsEnabled;
}
```
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import net.micode.notes.R;
import android.content.Context; import android.content.Context;
import android.text.format.DateFormat; import android.text.format.DateFormat;
@ -28,6 +285,9 @@ import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.NumberPicker; import android.widget.NumberPicker;
/**
* DateTimePicker
*/
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;
@ -158,19 +418,31 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
/**
* OnDateTimeChangedListener
*/
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);
} }
/**
* 使 DateTimePicker
*/
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
/**
* 使 DateTimePicker
*/
public DateTimePicker(Context context, long date) { public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context)); this(context, date, DateFormat.is24HourFormat(context));
} }
/**
* 使24 DateTimePicker
*/
public DateTimePicker(Context context, long date, boolean is24HourView) { public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); super(context);
mDate = Calendar.getInstance(); mDate = Calendar.getInstance();
@ -198,22 +470,25 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setDisplayedValues(stringsForAmPm); mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state // 更新控件到初始状态
updateDateControl(); updateDateControl();
updateHourControl(); updateHourControl();
updateAmPmControl(); updateAmPmControl();
set24HourView(is24HourView); set24HourView(is24HourView);
// set to current time // 设置为当前时间
setCurrentDate(date); setCurrentDate(date);
setEnabled(isEnabled()); setEnabled(isEnabled());
// set the content descriptions // 设置内容描述
mInitialising = false; mInitialising = false;
} }
/**
*
*/
@Override @Override
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) { if (mIsEnabled == enabled) {
@ -227,24 +502,23 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled; mIsEnabled = enabled;
} }
/**
*
*/
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return mIsEnabled; return mIsEnabled;
} }
/** /**
* Get the current date in millis *
*
* @return the current date in millis
*/ */
public long getCurrentDateInTimeMillis() { public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis(); return mDate.getTimeInMillis();
} }
/** /**
* Set the current date *
*
* @param date The current date in millis
*/ */
public void setCurrentDate(long date) { public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
@ -254,13 +528,7 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Set the current date *
*
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*/ */
public void setCurrentDate(int year, int month, public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
@ -272,18 +540,14 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get current year *
*
* @return The current year
*/ */
public int getCurrentYear() { public int getCurrentYear() {
return mDate.get(Calendar.YEAR); return mDate.get(Calendar.YEAR);
} }
/** /**
* Set current year *
*
* @param year The current year
*/ */
public void setCurrentYear(int year) { public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) { if (!mInitialising && year == getCurrentYear()) {
@ -295,18 +559,14 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get 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);
} }
/** /**
* Set current month in the year *
*
* @param month The month in the year
*/ */
public void setCurrentMonth(int month) { public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) { if (!mInitialising && month == getCurrentMonth()) {
@ -318,18 +578,14 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get current day of the month *
*
* @return The day of the month
*/ */
public int getCurrentDay() { public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH); return mDate.get(Calendar.DAY_OF_MONTH);
} }
/** /**
* Set current day of the month *
*
* @param dayOfMonth The day of the month
*/ */
public void setCurrentDay(int dayOfMonth) { public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) { if (!mInitialising && dayOfMonth == getCurrentDay()) {
@ -341,8 +597,7 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get current hour in 24 hour mode, in the range (0~23) * 24
* @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);
@ -362,9 +617,7 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Set current hour in 24 hour mode, in the range (0~23) * 24
*
* @param hourOfDay
*/ */
public void setCurrentHour(int hourOfDay) { public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
@ -390,16 +643,14 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get currentMinute *
*
* @return The Current Minute
*/ */
public int getCurrentMinute() { public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE); return mDate.get(Calendar.MINUTE);
} }
/** /**
* Set current minute *
*/ */
public void setCurrentMinute(int minute) { public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) { if (!mInitialising && minute == getCurrentMinute()) {
@ -411,16 +662,14 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* @return true if this is in 24 hour view else false. * 24
*/ */
public boolean is24HourView () { public boolean is24HourView () {
return mIs24HourView; return mIs24HourView;
} }
/** /**
* Set whether in 24 hour or AM/PM mode. * 24
*
* @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) {
@ -434,6 +683,9 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl(); updateAmPmControl();
} }
/**
*
*/
private void updateDateControl() { private void updateDateControl() {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
@ -448,6 +700,9 @@ public class DateTimePicker extends FrameLayout {
mDateSpinner.invalidate(); mDateSpinner.invalidate();
} }
/**
* AM/PM
*/
private void updateAmPmControl() { private void updateAmPmControl() {
if (mIs24HourView) { if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE); mAmPmSpinner.setVisibility(View.GONE);
@ -458,6 +713,9 @@ public class DateTimePicker extends FrameLayout {
} }
} }
/**
*
*/
private void updateHourControl() { private void updateHourControl() {
if (mIs24HourView) { if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
@ -469,13 +727,15 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Set the callback that indicates the 'Set' button has been pressed. *
* @param callback the callback, if null will do nothing
*/ */
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback; mOnDateTimeChangedListener = callback;
} }
/**
*
*/
private void onDateTimeChanged() { private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) { if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),

@ -29,17 +29,24 @@ 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;
// 自定义的日期时间选择对话框继承自AlertDialog并实现了OnClickListener接口
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 存储当前选择的日期时间
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
// 是否使用24小时制
private boolean mIs24HourView; private boolean mIs24HourView;
// 回调接口,当日期时间设置完成后调用
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);
} }
// 构造函数,初始化对话框并设置初始日期时间
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); super(context);
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
@ -64,14 +71,17 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
// 设置是否使用24小时制显示时间
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
// 设置日期时间选择完成后的回调监听器
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
// 更新对话框的标题以显示当前选择的日期时间
private void updateTitle(long date) { private void updateTitle(long date) {
int flag = int flag =
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR |
@ -81,6 +91,7 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
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());

@ -27,11 +27,13 @@ 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; // 菜单对象
// 构造函数,初始化下拉菜单,设置按钮背景,并将菜单资源加载到弹出菜单中
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);
@ -45,16 +47,19 @@ public class DropdownMenu {
}); });
} }
// 设置下拉菜单项点击监听器
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);
} }

@ -28,26 +28,31 @@ 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;
// 自定义的 CursorAdapter 用于显示文件夹列表
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
// 定义查询文件夹时需要的列
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.SNIPPET 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;
// 构造函数,初始化 FoldersListAdapter
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// TODO Auto-generated constructor stub // 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,21 +62,25 @@ 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;
// 构造函数,初始化 FolderListItem 视图
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);
} }

@ -71,9 +71,10 @@ import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
// 笔记编辑界面的Activity类
public class NoteEditActivity extends Activity implements OnClickListener, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
// 用于存储笔记头部视图的ViewHolder类
private class HeadViewHolder { private class HeadViewHolder {
public TextView tvModified; public TextView tvModified;
@ -84,6 +85,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
public ImageView ibSetBgColor; public ImageView ibSetBgColor;
} }
// 背景色选择按钮和颜色ID的映射
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static { static {
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
@ -93,6 +95,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
} }
// 背景色选择后的显示标记和颜色ID的映射
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
@ -102,6 +105,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
} }
// 字体大小选择按钮和字体大小ID的映射
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static { static {
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
@ -110,6 +114,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);
} }
// 字体大小选择后的显示标记和字体大小ID的映射
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
@ -149,6 +154,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
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);
@ -161,10 +167,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
initResources(); initResources();
} }
/** // 当Activity被系统杀死后恢复其状态
* Current activity may be killed when the memory is low. Once it is killed, for another time
* user load this activity, we should restore the former state
*/
@Override @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState);
@ -179,19 +182,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
// 初始化Activity状态根据Intent决定加载笔记或创建新笔记
private boolean initActivityState(Intent intent) { private boolean initActivityState(Intent intent) {
/**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
* 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 = "";
/**
* Starting from the searched result
*/
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);
@ -215,7 +212,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
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
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);
@ -224,7 +220,6 @@ public class NoteEditActivity extends Activity implements OnClickListener,
int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID,
ResourceParser.getDefaultBgId(this)); ResourceParser.getDefaultBgId(this));
// 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);
if (callDate != 0 && phoneNumber != null) { if (callDate != 0 && phoneNumber != null) {
@ -262,12 +257,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
// Activity恢复时初始化笔记显示
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
initNoteScreen(); initNoteScreen();
} }
// 初始化笔记显示界面,包括背景颜色、字体大小、修改日期等
private void initNoteScreen() { private void initNoteScreen() {
mNoteEditor.setTextAppearance(this, TextAppearanceResources mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId)); .getTexAppearanceResource(mFontSizeId));
@ -288,13 +285,10 @@ public class NoteEditActivity extends Activity implements OnClickListener,
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_YEAR)); | DateUtils.FORMAT_SHOW_YEAR));
/**
* TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker
* is not ready
*/
showAlertHeader(); showAlertHeader();
} }
// 显示或隐藏提醒头部信息
private void showAlertHeader() { private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
@ -312,20 +306,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}; };
} }
// 处理新的Intent可能需要重新加载笔记或创建新笔记
@Override @Override
protected void onNewIntent(Intent intent) { protected void onNewIntent(Intent intent) {
super.onNewIntent(intent); super.onNewIntent(intent);
initActivityState(intent); initActivityState(intent);
} }
// 保存Activity状态在系统需要恢复Activity时使用
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
/**
* For new note without note id, we should firstly save it to
* generate a id. If the editing note is not worth saving, there
* is no id which is equivalent to create new note
*/
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
@ -333,6 +324,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
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
@ -349,6 +341,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return super.dispatchTouchEvent(ev); return super.dispatchTouchEvent(ev);
} }
// 判断触摸事件是否发生在指定视图内
private boolean inRangeOfView(View view, MotionEvent ev) { private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2]; int []location = new int[2];
view.getLocationOnScreen(location); view.getLocationOnScreen(location);
@ -363,6 +356,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
// 初始化视图资源
private void initResources() { private void initResources() {
mHeadViewPanel = findViewById(R.id.note_title); mHeadViewPanel = findViewById(R.id.note_title);
mNoteHeaderHolder = new HeadViewHolder(); mNoteHeaderHolder = new HeadViewHolder();
@ -386,17 +380,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}; };
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.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
} }
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
} }
// 暂停Activity时保存笔记并清理设置状态
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
@ -406,6 +396,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
clearSettingState(); clearSettingState();
} }
// 更新桌面小部件显示
private void updateWidget() { private void updateWidget() {
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) {
@ -425,12 +416,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
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);
} else if (sBgSelectorBtnsMap.containsKey(id)) { } else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE); View.GONE);
@ -452,6 +444,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
// 处理返回键事件,如果设置面板可见则隐藏,否则保存笔记后返回
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if(clearSettingState()) { if(clearSettingState()) {
@ -462,6 +455,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
super.onBackPressed(); super.onBackPressed();
} }
// 清理设置面板状态
private boolean clearSettingState() { private boolean clearSettingState() {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
@ -473,6 +467,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
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);
@ -480,6 +475,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
} }
// 准备选项菜单,根据笔记状态动态更新菜单项
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
if (isFinishing()) { if (isFinishing()) {
@ -505,6 +501,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
// 处理选项菜单项点击事件
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
@ -553,6 +550,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
// 设置提醒时间
private void setReminder() { private void setReminder() {
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
d.setOnDateTimeSetListener(new OnDateTimeSetListener() { d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
@ -563,10 +561,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
d.show(); d.show();
} }
/** // 分享笔记内容到支持ACTION_SEND的其他应用
* Share note to apps that support {@link Intent#ACTION_SEND} action
* 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);
@ -574,11 +569,10 @@ public class NoteEditActivity extends Activity implements OnClickListener,
context.startActivity(intent); context.startActivity(intent);
} }
// 创建新笔记,跳转到新笔记编辑界面
private void createNewNote() { private void createNewNote() {
// Firstly, save current editing notes
saveNote(); saveNote();
// 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);
@ -586,6 +580,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
startActivity(intent); startActivity(intent);
} }
// 删除当前笔记
private void deleteCurrentNote() { private void deleteCurrentNote() {
if (mWorkingNote.existInDatabase()) { if (mWorkingNote.existInDatabase()) {
HashSet<Long> ids = new HashSet<Long>(); HashSet<Long> ids = new HashSet<Long>();
@ -608,15 +603,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote.markDeleted(true); mWorkingNote.markDeleted(true);
} }
// 判断是否处于同步模式
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
// 处理时钟提醒变化事件,设置或取消提醒
public void onClockAlertChanged(long date, boolean set) { public void onClockAlertChanged(long date, boolean set) {
/**
* User could set clock to an unsaved note, so before setting the
* alert clock, we should save the note first
*/
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
@ -632,20 +625,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);
} }
} else { } else {
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
Log.e(TAG, "Clock alert setting error"); Log.e(TAG, "Clock alert setting error");
showToast(R.string.error_note_empty_for_clock); showToast(R.string.error_note_empty_for_clock);
} }
} }
// 处理小部件变化事件,更新小部件显示
public void onWidgetChanged() { public void onWidgetChanged() {
updateWidget(); updateWidget();
} }
// 处理EditText删除事件调整列表项索引
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) {
@ -672,10 +662,8 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.setSelection(length); edit.setSelection(length);
} }
// 处理EditText输入事件添加新列表项
public void onEditTextEnter(int index, String text) { public void onEditTextEnter(int index, String text) {
/**
* Should not happen, check for debug
*/
if(index > mEditTextList.getChildCount()) { if(index > mEditTextList.getChildCount()) {
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");
} }
@ -691,6 +679,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");
@ -708,6 +697,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList.setVisibility(View.VISIBLE); mEditTextList.setVisibility(View.VISIBLE);
} }
// 获取高亮查询结果,用于显示搜索关键词
private Spannable getHighlightQueryResult(String fullText, String userQuery) { private Spannable getHighlightQueryResult(String fullText, String userQuery) {
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
if (!TextUtils.isEmpty(userQuery)) { if (!TextUtils.isEmpty(userQuery)) {
@ -725,6 +715,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return spannable; return spannable;
} }
// 生成一个新的列表项视图
private View getListItem(String item, int index) { private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
@ -756,6 +747,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return view; return view;
} }
// 处理EditText文本变化事件显示或隐藏复选框
public void onTextChange(int index, boolean hasText) { public void onTextChange(int index, boolean hasText) {
if (index >= mEditTextList.getChildCount()) { if (index >= mEditTextList.getChildCount()) {
Log.e(TAG, "Wrong index, should not happen"); Log.e(TAG, "Wrong index, should not happen");
@ -768,6 +760,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
// 处理笔记模式变化事件,从普通模式切换到列表模式或反之
public void onCheckListModeChanged(int oldMode, int newMode) { public void onCheckListModeChanged(int oldMode, int newMode) {
if (newMode == TextNote.MODE_CHECK_LIST) { if (newMode == TextNote.MODE_CHECK_LIST) {
switchToListMode(mNoteEditor.getText().toString()); switchToListMode(mNoteEditor.getText().toString());
@ -782,6 +775,7 @@ 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) {
@ -805,28 +799,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return hasChecked; return hasChecked;
} }
// 保存笔记内容到数据库
private boolean saveNote() { private boolean saveNote() {
getWorkingText(); getWorkingText();
boolean saved = mWorkingNote.saveNote(); boolean saved = mWorkingNote.saveNote();
if (saved) { if (saved) {
/**
* There are two modes from List view to edit view, open one note,
* create/edit a node. Opening node requires to the original
* position in the list when back from edit view, while creating a
* new node requires to the top of the list. This code
* {@link #RESULT_OK} is used to identify the create/edit state
*/
setResult(RESULT_OK); setResult(RESULT_OK);
} }
return saved; return saved;
} }
// 将笔记快捷方式添加到桌面
private void sendToDesktop() { private void sendToDesktop() {
/**
* Before send message to home, we should make sure that current
* editing note is exists in databases. So, for new note, firstly
* save it
*/
if (!mWorkingNote.existInDatabase()) { if (!mWorkingNote.existInDatabase()) {
saveNote(); saveNote();
} }
@ -846,16 +830,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
showToast(R.string.info_note_enter_desktop); showToast(R.string.info_note_enter_desktop);
sendBroadcast(sender); sendBroadcast(sender);
} else { } else {
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
Log.e(TAG, "Send to desktop error"); 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);
} }
} }
// 生成桌面快捷方式的标题,截取笔记内容的一部分作为标题
private String makeShortcutIconTitle(String content) { private String makeShortcutIconTitle(String content) {
content = content.replace(TAG_CHECKED, ""); content = content.replace(TAG_CHECKED, "");
content = content.replace(TAG_UNCHECKED, ""); content = content.replace(TAG_UNCHECKED, "");
@ -863,10 +843,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
SHORTCUT_ICON_TITLE_MAX_LEN) : content; SHORTCUT_ICON_TITLE_MAX_LEN) : content;
} }
// 显示短Toast消息
private void showToast(int resId) { private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT); showToast(resId, Toast.LENGTH_SHORT);
} }
// 显示指定持续时间的Toast消息
private void showToast(int resId, int duration) { private void showToast(int resId, int duration) {
Toast.makeText(this, resId, duration).show(); Toast.makeText(this, resId, duration).show();
} }

@ -37,6 +37,7 @@ import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
// 自定义的EditText用于笔记应用中支持删除、添加文本事件监听
public class NoteEditText extends EditText { public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText";
private int mIndex; private int mIndex;
@ -82,10 +83,12 @@ public class NoteEditText extends EditText {
mIndex = 0; mIndex = 0;
} }
// 设置当前文本框的索引
public void setIndex(int index) { public void setIndex(int index) {
mIndex = index; mIndex = index;
} }
// 设置文本变化监听器
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
@ -99,6 +102,7 @@ public class NoteEditText extends EditText {
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
// 处理触摸事件,更新光标位置
@Override @Override
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) { switch (event.getAction()) {
@ -121,6 +125,7 @@ public class NoteEditText extends EditText {
return super.onTouchEvent(event); return super.onTouchEvent(event);
} }
// 处理按键按下事件,记录删除操作前的光标位置
@Override @Override
public boolean onKeyDown(int keyCode, KeyEvent event) { public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { switch (keyCode) {
@ -138,6 +143,7 @@ public class NoteEditText extends EditText {
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event);
} }
// 处理按键弹起事件,根据按键类型执行相应操作
@Override @Override
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) { switch(keyCode) {
@ -167,6 +173,7 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event); return super.onKeyUp(keyCode, event);
} }
// 当EditText焦点发生变化时调用通知监听器文本是否有内容
@Override @Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
@ -179,6 +186,7 @@ public class NoteEditText extends EditText {
super.onFocusChanged(focused, direction, previouslyFocusedRect); super.onFocusChanged(focused, direction, previouslyFocusedRect);
} }
// 创建上下文菜单处理URL点击事件
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {

@ -25,7 +25,7 @@ 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,
@ -42,6 +42,7 @@ public class NoteItemData {
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
// 定义了游标中各个列的索引位置
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
@ -55,6 +56,7 @@ public class NoteItemData {
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
// 笔记项的各种属性
private long mId; private long mId;
private long mAlertDate; private long mAlertDate;
private int mBgColorId; private int mBgColorId;
@ -70,12 +72,14 @@ public class NoteItemData {
private String mName; private String mName;
private String mPhoneNumber; private String mPhoneNumber;
// 笔记项在列表中的位置信息
private boolean mIsLastItem; private boolean mIsLastItem;
private boolean mIsFirstItem; private boolean mIsFirstItem;
private boolean mIsOnlyOneItem; private boolean mIsOnlyOneItem;
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 +113,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 +139,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);
} }

@ -30,7 +30,7 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
// 自定义的CursorAdapter用于显示笔记列表
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;
@ -38,11 +38,13 @@ public class NotesListAdapter extends CursorAdapter {
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>();
@ -50,11 +52,13 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0; mNotesCount = 0;
} }
// 创建新的视图项
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); return new NotesListItem(context);
} }
// 绑定数据到视图项
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
@ -64,20 +68,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,6 +97,7 @@ 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()) {
@ -105,6 +114,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()) {
@ -128,6 +138,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 +154,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;
@ -155,18 +168,21 @@ public class NotesListAdapter extends CursorAdapter {
return mSelectedIndex.get(position); return mSelectedIndex.get(position);
} }
// 当数据内容发生变化时,更新笔记数量
@Override @Override
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); super.onContentChanged();
calcNotesCount(); calcNotesCount();
} }
// 更改Cursor时更新笔记数量
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);
calcNotesCount(); calcNotesCount();
} }
// 计算笔记数量
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {

@ -29,7 +29,7 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
// NotesListItem 类继承自 LinearLayout用于表示笔记列表中的一个项
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert; private ImageView mAlert;
private TextView mTitle; private TextView mTitle;
@ -38,6 +38,7 @@ public class NotesListItem extends LinearLayout {
private NoteItemData mItemData; private NoteItemData mItemData;
private CheckBox mCheckBox; private CheckBox mCheckBox;
// 构造函数,初始化 NotesListItem 的视图组件
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this);
@ -48,6 +49,7 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
} }
// 绑定数据到 NotesListItem 的视图组件,并设置选择模式和选中状态
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setVisibility(View.VISIBLE);
@ -99,6 +101,7 @@ public class NotesListItem extends LinearLayout {
setBackground(data); setBackground(data);
} }
// 根据数据设置 NotesListItem 的背景资源
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
@ -116,6 +119,7 @@ public class NotesListItem extends LinearLayout {
} }
} }
// 获取绑定到此 NotesListItem 的数据
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }

@ -47,7 +47,7 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
// 设置界面活动类继承自PreferenceActivity
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";
@ -69,11 +69,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
// 创建活动时初始化界面
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ /* 使用应用图标进行导航 */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
@ -88,12 +89,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
} }
// 恢复活动时刷新界面
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new // 如果用户添加了新账户,自动设置同步账户
// account
if (mHasAddedAccount) { if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
@ -116,6 +117,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
refreshUI(); refreshUI();
} }
// 销毁活动时注销广播接收器
@Override @Override
protected void onDestroy() { protected void onDestroy() {
if (mReceiver != null) { if (mReceiver != null) {
@ -124,6 +126,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
super.onDestroy(); super.onDestroy();
} }
// 加载账户偏好设置
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll(); mAccountCategory.removeAll();
@ -135,11 +138,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // 第一次设置账户
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // 如果账户已经设置,提示用户切换账户的风险
// user about the risk
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
} }
} else { } else {
@ -154,11 +156,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
// 加载同步按钮
private void loadSyncButton() { private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state // 设置按钮状态
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
@ -176,7 +179,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time // 设置上次同步时间
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
@ -193,11 +196,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
// 刷新用户界面
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
// 显示选择账户的对话框
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@ -254,6 +259,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
} }
// 显示更改账户确认对话框
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@ -283,11 +289,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.show(); dialogBuilder.show();
} }
// 获取Google账户列表
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
// 设置同步账户
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
@ -299,10 +307,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
editor.commit(); editor.commit();
// clean up last sync time // 清除上次同步时间
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// clean up local gtask related info // 清除本地Gtask相关信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -318,6 +326,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
// 移除同步账户
private void removeSyncAccount() { private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
@ -329,7 +338,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
editor.commit(); editor.commit();
// clean up local gtask related info // 清除本地Gtask相关信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -340,12 +349,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start(); }).start();
} }
// 获取同步账户名称
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
// 设置上次同步时间
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
@ -354,12 +365,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit(); editor.commit();
} }
// 获取上次同步时间
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
// 广播接收器,用于接收同步状态更新
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
@ -374,6 +387,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
// 选项菜单项点击事件处理
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:

@ -32,19 +32,24 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity; import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
// 提供笔记小部件功能的抽象类继承自AppWidgetProvider
public abstract class NoteWidgetProvider extends AppWidgetProvider { public abstract class NoteWidgetProvider extends AppWidgetProvider {
// 查询笔记时使用的投影列
public static final String [] PROJECTION = new String [] { public static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
// 投影列对应的索引
public static final int COLUMN_ID = 0; public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1; public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2; public static final int COLUMN_SNIPPET = 2;
// 日志标签
private static final String TAG = "NoteWidgetProvider"; private static final String TAG = "NoteWidgetProvider";
// 当小部件被删除时调用更新数据库中的小部件ID为无效值
@Override @Override
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -57,6 +62,7 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
} }
} }
// 根据小部件ID获取笔记信息
private Cursor getNoteWidgetInfo(Context context, int widgetId) { private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
@ -65,10 +71,12 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
null); null);
} }
// 更新小部件视图
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false); update(context, appWidgetManager, appWidgetIds, false);
} }
// 更新小部件视图,支持隐私模式
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) { boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
@ -124,9 +132,12 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
} }
} }
// 获取背景资源ID的方法由子类实现
protected abstract int getBgResourceId(int bgId); protected abstract int getBgResourceId(int bgId);
// 获取布局ID的方法由子类实现
protected abstract int getLayoutId(); protected abstract int getLayoutId();
// 获取小部件类型的ID由子类实现
protected abstract int getWidgetType(); protected abstract int getWidgetType();
} }

@ -23,23 +23,27 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
// 2x2 小部件提供者类,继承自 NoteWidgetProvider
public class NoteWidgetProvider_2x extends NoteWidgetProvider { public class NoteWidgetProvider_2x extends NoteWidgetProvider {
// 更新小部件时调用的方法
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
// 返回 2x2 小部件的布局 ID
@Override @Override
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_2x; return R.layout.widget_2x;
} }
// 根据背景 ID 返回对应的 2x2 小部件背景资源 ID
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
} }
// 返回 2x2 小部件的类型 ID
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X; return Notes.TYPE_WIDGET_2X;

@ -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.widget; package net.micode.notes.widget;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -23,22 +7,26 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
// 定义一个4x4小部件的提供者类继承自NoteWidgetProvider
public class NoteWidgetProvider_4x extends NoteWidgetProvider { public class NoteWidgetProvider_4x extends NoteWidgetProvider {
// 覆盖父类的onUpdate方法用于更新小部件的视图
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
// 返回4x4小部件的布局资源ID
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_4x; return R.layout.widget_4x;
} }
// 根据背景ID返回4x4小部件的背景资源ID
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
} }
// 返回小部件的类型这里是4x4类型
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; return Notes.TYPE_WIDGET_4X;

Loading…
Cancel
Save