Compare commits

...

9 Commits

Binary file not shown.

@ -1,17 +1,15 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * (c) 2010-2011, The MiCode (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* 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.data; package net.micode.notes.data;
@ -25,10 +23,21 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
/**
*
*/
public class Contact { public class Contact {
// 静态联系人缓存使用HashMap存储电话号码到联系人姓名的映射
// 键:电话号码(String),值:联系人姓名(String)
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
// 日志标签,用于调试和错误记录
private static final String TAG = "Contact"; private static final String TAG = "Contact";
// 联系人查询的选择条件(WHERE子句)
// 1. 使用PHONE_NUMBERS_EQUAL函数比较电话号码
// 2. 限制MIME类型为电话类型
// 3. 通过phone_lookup表提高查询效率
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,38 +45,65 @@ public class Contact {
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/**
*
*
* @param context Android访ContentResolver
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 初始化缓存(懒加载模式)
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
// 首先检查缓存中是否已有该号码的查询结果
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber); // 命中缓存直接返回
} }
// 准备查询条件:
// 1. 将选择语句中的"+"替换为电话号码的最小匹配长度
// 2. PhoneNumberUtils.toCallerIDMinMatch()方法会根据号码格式返回合适的匹配长度
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 执行内容提供器查询:
// 1. 查询URI: Data.CONTENT_URI (联系人数据)
// 2. 只查询DISPLAY_NAME(显示名称)列
// 3. 使用上面构建的选择条件
// 4. 查询参数为phoneNumber
// 5. 不指定排序方式
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI, // 联系人数据URI
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME }, // 要查询的列
selection, selection, // WHERE条件
new String[] { phoneNumber }, new String[] { phoneNumber }, // WHERE参数
null); null); // 排序方式
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
// 获取第一行第一列的数据(联系人姓名)
String name = cursor.getString(0); String name = cursor.getString(0);
// 将结果存入缓存以备后续使用
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);
return name; return name;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString()); // 处理可能的数组越界异常
Log.e(TAG, "获取Cursor字符串时出错" + e.toString());
return null; return null;
} finally { } finally {
// 确保关闭Cursor释放资源
cursor.close(); cursor.close();
} }
} else { } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); // 没有找到匹配的联系人记录
Log.d(TAG, "没有找到匹配号码的联系人:" + phoneNumber);
return null; return null;
} }
} }
} }

@ -1,279 +1,292 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * (c) 2010-2011, The MiCode (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* 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.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
/**
* 便
* URI
*/
public class Notes { public class Notes {
// 内容提供器的授权标识
public static final String AUTHORITY = "micode_notes"; public static final String AUTHORITY = "micode_notes";
// 日志标签
public static final String TAG = "Notes"; public static final String TAG = "Notes";
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1; // 笔记类型常量
public static final int TYPE_SYSTEM = 2; public static final int TYPE_NOTE = 0; // 普通笔记
public static final int TYPE_FOLDER = 1; // 文件夹
public static final int TYPE_SYSTEM = 2; // 系统文件夹
/** /**
* Following IDs are system folders' identifiers * ID
* {@link Notes#ID_ROOT_FOLDER } is default folder * {@link Notes#ID_ROOT_FOLDER}
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER}
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@link Notes#ID_CALL_RECORD_FOLDER}
*/ */
public static final int ID_ROOT_FOLDER = 0; public static final int ID_ROOT_FOLDER = 0; // 根文件夹ID
public static final int ID_TEMPARAY_FOLDER = -1; public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹ID
public static final int ID_CALL_RECORD_FOLDER = -2; public static final int ID_CALL_RECORD_FOLDER = -2; // 通话记录文件夹ID
public static final int ID_TRASH_FOLER = -3; public static final int ID_TRASH_FOLER = -3; // 回收站文件夹ID
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // Intent附加数据键名常量
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; // 提醒日期
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; // 背景颜色ID
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; // 桌面小部件ID
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; // 小部件类型
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id"; // 文件夹ID
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date"; // 通话日期
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0; // 桌面小部件类型常量
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_INVALIDE = -1; // 无效小部件
public static final int TYPE_WIDGET_2X = 0; // 2x大小小部件
public static final int TYPE_WIDGET_4X = 1; // 4x大小小部件
/**
*
*/
public static class DataConstants { public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; // 普通笔记类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; // 通话笔记类型
} }
/** // 内容URI定义
* Uri to query all notes and folders public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); // 笔记查询URI
*/ public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); // 数据查询URI
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/** /**
* Uri to query data *
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns { public interface NoteColumns {
/** /**
* The unique ID for a row * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
/** /**
* The parent's id for note or folder * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id";
/** /**
* Created data for note or folder *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* Latest modified date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* Alert date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ALERTED_DATE = "alert_date"; public static final String ALERTED_DATE = "alert_date";
/** /**
* Folder's name or text content of note *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String SNIPPET = "snippet"; public static final String SNIPPET = "snippet";
/** /**
* Note's widget id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id";
/** /**
* Note's widget type *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type";
/** /**
* Note's background color's id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String BG_COLOR_ID = "bg_color_id"; public static final String BG_COLOR_ID = "bg_color_id";
/** /**
* For text note, it doesn't has attachment, for multi-media * 0-1-
* note, it has at least one attachment * <P> : INTEGER </P>
* <P> Type: INTEGER </P>
*/ */
public static final String HAS_ATTACHMENT = "has_attachment"; public static final String HAS_ATTACHMENT = "has_attachment";
/** /**
* Folder's count of notes *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String NOTES_COUNT = "notes_count"; public static final String NOTES_COUNT = "notes_count";
/** /**
* The file type: folder or note * //
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String TYPE = "type"; public static final String TYPE = "type";
/** /**
* The last sync id * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id";
/** /**
* Sign to indicate local modified or not * 0-1-
* <P> Type: INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified";
/** /**
* Original parent id before moving into temporary folder * ID
* <P> Type : INTEGER </P> * <P> : INTEGER </P>
*/ */
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/** /**
* The gtask id * GoogleIDGoogle Tasks
* <P> Type : TEXT </P> * <P> : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id";
/** /**
* The version code *
* <P> Type : INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String VERSION = "version"; public static final String VERSION = "version";
} }
/**
*
*/
public interface DataColumns { public interface DataColumns {
/** /**
* The unique ID for a row * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
/** /**
* The MIME type of the item represented by this row. * MIME
* <P> Type: Text </P> * <P> : TEXT </P>
*/ */
public static final String MIME_TYPE = "mime_type"; public static final String MIME_TYPE = "mime_type";
/** /**
* The reference id to note that this data belongs to * ID
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String NOTE_ID = "note_id"; public static final String NOTE_ID = "note_id";
/** /**
* Created data for note or folder *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* Latest modified date *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* Data's content *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String CONTENT = "content"; public static final String CONTENT = "content";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * 1MIME_TYPE
* integer data type * <P> : INTEGER </P>
* <P> Type: INTEGER </P>
*/ */
public static final String DATA1 = "data1"; public static final String DATA1 = "data1";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * 2MIME_TYPE
* integer data type * <P> : INTEGER </P>
* <P> Type: INTEGER </P>
*/ */
public static final String DATA2 = "data2"; public static final String DATA2 = "data2";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * 3MIME_TYPE
* TEXT data type * <P> : TEXT </P>
* <P> Type: TEXT </P>
*/ */
public static final String DATA3 = "data3"; public static final String DATA3 = "data3";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * 4MIME_TYPE
* TEXT data type * <P> : TEXT </P>
* <P> Type: TEXT </P>
*/ */
public static final String DATA4 = "data4"; public static final String DATA4 = "data4";
/** /**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for * 5MIME_TYPE
* TEXT data type * <P> : TEXT </P>
* <P> Type: TEXT </P>
*/ */
public static final String DATA5 = "data5"; public static final String DATA5 = "data5";
} }
/**
*
*/
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not * 0-1-
* <P> Type: Integer 1:check list mode 0: normal mode </P> * <P> : INTEGER </P>
*/ */
public static final String MODE = DATA1; public static final String MODE = DATA1;
public static final int MODE_CHECK_LIST = 1; public static final int MODE_CHECK_LIST = 1; // 清单模式
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // MIME类型定义
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; // 多项目类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; // 单项目类型
// 内容URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
} }
/**
*
*/
public static final class CallNote implements DataColumns { public static final class CallNote implements DataColumns {
/** /**
* Call date for this record *
* <P> Type: INTEGER (long) </P> * <P> : INTEGER (long) </P>
*/ */
public static final String CALL_DATE = DATA1; public static final String CALL_DATE = DATA1;
/** /**
* Phone number for this record *
* <P> Type: TEXT </P> * <P> : TEXT </P>
*/ */
public static final String PHONE_NUMBER = DATA3; public static final String PHONE_NUMBER = DATA3;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; // MIME类型定义
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; // 多项目类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; // 单项目类型
// 内容URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
} }
} }

@ -1,17 +1,15 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * (c) 2010-2011, The MiCode (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* 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.data; package net.micode.notes.data;
@ -26,64 +24,74 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库名称常量
private static final String DB_NAME = "note.db"; private static final String DB_NAME = "note.db";
// 数据库版本号
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;
/**
*
*/
public interface TABLE { public interface TABLE {
public static final String NOTE = "note"; public static final String NOTE = "note"; // 笔记表
public static final String DATA = "data"; // 数据表
public static final String DATA = "data";
} }
// 日志标签
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";
// 单例实例
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
// 创建笔记表的SQL语句
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + NoteColumns.ID + " INTEGER PRIMARY KEY," + // 笔记ID
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父文件夹ID
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + // 提醒日期
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 背景颜色ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + // 是否有附件
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 包含笔记数(文件夹用)
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 内容摘要
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 类型(笔记/文件夹)
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的小部件ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 本地修改标记
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原始父ID
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // Google任务ID
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本号
")"; ")";
// 创建数据表的SQL语句
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," + // 数据ID
DataColumns.MIME_TYPE + " TEXT NOT NULL," + DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME类型
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的笔记ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + // 内容
DataColumns.DATA1 + " INTEGER," + DataColumns.DATA1 + " INTEGER," + // 通用数据列1
DataColumns.DATA2 + " INTEGER," + DataColumns.DATA2 + " INTEGER," + // 通用数据列2
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 通用数据列3
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 通用数据列4
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 通用数据列5
")"; ")";
// 创建数据表note_id索引的SQL语句
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/** /**
* Increase folder's note count when move note to the folder *
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+ "CREATE TRIGGER increase_folder_count_on_update "+
@ -95,7 +103,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Decrease folder's note count when move note from folder *
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " + "CREATE TRIGGER decrease_folder_count_on_update " +
@ -108,7 +116,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Increase folder's note count when insert new note to the folder *
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " + "CREATE TRIGGER increase_folder_count_on_insert " +
@ -120,7 +128,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Decrease folder's note count when delete note from the folder *
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " + "CREATE TRIGGER decrease_folder_count_on_delete " +
@ -133,7 +141,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE} *
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " + "CREATE TRIGGER update_note_content_on_insert " +
@ -146,7 +154,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changed *
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " + "CREATE TRIGGER update_note_content_on_update " +
@ -159,7 +167,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted *
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " + "CREATE TRIGGER update_note_content_on_delete " +
@ -172,7 +180,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Delete datas belong to note which has been deleted *
*/ */
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " + "CREATE TRIGGER delete_data_on_delete " +
@ -183,7 +191,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Delete notes belong to folder which has been deleted *
*/ */
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " + "CREATE TRIGGER folder_delete_notes_on_delete " +
@ -194,7 +202,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Move notes belong to folder which has been moved to trash folder *
*/ */
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " + "CREATE TRIGGER folder_move_notes_on_trash " +
@ -206,18 +214,31 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/**
*
* @param context
*/
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION);
} }
/**
*
* @param db SQLite
*/
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL); // 执行建表SQL
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db); // 重建触发器
createSystemFolder(db); createSystemFolder(db); // 创建系统文件夹
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created");
} }
/**
*
* @param db SQLite
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) { private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除所有现有触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,6 +247,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 重新创建所有触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -235,58 +257,69 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
} }
/**
*
* @param db SQLite
*/
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
/** // 创建通话记录文件夹
* call record foler for call notes
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
/** // 创建根文件夹
* root folder which is default folder
*/
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
/** // 创建临时文件夹
* temporary folder which is used for moving note
*/
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
/** // 创建回收站文件夹
* create trash folder
*/
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/**
*
* @param db SQLite
*/
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL); // 执行建表SQL
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db); // 重建触发器
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); // 创建索引
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created");
} }
/**
*
* @param db SQLite
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) { private void reCreateDataTableTriggers(SQLiteDatabase db) {
// 删除现有触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
// 重新创建触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
} }
/**
*
* @param context
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context);
@ -294,69 +327,100 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance; return mInstance;
} }
/**
*
* @param db SQLite
*/
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db); // 创建笔记表
createDataTable(db); createDataTable(db); // 创建数据表
} }
/**
*
* @param db SQLite
* @param oldVersion
* @param newVersion
*/
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false; boolean reCreateTriggers = false;
boolean skipV2 = false; boolean skipV2 = false;
// 从版本1升级到版本2
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // 这个升级包含从v2到v3的升级
oldVersion++; oldVersion++;
} }
// 从版本2升级到版本3
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true; reCreateTriggers = true;
oldVersion++; oldVersion++;
} }
// 从版本3升级到版本4
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); upgradeToV4(db);
oldVersion++; oldVersion++;
} }
// 如果需要,重新创建触发器
if (reCreateTriggers) { if (reCreateTriggers) {
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
} }
// 检查版本号是否匹配
if (oldVersion != newVersion) { if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion throw new IllegalStateException("升级笔记数据库到版本 " + newVersion + "失败");
+ "fails");
} }
} }
/**
* 2
* @param db SQLite
*/
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
// 删除旧表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
// 重新创建表
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
} }
/**
* 3
* @param db SQLite
*/
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers // 删除不再使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
// 添加Google任务ID列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''"); + " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
// 添加回收站系统文件夹
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/**
* 4
* @param db SQLite
*/
private void upgradeToV4(SQLiteDatabase db) { private void upgradeToV4(SQLiteDatabase db) {
// 添加版本号列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0"); + " INTEGER NOT NULL DEFAULT 0");
} }
} }

@ -1,22 +1,19 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * (c) 2010-2011, The MiCode (www.micode.net)
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Apache 2.0
* 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.data; package net.micode.notes.data;
import android.app.SearchManager; import android.app.SearchManager;
import android.content.ContentProvider; import android.content.ContentProvider;
import android.content.ContentUris; import android.content.ContentUris;
@ -34,36 +31,45 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* 便(ContentProvider)
* 访
*/
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
// URI匹配器用于识别不同类型的URI请求
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
// 数据库帮助类实例
private NotesDatabaseHelper mHelper; private NotesDatabaseHelper mHelper;
// 日志标签
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1; // URI匹配类型常量
private static final int URI_NOTE_ITEM = 2; private static final int URI_NOTE = 1; // 笔记集合
private static final int URI_DATA = 3; private static final int URI_NOTE_ITEM = 2; // 单条笔记
private static final int URI_DATA_ITEM = 4; private static final int URI_DATA = 3; // 数据集合
private static final int URI_DATA_ITEM = 4; // 单条数据
private static final int URI_SEARCH = 5; private static final int URI_SEARCH = 5; // 搜索
private static final int URI_SEARCH_SUGGEST = 6; private static final int URI_SEARCH_SUGGEST = 6; // 搜索建议
// 静态初始化块配置URI匹配器
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 添加URI匹配规则
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); // 匹配笔记集合
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); // 匹配单条笔记
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); // 匹配数据集合
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM); // 匹配单条数据
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH); // 匹配搜索
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST); // 匹配搜索建议
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST); // 带参数的搜索建议
} }
/** /**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * ()
* we will trim '\n' and white space in order to show more information. * x'0A'SQLite'\n'
*
*/ */
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
@ -73,50 +79,68 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 笔记片段搜索查询SQL
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " WHERE " + NoteColumns.SNIPPET + " LIKE ?" // 使用LIKE进行模糊匹配
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER // 排除回收站中的笔记
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; // 只搜索普通笔记(非文件夹)
/**
*
* @return
*/
@Override @Override
public boolean onCreate() { public boolean onCreate() {
// 获取数据库帮助类实例
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
/**
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor
*/
@Override @Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
Cursor c = null; Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
// 根据URI类型执行不同的查询
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE: // 查询笔记集合
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM: // 查询单条笔记
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取笔记ID
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_DATA: case URI_DATA: // 查询数据集合
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM: // 查询单条数据
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1); // 获取数据ID
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_SEARCH: case URI_SEARCH: // 搜索请求
case URI_SEARCH_SUGGEST: case URI_SEARCH_SUGGEST: // 搜索建议请求
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "搜索查询不支持指定sortOrder、selection、selectionArgs或projection参数");
} }
// 获取搜索关键字
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
@ -131,72 +155,92 @@ public class NotesProvider extends ContentProvider {
} }
try { try {
// 格式化搜索字符串(添加通配符)
searchString = String.format("%%%s%%", searchString); searchString = String.format("%%%s%%", searchString);
// 执行原始SQL查询
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); new String[] { searchString });
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString()); Log.e(TAG, "查询异常: " + ex.toString());
} }
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("未知URI: " + uri);
} }
// 设置内容变化通知URI
if (c != null) { if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); c.setNotificationUri(getContext().getContentResolver(), uri);
} }
return c; return c;
} }
/**
*
* @param uri URI
* @param values
* @return URI
*/
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0; long dataId = 0, noteId = 0, insertedId = 0;
// 根据URI类型执行不同的插入操作
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE: // 插入笔记
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break; break;
case URI_DATA: case URI_DATA: // 插入数据
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
} else { } else {
Log.d(TAG, "Wrong data format without note id:" + values.toString()); Log.d(TAG, "数据格式错误,缺少note id:" + values.toString());
} }
insertedId = dataId = db.insert(TABLE.DATA, null, values); insertedId = dataId = db.insert(TABLE.DATA, null, values);
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("未知URI: " + uri);
} }
// Notify the note uri
// 通知相关URI的数据变化
if (noteId > 0) { if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
} }
// Notify the data uri
if (dataId > 0) { if (dataId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
// 返回新插入数据的URI
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId);
} }
/**
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
*/
@Override @Override
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false; boolean deleteData = false;
// 根据URI类型执行不同的删除操作
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE: // 删除笔记集合
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs); count = db.delete(TABLE.NOTE, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM: // 删除单条笔记
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
/** /**
* ID that smaller than 0 is system folder which is not allowed to * ID0
* trash
*/ */
long noteId = Long.valueOf(id); long noteId = Long.valueOf(id);
if (noteId <= 0) { if (noteId <= 0) {
@ -205,19 +249,21 @@ public class NotesProvider extends ContentProvider {
count = db.delete(TABLE.NOTE, count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA: case URI_DATA: // 删除数据集合
count = db.delete(TABLE.DATA, selection, selectionArgs); count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true; deleteData = true;
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM: // 删除单条数据
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA, count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true; deleteData = true;
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("未知URI: " + uri);
} }
// 通知相关URI的数据变化
if (count > 0) { if (count > 0) {
if (deleteData) { if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -227,37 +273,48 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
/**
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
*/
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false; boolean updateData = false;
// 根据URI类型执行不同的更新操作
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE: // 更新笔记集合
increaseNoteVersion(-1, selection, selectionArgs); increaseNoteVersion(-1, selection, selectionArgs); // 增加版本号
count = db.update(TABLE.NOTE, values, selection, selectionArgs); count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM: // 更新单条笔记
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 增加版本号
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA: case URI_DATA: // 更新数据集合
count = db.update(TABLE.DATA, values, selection, selectionArgs); count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true; updateData = true;
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM: // 更新单条数据
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
updateData = true; updateData = true;
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("未知URI: " + uri);
} }
// 通知相关URI的数据变化
if (count > 0) { if (count > 0) {
if (updateData) { if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -267,17 +324,28 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
/**
* AND
* @param selection
* @return
*/
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
} }
/**
*
* @param id ID
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
sql.append(TABLE.NOTE); sql.append(TABLE.NOTE);
sql.append(" SET "); sql.append(" SET ");
sql.append(NoteColumns.VERSION); sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append("=" + NoteColumns.VERSION + "+1 "); // 版本号+1
if (id > 0 || !TextUtils.isEmpty(selection)) { if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE "); sql.append(" WHERE ");
@ -293,13 +361,18 @@ public class NotesProvider extends ContentProvider {
sql.append(selectString); sql.append(selectString);
} }
// 执行SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString());
} }
/**
* URIMIME
* @param uri URI
* @return MIME
*/
@Override @Override
public String getType(Uri uri) { public String getType(Uri uri) {
// TODO Auto-generated method stub // TODO 待实现
return null; return null;
} }
}
}

@ -0,0 +1,427 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.tool;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/**
*
* SD
*/
public class BackupUtils {
private static final String TAG = "BackupUtils";
// 单例实例
private static BackupUtils sInstance;
/**
*
* @param context
* @return BackupUtils
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
}
return sInstance;
}
/**
* /
* STATE_SD_CARD_UNMOUONTED: SD
* STATE_BACKUP_FILE_NOT_EXIST:
* STATE_DATA_DESTROIED:
* STATE_SYSTEM_ERROR:
* STATE_SUCCESS:
*/
public static final int STATE_SD_CARD_UNMOUONTED = 0;
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
public static final int STATE_DATA_DESTROIED = 2;
public static final int STATE_SYSTEM_ERROR = 3;
public static final int STATE_SUCCESS = 4;
private final TextExport mTextExport; // 文本导出模块
/**
*
* @param context
*/
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
/**
*
* @return true if SD
*/
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
*
* @return STATE_*
*/
public int exportToText() {
return mTextExport.exportToText();
}
/**
*
* @return "notes_20231001.txt"
*/
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
/**
*
* @return "/sdcard/notes_backup/"
*/
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
/**
*
*/
private static class TextExport {
// 笔记查询投影(仅获取必要字段)
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID, // 笔记ID
NoteColumns.MODIFIED_DATE, // 最后修改时间
NoteColumns.SNIPPET, // 摘要(文件夹名称/笔记标题)
NoteColumns.TYPE // 类型(文件夹/笔记)
};
// 投影字段索引
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
// 笔记内容数据查询投影
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT, // 内容(文本/位置信息)
DataColumns.MIME_TYPE, // MIME类型区分普通笔记/通话记录)
DataColumns.DATA1, // 预留字段1通话记录中为日期
DataColumns.DATA2, // 预留字段2
DataColumns.DATA3, // 预留字段3
DataColumns.DATA4, // 电话号码(通话记录专用)
};
// 数据投影字段索引
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2; // DATA1的别名通话时间
private static final int DATA_COLUMN_PHONE_NUMBER = 4; // DATA4的别名电话号码
// 导出格式模板对应res/array/format_for_exported_note.xml
private final String[] TEXT_FORMAT;
// 格式模板索引
private static final int FORMAT_FOLDER_NAME = 0; // 文件夹名称格式
private static final int FORMAT_NOTE_DATE = 1; // 笔记日期格式
private static final int FORMAT_NOTE_CONTENT = 2; // 笔记内容格式
private final Context mContext;
private String mFileName; // 导出文件名
private String mFileDirectory; // 导出文件目录
/**
*
* @param context
*/
public TextExport(Context context) {
// 从资源文件获取导出格式模板
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
}
/**
*
* @param id FORMAT_*
* @return
*/
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
/**
*
* @param folderId ID
* @param ps
*/
private void exportFolderToText(String folderId, PrintStream ps) {
// 查询该文件夹下的所有笔记
Cursor notesCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.PARENT_ID + "=?", // 条件父级ID为当前文件夹ID
new String[]{folderId},
null
);
if (notesCursor != null) {
try {
if (notesCursor.moveToFirst()) {
do {
// 打印笔记最后修改时间
String dateStr = DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), // 格式MM月dd日 HH:mm
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)
).toString();
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), dateStr));
// 导出笔记内容
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
}
} finally {
notesCursor.close(); // 释放游标资源
}
}
}
/**
*
* @param noteId ID
* @param ps
*/
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询笔记对应的内容数据(如文本内容、通话记录)
Cursor dataCursor = mContext.getContentResolver().query(
Notes.CONTENT_DATA_URI,
DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", // 条件属于该笔记ID
new String[]{noteId},
null
);
if (dataCursor != null) {
try {
if (dataCursor.moveToFirst()) {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// 处理通话记录笔记
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); // 通话位置或备注
// 打印电话号码
if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber));
}
// 打印通话时间
String callDateStr = DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
callDate
).toString();
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), callDateStr));
// 打印位置信息
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 处理普通文本笔记
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
}
}
} while (dataCursor.moveToNext());
}
} finally {
dataCursor.close(); // 释放游标资源
}
}
// 打印分隔符(换行符+特殊字符,可能用于区分笔记)
try {
ps.write(new byte[]{Character.LINE_SEPARATOR, Character.LETTER_NUMBER});
} catch (IOException e) {
Log.e(TAG, "写入分隔符失败:" + e.getMessage());
}
}
/**
*
* @return
*/
public int exportToText() {
// 检查SD卡是否可用
if (!externalStorageAvailable()) {
Log.d(TAG, "SD卡未挂载无法导出");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取输出流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "创建输出流失败");
return STATE_SYSTEM_ERROR;
}
// 导出文件夹及其笔记
String whereClause = "(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND " +
NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR " +
NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER; // 排除回收站,包含通话记录文件夹
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
whereClause,
null,
null
);
if (folderCursor != null) {
try {
if (folderCursor.moveToFirst()) {
do {
String folderName;
// 处理特殊文件夹:通话记录文件夹使用固定名称
if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET); // 使用文件夹摘要作为名称
}
// 打印文件夹名称
if (!TextUtils.isEmpty(folderName)) {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
exportFolderToText(folderId, ps); // 导出文件夹下的笔记
} while (folderCursor.moveToNext());
}
} finally {
folderCursor.close();
}
}
// 导出根目录下的普通笔记父级ID=0
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0",
null,
null
);
if (noteCursor != null) {
try {
if (noteCursor.moveToFirst()) {
do {
String dateStr = DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)
).toString();
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), dateStr));
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); // 导出笔记内容
} while (noteCursor.moveToNext());
}
} finally {
noteCursor.close();
}
}
ps.close(); // 关闭输出流
return STATE_SUCCESS;
}
/**
*
* @return PrintStreamnull
*/
private PrintStream getExportToTextPrintStream() {
// 生成文件路径(如/sdcard/notes_backup/notes_20231001.txt
File file = generateFileMountedOnSDcard(
mContext,
R.string.file_path, // 目录路径(如"/notes_backup/"
R.string.file_name_txt_format // 文件名格式(如"notes_%s.txt"
);
if (file == null) {
return null;
}
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path); // 存储目录路径
// 创建文件输出流
try {
FileOutputStream fos = new FileOutputStream(file);
return new PrintStream(fos);
} catch (FileNotFoundException e) {
Log.e(TAG, "文件未找到:" + e.getMessage());
} catch (NullPointerException e) {
Log.e(TAG, "空指针异常:" + e.getMessage());
}
return null;
}
}
/**
* SD
* @param context
* @param filePathResId IDR.string.file_path
* @param fileNameFormatResId IDR.string.file_name_txt_format
* @return null
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 构建文件路径SD卡根目录 + 自定义目录 + 文件名
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory()); // SD卡根目录
sb.append(context.getString(filePathResId)); // 自定义目录(如"/notes_backup/"
File filedir = new File(sb.toString()); // 目录对象
// 构建文件名:格式字符串 + 当前日期(如"notes_20231001.txt"
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd), System.currentTimeMillis()) // 日期格式yyyyMMdd
));
File file = new File(sb.toString()); // 文件对象
// 创建目录和文件(若不存在)
try {
if (!filedir.exists() && !filedir.mkdirs()) {
Log.e(TAG, "创建目录失败:" + filedir.getPath());
return null;
}
if (!file.exists() && !file.createNewFile()) {
Log.e(TAG, "创建文件失败:" + file.getPath());
return null;
}
return file;
} catch (SecurityException | IOException e) {
Log.e(TAG, "文件操作失败:" + e.getMessage());
return null;
}
}
}

@ -0,0 +1,392 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.tool;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;
import java.util.HashSet;
/**
*
* ContentProvider
*/
public class DataUtils {
public static final String TAG = "DataUtils";
/**
*
* @param resolver
* @param ids ID
* @return
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
Log.d(TAG, "待删除的ID集合为空");
return true;
}
if (ids.size() == 0) {
Log.d(TAG, "ID集合中无有效数据");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<>();
for (long id : ids) {
// 跳过系统根文件夹(禁止删除)
if (id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "尝试删除系统根文件夹,已忽略");
continue;
}
// 创建删除操作根据ID构建删除URI
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build());
}
try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "删除失败ID集合" + ids.toString());
return false;
}
return true;
} catch (RemoteException | OperationApplicationException e) {
Log.e(TAG, "批量删除异常:" + e.getMessage());
e.printStackTrace();
}
return false;
}
/**
*
* @param resolver
* @param id ID
* @param srcFolderId ID
* @param desFolderId ID
*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues();
// 更新父级ID为目标文件夹ID
values.put(NoteColumns.PARENT_ID, desFolderId);
// 记录原始父级ID用于同步或回滚
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
// 标记本地修改(可能用于同步逻辑)
values.put(NoteColumns.LOCAL_MODIFIED, 1);
// 执行更新操作
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
/**
*
* @param resolver
* @param ids ID
* @param folderId ID
* @return
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, long folderId) {
if (ids == null) {
Log.d(TAG, "待移动的ID集合为空");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<>();
for (long id : ids) {
// 创建更新操作设置父级ID并标记本地修改
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());
}
try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "移动失败ID集合" + ids.toString());
return false;
}
return true;
} catch (RemoteException | OperationApplicationException e) {
Log.e(TAG, "批量移动异常:" + e.getMessage());
e.printStackTrace();
}
return false;
}
/**
*
* @param resolver
* @return
*/
public static int getUserFolderCount(ContentResolver resolver) {
// 查询条件类型为文件夹且父级ID不是回收站ID
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String[]{"COUNT(*)"},
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[]{String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
int count = 0;
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
count = cursor.getInt(0); // 获取计数结果
}
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "查询文件夹数量失败:" + e.getMessage());
} finally {
cursor.close(); // 关闭游标释放资源
}
}
return count;
}
/**
*
* @param resolver
* @param noteId ID
* @param type Notes.TYPE_NOTENotes.TYPE_FOLDER
* @return
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 查询条件类型匹配且父级ID不是回收站ID
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String[]{String.valueOf(type)},
null);
boolean exist = false;
if (cursor != null) {
exist = cursor.getCount() > 0; // 存在有效记录则可见
cursor.close();
}
return exist;
}
/**
*
* @param resolver
* @param noteId ID
* @return
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 直接查询笔记ID是否存在
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
exist = cursor.getCount() > 0;
cursor.close();
}
return exist;
}
/**
*
* @param resolver
* @param dataId ID
* @return
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 查询数据项URI对应的记录
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
exist = cursor.getCount() > 0;
cursor.close();
}
return exist;
}
/**
*
* @param resolver
* @param name
* @return
*/
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询条件:类型为文件夹,不在回收站,且名称匹配
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[]{name}, null);
boolean exist = false;
if (cursor != null) {
exist = cursor.getCount() > 0;
cursor.close();
}
return exist;
}
/**
*
* @param resolver
* @param folderId ID
* @return AppWidgetAttribute
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询该文件夹下所有笔记的小部件ID和类型
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[]{NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE},
NoteColumns.PARENT_ID + "=?",
new String[]{String.valueOf(folderId)},
null);
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
set = new HashSet<>();
try {
if (c.moveToFirst()) {
do {
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0); // 小部件ID
widget.widgetType = c.getInt(1); // 小部件类型
set.add(widget);
} while (c.moveToNext());
}
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "解析小部件数据失败:" + e.getMessage());
} finally {
c.close();
}
}
return set;
}
/**
* ID
* @param resolver
* @param noteId ID
* @return
*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 查询通话笔记对应的电话号码通过MIME类型过滤
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String[]{CallNote.PHONE_NUMBER},
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String[]{String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE},
null);
if (cursor != null && cursor.moveToFirst()) {
try {
return cursor.getString(0); // 获取电话号码
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取电话号码失败:" + e.getMessage());
} finally {
cursor.close();
}
}
return "";
}
/**
* ID
* @param resolver
* @param phoneNumber
* @param callDate
* @return ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 使用PHONE_NUMBERS_EQUAL函数进行模糊匹配处理格式差异
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String[]{CallNote.NOTE_ID},
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
new String[]{String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber},
null);
long noteId = 0;
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
noteId = cursor.getLong(0); // 获取笔记ID
}
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "获取通话笔记ID失败" + e.getMessage());
} finally {
cursor.close();
}
}
return noteId;
}
/**
* ID
* @param resolver
* @param noteId ID
* @return
*/
public static String getSnippetById(ContentResolver resolver, long noteId) {
// 查询笔记的摘要字段
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String[]{NoteColumns.SNIPPET},
NoteColumns.ID + "=?",
new String[]{String.valueOf(noteId)},
null);
if (cursor != null) {
String snippet = "";
try {
if (cursor.moveToFirst()) {
snippet = cursor.getString(0); // 获取摘要
}
} finally {
cursor.close();
}
return snippet;
}
throw new IllegalArgumentException("未找到ID为 " + noteId + " 的笔记");
}
/**
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
snippet = snippet.trim(); // 去除首尾空格
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index); // 截断到第一个换行符
}
}
return snippet;
}
}

@ -0,0 +1,87 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.tool;
/**
* Google Tasks
* Google Tasks API使JSON
*/
public class GTaskStringUtils {
// --------------- JSON请求/响应字段名常量 ---------------
// 操作相关字段
public final static String GTASK_JSON_ACTION_ID = "action_id"; // 操作ID
public final static String GTASK_JSON_ACTION_LIST = "action_list"; // 操作列表
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; // 操作类型
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; // 创建操作
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; // 获取所有操作
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; // 移动操作
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; // 更新操作
// 实体相关字段
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; // 创建者ID
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; // 子实体
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; // 实体变更
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; // 实体类型
// 任务/列表属性字段
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";// 客户端版本
public final static String GTASK_JSON_COMPLETED = "completed"; // 完成状态
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";// 当前列表ID
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";// 默认列表ID
public final static String GTASK_JSON_DELETED = "deleted"; // 删除状态
public final static String GTASK_JSON_DEST_LIST = "dest_list"; // 目标列表
public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; // 目标父级
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";// 目标父级类型
public final static String GTASK_JSON_ID = "id"; // ID
public final static String GTASK_JSON_INDEX = "index"; // 索引位置
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 最后修改时间
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";// 最新同步点
public final static String GTASK_JSON_LIST_ID = "list_id"; // 列表ID
public final static String GTASK_JSON_LISTS = "lists"; // 列表集合
public final static String GTASK_JSON_NAME = "name"; // 名称
public final static String GTASK_JSON_NEW_ID = "new_id"; // 新ID
public final static String GTASK_JSON_NOTES = "notes"; // 备注
public final static String GTASK_JSON_PARENT_ID = "parent_id"; // 父级ID
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";// 前一个兄弟节点ID
public final static String GTASK_JSON_RESULTS = "results"; // 结果集
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; // 源列表
public final static String GTASK_JSON_TASKS = "tasks"; // 任务集合
public final static String GTASK_JSON_TYPE = "type"; // 类型
public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; // 组类型
public final static String GTASK_JSON_TYPE_TASK = "TASK"; // 任务类型
public final static String GTASK_JSON_USER = "user"; // 用户
// --------------- 特殊文件夹和元数据相关常量 ---------------
// MIUI笔记文件夹前缀用于标识由MIUI笔记创建的Google Tasks文件夹
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 默认文件夹名称
public final static String FOLDER_DEFAULT = "Default"; // 默认任务列表
public final static String FOLDER_CALL_NOTE = "Call_Note"; // 通话记录笔记
public final static String FOLDER_META = "METADATA"; // 元数据文件夹
// 元数据头部标识
public final static String META_HEAD_GTASK_ID = "meta_gid"; // Google Tasks ID元数据
public final static String META_HEAD_NOTE = "meta_note"; // 笔记元数据
public final static String META_HEAD_DATA = "meta_data"; // 数据元数据
// 元数据笔记名称,提示用户不要更新或删除
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}

@ -0,0 +1,273 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.tool;
import android.content.Context;
import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
*
*
*/
public class ResourceParser {
// 笔记背景颜色常量定义
public static final int YELLOW = 0; // 黄色背景
public static final int BLUE = 1; // 蓝色背景
public static final int WHITE = 2; // 白色背景
public static final int GREEN = 3; // 绿色背景
public static final int RED = 4; // 红色背景
public static final int BG_DEFAULT_COLOR = YELLOW; // 默认背景颜色为黄色
// 字体大小常量定义
public static final int TEXT_SMALL = 0; // 小号字体
public static final int TEXT_MEDIUM = 1; // 中号字体(默认)
public static final int TEXT_LARGE = 2; // 大号字体
public static final int TEXT_SUPER = 3; // 超大号字体
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; // 默认字体大小为中号
/**
*
*
*/
public static class NoteBgResources {
// 笔记编辑界面背景资源数组,按颜色索引
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow, // 黄色背景
R.drawable.edit_blue, // 蓝色背景
R.drawable.edit_white, // 白色背景
R.drawable.edit_green, // 绿色背景
R.drawable.edit_red // 红色背景
};
// 笔记编辑界面标题栏背景资源数组,按颜色索引
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow, // 黄色标题栏
R.drawable.edit_title_blue, // 蓝色标题栏
R.drawable.edit_title_white, // 白色标题栏
R.drawable.edit_title_green, // 绿色标题栏
R.drawable.edit_title_red // 红色标题栏
};
/**
* ID
* @param id ID (0-4)
* @return ID
*/
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
/**
* ID
* @param id ID (0-4)
* @return ID
*/
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
/**
* ID
*
* @param context
* @return ID
*/
public static int getDefaultBgId(Context context) {
// 检查用户是否开启了"随机背景色"设置
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 随机生成一个颜色ID
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 返回默认颜色ID
return BG_DEFAULT_COLOR;
}
}
/**
*
* ()
*/
public static class NoteItemBgResources {
// 列表首项背景资源数组,按颜色索引
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up, // 黄色首项背景
R.drawable.list_blue_up, // 蓝色首项背景
R.drawable.list_white_up, // 白色首项背景
R.drawable.list_green_up, // 绿色首项背景
R.drawable.list_red_up // 红色首项背景
};
// 列表中间项背景资源数组,按颜色索引
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle, // 黄色中间项背景
R.drawable.list_blue_middle, // 蓝色中间项背景
R.drawable.list_white_middle, // 白色中间项背景
R.drawable.list_green_middle, // 绿色中间项背景
R.drawable.list_red_middle // 红色中间项背景
};
// 列表末项背景资源数组,按颜色索引
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down, // 黄色末项背景
R.drawable.list_blue_down, // 蓝色末项背景
R.drawable.list_white_down, // 白色末项背景
R.drawable.list_green_down, // 绿色末项背景
R.drawable.list_red_down, // 红色末项背景
};
// 列表单项(只有一项)背景资源数组,按颜色索引
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single, // 黄色单项背景
R.drawable.list_blue_single, // 蓝色单项背景
R.drawable.list_white_single, // 白色单项背景
R.drawable.list_green_single, // 绿色单项背景
R.drawable.list_red_single // 红色单项背景
};
/**
* ID
* @param id ID (0-4)
* @return ID
*/
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
/**
* ID
* @param id ID (0-4)
* @return ID
*/
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
/**
* ID
* @param id ID (0-4)
* @return ID
*/
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
/**
* ID
* @param id ID (0-4)
* @return ID
*/
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
/**
*
* @return ID
*/
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
/**
*
* (2x4x)
*/
public static class WidgetBgResources {
// 2x尺寸小部件背景资源数组按颜色索引
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow, // 黄色2x小部件背景
R.drawable.widget_2x_blue, // 蓝色2x小部件背景
R.drawable.widget_2x_white, // 白色2x小部件背景
R.drawable.widget_2x_green, // 绿色2x小部件背景
R.drawable.widget_2x_red, // 红色2x小部件背景
};
/**
* ID2x
* @param id ID (0-4)
* @return 2xID
*/
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 4x尺寸小部件背景资源数组按颜色索引
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow, // 黄色4x小部件背景
R.drawable.widget_4x_blue, // 蓝色4x小部件背景
R.drawable.widget_4x_white, // 白色4x小部件背景
R.drawable.widget_4x_green, // 绿色4x小部件背景
R.drawable.widget_4x_red // 红色4x小部件背景
};
/**
* ID4x
* @param id ID (0-4)
* @return 4xID
*/
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
/**
*
*
*/
public static class TextAppearanceResources {
// 文本样式资源数组,按字体大小索引
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal, // 小号字体样式
R.style.TextAppearanceMedium, // 中号字体样式
R.style.TextAppearanceLarge, // 大号字体样式
R.style.TextAppearanceSuper // 超大号字体样式
};
/**
* ID
* @param id ID (0-3)
* @return ID
*/
public static int getTexAppearanceResource(int id) {
/**
* HACKME: ID
* IDID
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
}
/**
*
* @return
*/
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}
Loading…
Cancel
Save