wyxfzgg 3 weeks ago
commit 7968a3e325

Binary file not shown.

@ -25,10 +25,46 @@ import android.util.Log;
import java.util.HashMap;
/**
* <p></p>
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li>使AndroidAPI</li>
* </ul>
* <p></p>
* <ul>
* <li>便</li>
* <li></li>
* <li>便</li>
* </ul>
* <p></p>
* <ul>
* <li>使{@link Context}访Content Provider</li>
* <li>使{@link HashMap}</li>
* <li>便使</li>
* </ul>
*/
public class Contact {
/**
* <p></p>
* <p></p>
* <p>使HashMap</p>
*/
private static HashMap<String, String> sContactCache;
/**
* <p></p>
* <p>Contact</p>
*/
private static final String TAG = "Contact";
/**
* <p></p>
* <p>SQL使PHONE_NUMBERS_EQUAL</p>
* <p>'+'</p>
*/
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,6 +72,32 @@ public class Contact {
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
* <p></p>
* <p></p>
*
* @param context 访ContentResolver
* @param phoneNumber
*
* @return null
*
* <p></p>
* <ol>
* <li></li>
* <li></li>
* <li></li>
* <li>ContentResolverContent Provider</li>
* <li></li>
* <li>Cursor</li>
* <li></li>
* </ol>
*
* <p></p>
* <ul>
* <li>IndexOutOfBoundsExceptionnull</li>
* <li>null</li>
* </ul>
*/
public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();

@ -17,263 +17,562 @@
package net.micode.notes.data;
import android.net.Uri;
/**
* 便URI
* <p>
*
* <ul>
* <li>便</li>
* <li>ID</li>
* <li>Intent</li>
* <li>Widget</li>
* <li>Content ProviderURI</li>
* <li></li>
* </ul>
* <p>
*
* <ul>
* <li></li>
* <li>Content Provider</li>
* <li></li>
* <li>便便便</li>
* <li>便</li>
* <li>Widget</li>
* </ul>
* <p>
*
* <ul>
* <li>{@link NotesProvider}使Content Provider</li>
* <li>{@link NotesDatabaseHelper}使</li>
* <li>UI使Intent</li>
* <li>Widget使Widget</li>
* </ul>
*
*/
public class Notes {
/**
* Content ProviderAuthority便Content Provider
*/
public static final String AUTHORITY = "micode_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;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
* ID便
*/
public static final int ID_ROOT_FOLDER = 0;
/**
* ID便
*/
public static final int ID_TEMPARAY_FOLDER = -1;
/**
* ID便
*/
public static final int ID_CALL_RECORD_FOLDER = -2;
/**
* ID便
*/
public static final int ID_TRASH_FOLER = -3;
/**
* Intent便
*/
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
/**
* IntentID便
*/
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
/**
* IntentWidget IDWidget
*/
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
/**
* IntentWidgetWidget2x4x
*/
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
/**
* IntentID便ID
*/
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
/**
* Intent
*/
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
/**
* WidgetWidget
*/
public static final int TYPE_WIDGET_INVALIDE = -1;
/**
* Widget2xWidget2x2
*/
public static final int TYPE_WIDGET_2X = 0;
/**
* Widget4xWidget4x4
*/
public static final int TYPE_WIDGET_4X = 1;
/**
* 便MIME
* <p>
*
* <ul>
* <li>访</li>
* <li>便MIME</li>
* </ul>
*/
public static class DataConstants {
/**
* 便MIME
*/
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
/**
* 便MIME
*/
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri to query all notes and folders
* Content Provider URI便
* <p>
* URIContent Providernote便
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri to query data
* Content Provider URI便
* <p>
* URIContent Providerdata便
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
* 便
* <p>
*
* <ul>
* <li>便</li>
* <li>Content Provider</li>
* <li>便</li>
* </ul>
* <p>
*
* <ul>
* <li>使便</li>
* <li>便</li>
* <li>ID</li>
* <li>便</li>
* <li>便Widget</li>
* <li>便</li>
* <li>便</li>
* </ul>
* <p>
*
* <ul>
* <li>{@link NotesProvider}使</li>
* <li>{@link NotesDatabaseHelper}使</li>
* <li>UI使</li>
* </ul>
*/
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*
* <p>: INTEGER (long)</p>
* <p>: </p>
*/
public static final String ID = "_id";
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
* 便ID
* <p>: INTEGER (long)</p>
* <p>: ID</p>
* <p>: 便</p>
*/
public static final String PARENT_ID = "parent_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
* 便
* <p>: INTEGER (long)</p>
* <p>: Unix</p>
* <p>: </p>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <p>: INTEGER (long)</p>
* <p>: Unix</p>
* <p>: </p>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*
* <p>: INTEGER (long)</p>
* <p>: Unix0</p>
* <p>: 便</p>
*/
public static final String ALERTED_DATE = "alert_date";
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
* 便
* <p>: TEXT</p>
* <p>: </p>
* <p>: 便</p>
*/
public static final String SNIPPET = "snippet";
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
* 便Widget ID
* <p>: INTEGER (long)</p>
* <p>: -1Widget</p>
* <p>: 便Widget</p>
*/
public static final String WIDGET_ID = "widget_id";
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
* 便Widget
* <p>: INTEGER (long)</p>
* <p>: {@link Notes#TYPE_WIDGET_INVALIDE}{@link Notes#TYPE_WIDGET_2X}{@link Notes#TYPE_WIDGET_4X}</p>
* <p>: Widget</p>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
* 便ID
* <p>: INTEGER (long)</p>
* <p>: ID</p>
* <p>: 便</p>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*
* <p>: INTEGER</p>
* <p>: 01</p>
* <p>: 便</p>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
* 便
* <p>: INTEGER (long)</p>
* <p>: </p>
* <p>: 便</p>
*/
public static final String NOTES_COUNT = "notes_count";
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
* 便
* <p>: INTEGER</p>
* <p>: {@link Notes#TYPE_NOTE}{@link Notes#TYPE_FOLDER}{@link Notes#TYPE_SYSTEM}</p>
* <p>: 便</p>
*/
public static final String TYPE = "type";
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
* ID
* <p>: INTEGER (long)</p>
* <p>: </p>
* <p>: 便</p>
*/
public static final String SYNC_ID = "sync_id";
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*
* <p>: INTEGER</p>
* <p>: 01</p>
* <p>: </p>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
* ID
* <p>: INTEGER</p>
* <p>: ID</p>
* <p>: 便便</p>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
* Google Task ID
* <p>: TEXT</p>
* <p>: Google Task使</p>
* <p>: 便Google Task</p>
*/
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*
* <p>: INTEGER (long)</p>
* <p>: </p>
* <p>: </p>
*/
public static final String VERSION = "version";
}
/**
* 便
* <p>
*
* <ul>
* <li>便</li>
* <li>便</li>
* <li>便</li>
* </ul>
* <p>
*
* <ul>
* <li>使便</li>
* <li>便便便</li>
* <li>便便</li>
* <li>ID</li>
* <li>便</li>
* </ul>
* <p>
*
* <ul>
* <li>{@link NotesProvider}使</li>
* <li>{@link NotesDatabaseHelper}使</li>
* <li>{@link TextNote}{@link CallNote}便</li>
* </ul>
*/
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*
* <p>: INTEGER (long)</p>
* <p>: </p>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
* MIME
* <p>: TEXT</p>
* <p>: "text_note""call_note"</p>
* <p>: 便</p>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
* 便ID
* <p>: INTEGER (long)</p>
* <p>: noteID</p>
* <p>: 便</p>
*/
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*
* <p>: INTEGER (long)</p>
* <p>: Unix</p>
* <p>: </p>
*/
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*
* <p>: INTEGER (long)</p>
* <p>: Unix</p>
* <p>: </p>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*
* <p>: TEXT</p>
* <p>: 便</p>
* <p>: 便</p>
*/
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* 1{@link #MIME_TYPE}
* <p>: INTEGER</p>
* <p>: MIME</p>
* <p>: 便</p>
* <p>: 便/ checklist</p>
*/
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
* 2{@link #MIME_TYPE}
* <p>: INTEGER</p>
* <p>: MIME</p>
* <p>: 便</p>
*/
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* 3{@link #MIME_TYPE}
* <p>: TEXT</p>
* <p>: MIME</p>
* <p>: 便</p>
* <p>: 便</p>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* 4{@link #MIME_TYPE}
* <p>: TEXT</p>
* <p>: MIME</p>
* <p>: 便</p>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
* 5{@link #MIME_TYPE}
* <p>: TEXT</p>
* <p>: MIME</p>
* <p>: 便</p>
*/
public static final String DATA5 = "data5";
}
/**
* 便{@link DataColumns}
* <p>
*
* <ul>
* <li>便</li>
* <li>便MIME</li>
* <li>便Content Provider URI</li>
* <li>Checklist</li>
* </ul>
* <p>
*
* <ul>
* <li>{@link DataColumns}便</li>
* <li>使DATA1便/Checklist</li>
* <li>Content Provider便访</li>
* <li>便</li>
* </ul>
* <p>
*
* <ul>
* <li>{@link DataColumns}</li>
* <li>{@link NotesProvider}使便</li>
* <li>UI使便</li>
* </ul>
*/
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
* 便DATA1
* <p>: INTEGER</p>
* <p>: 01Checklist</p>
* <p>: 便</p>
*/
public static final String MODE = DATA1;
/**
* Checklist便Checklist
*/
public static final int MODE_CHECK_LIST = 1;
/**
* 便MIMEContent Provider便使
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
/**
* 便MIMEContent Provider便使
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
/**
* 便Content Provider URI便
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
/**
* 便{@link DataColumns}
* <p>
*
* <ul>
* <li>便</li>
* <li>便MIME</li>
* <li>便Content Provider URI</li>
* <li></li>
* </ul>
* <p>
*
* <ul>
* <li>{@link DataColumns}便</li>
* <li>使DATA1</li>
* <li>使DATA3</li>
* <li>Content Provider便访</li>
* <li></li>
* </ul>
* <p>
*
* <ul>
* <li>{@link DataColumns}</li>
* <li>{@link NotesProvider}使便</li>
* <li>使便</li>
* <li>UI使便</li>
* </ul>
*/
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
* DATA1
* <p>: INTEGER (long)</p>
* <p>: Unix</p>
* <p>: </p>
*/
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
* DATA3
* <p>: TEXT</p>
* <p>: </p>
* <p>: 便</p>
*/
public static final String PHONE_NUMBER = DATA3;
/**
* 便MIMEContent Provider便使
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
/**
* 便MIMEContent Provider便使
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
/**
* 便Content Provider URI便
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}

@ -26,190 +26,314 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
* <p>
*
* <ul>
* <li> "note.db" ({@link #onCreate})</li>
* <li> ({@link #onUpgrade})</li>
* <li> {@link TABLE#NOTE}</li>
* <li> SQL Triggers </li>
* <li></li>
* <li></li>
* </ul>
* <p>
*
* <ul>
* <li></li>
* <li>使SQL Triggers</li>
* <li></li>
* <li>便</li>
* <li>便</li>
* </ul>
* <p>
*
* <ul>
* <li> {@link SQLiteOpenHelper}Android</li>
* </ul>
* <p>
*
* <ul>
* <li> {@link NotesProvider} 使Content Provider</li>
* <li>使 {@link Notes} </li>
* <li>访</li>
* </ul>
* <p>
*
* <ul>
* <li>使SQL Triggers便</li>
* <li></li>
* <li>便</li>
* <li></li>
* </ul>
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
*
* <p>note.db</p>
*/
private static final String DB_NAME = "note.db";
/**
*
* <p>
* <strong></strong>
* addColumn Trigger +1
* {@link #onUpgrade}
* </p>
* <p>
*
* <ul>
* <li>1</li>
* <li>2</li>
* <li>3Google Task ID</li>
* <li>4</li>
* </ul>
* </p>
*/
private static final int DB_VERSION = 4;
/**
*
* <p>
*
* <ul>
* <li></li>
* <li>访便</li>
* <li>{@link NotesProvider}使</li>
* </ul>
*/
public interface TABLE {
/**
* 便
* <p>IDPARENT_IDALERTED_DATEBG_COLOR_IDCREATED_DATE</p>
*/
public static final String NOTE = "note";
/**
* 便
* <p>IDMIME_TYPENOTE_IDCONTENTDATA1-DATA5</p>
*/
public static final String DATA = "data";
}
/**
*
*/
private static final String TAG = "NotesDatabaseHelper";
/**
*
* <p>
*
* <ul>
* <li></li>
* <li>线</li>
* <li>{@link #getInstance(Context)}</li>
* </ul>
*/
private static NotesDatabaseHelper mInstance;
/**
* SQL
* IDID
*/
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父文件夹ID默认为0
NoteColumns.ALERTED_DATE + " 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.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + // 是否有附件
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期,默认为当前时间
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 笔记数量(用于文件夹)
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 内容摘要
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 类型(笔记/文件夹/系统文件夹等)
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的小部件ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步ID
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 本地修改标记
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原始父文件夹ID
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // Google Task ID
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本号
")";
/**
* SQL
* MIME
*/
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + // 主键ID
DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME类型标识数据类型
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 关联的笔记ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + // 内容
DataColumns.DATA1 + " INTEGER," + // 扩展字段1整数
DataColumns.DATA2 + " INTEGER," + // 扩展字段2整数
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 扩展字段3文本
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 扩展字段4文本
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 扩展字段5文本
")";
/**
* note_id
*/
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/**
* Increase folder's note count when move note to the folder
* SQL
* <p>
* <strong></strong><br>
* 1. {@link TABLE#NOTE} {@link NoteColumns#PARENT_ID} <br>
* 2. ID (new.parent_id)<br>
* 3. 'note_count' +1
* </p>
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
* Decrease folder's note count when move note from folder
* SQL
* 0
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";
/**
* Increase folder's note count when insert new note to the folder
* SQL
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
/**
* Decrease folder's note count when delete note from the folder
* SQL
* 0
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
"CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
* SQL NOTE
* MIME_TYPEDataConstants.NOTE
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
* SQL NOTE
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
* SQL NOTE
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";
/**
* Delete datas belong to note which has been deleted
* SQL
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
* Delete notes belong to folder which has been deleted
* SQL
* delete_data_on_delete
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
"CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
* Move notes belong to folder which has been moved to trash folder
* SQL
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
*
* @param context Android
*/
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
*
* @param db SQLite
*/
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
@ -217,7 +341,13 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created");
}
/**
*
*
* @param db SQLite
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除所有旧触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,6 +356,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -235,18 +366,23 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}
/**
*
*
* @param db SQLite
*/
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*
*/
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* root folder which is default folder
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
@ -254,7 +390,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
/**
* temporary folder which is used for moving note
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
@ -262,7 +398,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*
*/
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
@ -270,13 +406,22 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values);
}
/**
*
* @param db SQLite
*/
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
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");
}
/**
*
*
* @param db SQLite
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
@ -287,6 +432,11 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
* 线
* @param context Android
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -294,69 +444,103 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance;
}
/**
*
*
* @param db SQLite
*/
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}
/**
*
*
* @param db SQLite
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
boolean reCreateTriggers = false; // 是否需要重建触发器
boolean skipV2 = false; // 是否跳过V2升级
// 从版本1升级到版本2
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
skipV2 = true; // V1到V2的升级包含了V2到V3的内容
oldVersion++;
}
// 从版本2升级到版本3如果未跳过
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db);
reCreateTriggers = true;
reCreateTriggers = true; // V3升级需要重建触发器
oldVersion++;
}
// 从版本3升级到版本4
if (oldVersion == 3) {
upgradeToV4(db);
oldVersion++;
}
// 如果需要,重建所有触发器
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
// 版本号检查,确保升级完成
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
}
}
/**
* 2
* @param db SQLite
*/
private void upgradeToV2(SQLiteDatabase db) {
// 删除旧表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
// 创建新表
createNoteTable(db);
createDataTable(db);
}
/**
* 3Google Task ID
* @param db SQLite
*/
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_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
// 添加Google Task ID字段
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
// 添加回收站系统文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
* 4
* @param db SQLite
*/
private void upgradeToV4(SQLiteDatabase db) {
// 添加版本号字段
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}
}
}

@ -35,21 +35,120 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* 便Content Provider便CRUD
* <p>
*
* <ul>
* <li>便Content Provider访</li>
* <li>便便</li>
* <li>便</li>
* <li>便</li>
* <li></li>
* </ul>
* <p>
*
* <ul>
* <li>Android Content Provider访</li>
* <li>使UriMatcherURI</li>
* <li></li>
* <li>访</li>
* <li>Android</li>
* </ul>
* <p>
*
* <ul>
* <li>{@link android.content.ContentProvider}Content Provider</li>
* </ul>
* <p>
*
* <ul>
* <li>{@link NotesDatabaseHelper}</li>
* <li>使{@link Notes}URI访</li>
* <li>{@link SearchManager}Android</li>
* <li>UIWidget使访</li>
* </ul>
* <p>
* URI
* <ul>
* <li>content://micode_notes/note - 所有便签和文件夹</li>
* <li>content://micode_notes/note/# - 单个便签或文件夹</li>
* <li>content://micode_notes/data - 所有便签详细数据</li>
* <li>content://micode_notes/data/# - 单个便签详细数据</li>
* <li>content://micode_notes/search - 搜索便签</li>
* <li>content://micode_notes/search_suggest_query - 搜索建议</li>
* </ul>
*
*/
public class NotesProvider extends ContentProvider {
/**
* UriMatcherURI
* <p>
* URI
* <p>
* URI
*/
private static final UriMatcher mMatcher;
/**
* SQLiteDatabase
* <p>
*
* <p>
* onCreate
*/
private NotesDatabaseHelper mHelper;
/**
*
*/
private static final String TAG = "NotesProvider";
/**
* URI便
*/
private static final int URI_NOTE = 1;
/**
* URI便
*/
private static final int URI_NOTE_ITEM = 2;
/**
* URI便
*/
private static final int URI_DATA = 3;
/**
* URI便
*/
private static final int URI_DATA_ITEM = 4;
/**
* URI便
*/
private static final int URI_SEARCH = 5;
/**
* URI
*/
private static final int URI_SEARCH_SUGGEST = 6;
/**
* UriMatcherURI
* <p>
* URI
* <ul>
* <li>note - 便</li>
* <li>note/# - 便</li>
* <li>data - 便</li>
* <li>data/# - 便</li>
* <li>search - 便</li>
* <li>search_suggest_query - </li>
* <li>search_suggest_query/* - </li>
* </ul>
*/
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
@ -62,8 +161,24 @@ public class NotesProvider extends ContentProvider {
}
/**
* 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.
* 便
* <p>
*
* <ul>
* <li>便ID</li>
* <li>便ID</li>
* <li>1便</li>
* <li>2便</li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* <p>
*
* <ul>
* <li>使SQLiteTRIMREPLACE便x'0A'</li>
* <li>使</li>
* </ul>
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
@ -73,18 +188,91 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
/**
* 便SQL
* <p>
*
* <ul>
* <li>便LIKE ?</li>
* <li>便PARENT_ID <> TRASH_FOLDER</li>
* <li>便便TYPE = TYPE_NOTE</li>
* </ul>
* <p>
* URI_SEARCHURI_SEARCH_SUGGEST
*/
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
/**
* Content Provider
* <p>
*
* <ul>
* <li>NotesDatabaseHelper</li>
* <li></li>
* </ul>
* <p>
*
* <ul>
* <li>{@link NotesDatabaseHelper#getInstance(android.content.Context)}</li>
* </ul>
*
* @return true
* @see android.content.ContentProvider#onCreate()
*/
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
* URICursor
* <p>
*
* <ul>
* <li>URI</li>
* <li></li>
* <li>Cursor</li>
* <li>CursorURI便</li>
* </ul>
* <p>
* URI
* <ul>
* <li>{@link #URI_NOTE} - 便</li>
* <li>{@link #URI_NOTE_ITEM} - 便</li>
* <li>{@link #URI_DATA} - 便</li>
* <li>{@link #URI_DATA_ITEM} - 便</li>
* <li>{@link #URI_SEARCH} - 便</li>
* <li>{@link #URI_SEARCH_SUGGEST} - </li>
* </ul>
* <p>
*
* <ul>
* <li>使{@link NotesDatabaseHelper#getReadableDatabase()}</li>
* <li>使{@link SQLiteDatabase}</li>
* <li>使{@link SearchManager}</li>
* </ul>
* <p>
*
* <ul>
* <li>sortOrderprojection</li>
* <li>便</li>
* <li>便</li>
* </ul>
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor Cursornull
* @throws IllegalArgumentException URI
* @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
@ -147,6 +335,43 @@ public class NotesProvider extends ContentProvider {
return c;
}
/**
* URIURI
* <p>
*
* <ul>
* <li>URI</li>
* <li></li>
* <li>ID</li>
* <li>URI</li>
* <li>IDURI</li>
* </ul>
* <p>
* URI
* <ul>
* <li>{@link #URI_NOTE} - 便</li>
* <li>{@link #URI_DATA} - 便</li>
* </ul>
* <p>
*
* <ul>
* <li>使{@link NotesDatabaseHelper#getWritableDatabase()}</li>
* <li>使{@link SQLiteDatabase}</li>
* <li>{@link android.content.ContentResolver#notifyChange(android.net.Uri, android.database.ContentObserver)}</li>
* </ul>
* <p>
*
* <ul>
* <li>noteIddataId</li>
* <li>URI</li>
* </ul>
*
* @param uri URI
* @param values
* @return Uri IDURI
* @throws IllegalArgumentException URI
* @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
@ -181,6 +406,45 @@ public class NotesProvider extends ContentProvider {
return ContentUris.withAppendedId(uri, insertedId);
}
/**
* URI
* <p>
*
* <ul>
* <li>URI</li>
* <li></li>
* <li></li>
* <li>URI</li>
* </ul>
* <p>
* URI
* <ul>
* <li>{@link #URI_NOTE} - 便</li>
* <li>{@link #URI_NOTE_ITEM} - 便</li>
* <li>{@link #URI_DATA} - 便</li>
* <li>{@link #URI_DATA_ITEM} - 便</li>
* </ul>
* <p>
*
* <ul>
* <li>使{@link NotesDatabaseHelper#getWritableDatabase()}</li>
* <li>使{@link SQLiteDatabase}</li>
* <li>{@link android.content.ContentResolver#notifyChange(android.net.Uri, android.database.ContentObserver)}</li>
* </ul>
* <p>
*
* <ul>
* <li>便ID0</li>
* <li>CONTENT_NOTE_URI</li>
* </ul>
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return int
* @throws IllegalArgumentException URI
* @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
@ -227,6 +491,48 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
* URI
* <p>
*
* <ul>
* <li>URI</li>
* <li></li>
* <li>便</li>
* <li></li>
* <li>URI</li>
* </ul>
* <p>
* URI
* <ul>
* <li>{@link #URI_NOTE} - 便</li>
* <li>{@link #URI_NOTE_ITEM} - 便</li>
* <li>{@link #URI_DATA} - 便</li>
* <li>{@link #URI_DATA_ITEM} - 便</li>
* </ul>
* <p>
*
* <ul>
* <li>使{@link NotesDatabaseHelper#getWritableDatabase()}</li>
* <li>使{@link SQLiteDatabase}</li>
* <li>{@link #increaseNoteVersion(long, String, String[])}便</li>
* <li>{@link android.content.ContentResolver#notifyChange(android.net.Uri, android.database.ContentObserver)}</li>
* </ul>
* <p>
*
* <ul>
* <li>便</li>
* <li>CONTENT_NOTE_URI</li>
* </ul>
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return int
* @throws IllegalArgumentException URI
* @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
@ -267,10 +573,49 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
*
* <p>
*
* <ul>
* <li>selection" AND (selection)"</li>
* <li></li>
* </ul>
*
* @param selection
* @return String
*/
private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
/**
* 便
* <p>
*
* <ul>
* <li>UPDATE1</li>
* <li>idselectionWHERE</li>
* <li>SQL</li>
* </ul>
* <p>
*
* <ul>
* <li>使{@link NotesDatabaseHelper#getWritableDatabase()}</li>
* <li>使{@link SQLiteDatabase#execSQL(String)}SQL</li>
* </ul>
* <p>
*
* <ul>
* <li>使SQLSQL</li>
* <li>使replaceFirst</li>
* <li>TODO: 使PreparedStatement</li>
* </ul>
*
* @param id 便ID-1便
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
@ -296,6 +641,17 @@ public class NotesProvider extends ContentProvider {
mHelper.getWritableDatabase().execSQL(sql.toString());
}
/**
* URIMIME
* <p>
* null
* <p>
* TODO: MIME
*
* @param uri URI
* @return String URIMIMEnull
* @see android.content.ContentProvider#getType(android.net.Uri)
*/
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub

@ -25,11 +25,57 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* <p>Google</p>
* <p></p>
* <ul>
* <li></li>
* <li>JSON</li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>{@link Task}</li>
* <li>使JSON便</li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>{@link Task}</li>
* <li>使{@link GTaskStringUtils}</li>
* <li>{@link GTaskManager}{@link GTaskSyncService}使</li>
* </ul>
*/
public class MetaData extends Task {
/**
* <p></p>
* <p>MetaData</p>
*/
private final static String TAG = MetaData.class.getSimpleName();
/**
* <p>GoogleID</p>
* <p>Google</p>
* <p>{@link #setContentByRemoteJSON(JSONObject)}JSON</p>
*/
private String mRelatedGid = null;
/**
* <p></p>
* <p></p>
* <ul>
* <li>GoogleIDJSON</li>
* <li>JSONnotes</li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>JSONExceptionGoogleID</li>
* </ul>
*
* @param gid GoogleID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
@ -40,15 +86,42 @@ public class MetaData extends Task {
setName(GTaskStringUtils.META_NOTE_NAME);
}
/**
* <p>GoogleID</p>
* <p>Google</p>
*
* @return GoogleIDnull
*/
public String getRelatedGid() {
return mRelatedGid;
}
/**
* <p></p>
* <p>notesnull</p>
*
* @return truefalse
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/**
* <p>JSON</p>
* <p></p>
* <ul>
* <li>setContentByRemoteJSON</li>
* <li>notesnullJSON</li>
* <li>GoogleID</li>
* </ul>
* <p></p>
* <ul>
* <li>JSONExceptionmRelatedGidnull</li>
* </ul>
*
* @param js JSON
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
@ -63,17 +136,42 @@ public class MetaData extends Task {
}
}
/**
* <p>JSON</p>
* <p>IllegalAccessError</p>
* <p>MetaDataJSON</p>
*
* @param js JSON
* @throws IllegalAccessError
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/**
* <p>JSON</p>
* <p>IllegalAccessError</p>
* <p>MetaDataJSON</p>
*
* @return JSON
* @throws IllegalAccessError
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/**
* <p></p>
* <p>IllegalAccessError</p>
* <p>MetaData</p>
*
* @param c
* @return
* @throws IllegalAccessError
*/
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");

@ -20,33 +20,91 @@ import android.database.Cursor;
import org.json.JSONObject;
/**
* <p>Google</p>
* <p>Google</p>
* <p></p>
* <ul>
* <li>GoogleIDGID</li>
* <li>//JSON</li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>{@link Task}, {@link MetaData}</li>
* <li>{@link GTaskClient}Google</li>
* <li>{@link Cursor}</li>
* </ul>
*/
public abstract class Node {
/**
*
*/
public static final int SYNC_ACTION_NONE = 0;
/**
*
*/
public static final int SYNC_ACTION_ADD_REMOTE = 1;
/**
*
*/
public static final int SYNC_ACTION_ADD_LOCAL = 2;
/**
*
*/
public static final int SYNC_ACTION_DEL_REMOTE = 3;
/**
*
*/
public static final int SYNC_ACTION_DEL_LOCAL = 4;
/**
*
*/
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
/**
*
*/
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
/**
*
*/
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
/**
*
*/
public static final int SYNC_ACTION_ERROR = 8;
/**
* GoogleID
*/
private String mGid;
/**
*
*/
private String mName;
/**
*
*/
private long mLastModified;
/**
*
*/
private boolean mDeleted;
/**
*
*/
public Node() {
mGid = null;
mName = "";
@ -54,46 +112,134 @@ public abstract class Node {
mDeleted = false;
}
/**
* <p>JSON</p>
* <p>GoogleJSON</p>
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId);
/**
* <p>JSON</p>
* <p>GoogleJSON</p>
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId);
/**
* <p>JSON</p>
* <p>GoogleJSON</p>
*
* @param js JSONGoogle
*/
public abstract void setContentByRemoteJSON(JSONObject js);
/**
* <p>JSON</p>
* <p>JSON</p>
*
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js);
/**
* <p>JSON</p>
* <p>JSON</p>
*
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent();
/**
* <p></p>
* <p></p>
* <p>
* <ul>
* <li>{@link #SYNC_ACTION_NONE}</li>
* <li>{@link #SYNC_ACTION_ADD_REMOTE}</li>
* <li>{@link #SYNC_ACTION_UPDATE_LOCAL}</li>
* <li>{@link #SYNC_ACTION_UPDATE_CONFLICT}</li>
* <li></li>
* </ul>
* </p>
*
* @param c
* @return {@link #SYNC_ACTION_NONE}{@link #SYNC_ACTION_ERROR}
*/
public abstract int getSyncAction(Cursor c);
/**
* GoogleID
*
* @param gid GoogleID
*/
public void setGid(String gid) {
this.mGid = gid;
}
/**
*
*
* @param name
*/
public void setName(String name) {
this.mName = name;
}
/**
*
*
* @param lastModified
*/
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}
/**
*
*
* @param deleted
*/
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
/**
* GoogleID
*
* @return GoogleID
*/
public String getGid() {
return this.mGid;
}
/**
*
*
* @return
*/
public String getName() {
return this.mName;
}
/**
*
*
* @return
*/
public long getLastModified() {
return this.mLastModified;
}
/**
*
*
* @return
*/
public boolean getDeleted() {
return this.mDeleted;
}

@ -35,42 +35,103 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* <p>SQL便</p>
* <p>GoogleContentProvider访</p>
* <p></p>
* <ul>
* <li>Cursor</li>
* <li>JSON</li>
* <li>ContentProvider</li>
* <li></li>
* </ul>
*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
/**
* ID
*/
private static final int INVALID_ID = -99999;
/**
*
*/
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
/**
* ID
*/
public static final int DATA_ID_COLUMN = 0;
/**
* MIME
*/
public static final int DATA_MIME_TYPE_COLUMN = 1;
/**
*
*/
public static final int DATA_CONTENT_COLUMN = 2;
/**
* DATA1
*/
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
/**
* DATA3
*/
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
/**
* 访ContentProvider
*/
private ContentResolver mContentResolver;
/**
*
*/
private boolean mIsCreate;
/**
* ID
*/
private long mDataId;
/**
* MIME
*/
private String mDataMimeType;
/**
*
*/
private String mDataContent;
/**
* DATA1
*/
private long mDataContentData1;
/**
* DATA3
*/
private String mDataContentData3;
/**
*
*/
private ContentValues mDiffDataValues;
/**
* <p>SqlData</p>
*
* @param context
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -82,6 +143,12 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
* <p>CursorSqlData</p>
*
* @param context
* @param c Cursor
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -89,6 +156,11 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
* <p>Cursor</p>
*
* @param c Cursor
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,6 +169,18 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/**
* <p>JSON</p>
* <p></p>
* <ul>
* <li>JSON</li>
* <li></li>
* <li></li>
* </ul>
*
* @param js JSON
* @throws JSONException JSON
*/
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
@ -130,6 +214,18 @@ public class SqlData {
mDataContentData3 = dataContentData3;
}
/**
* <p>JSON</p>
* <p></p>
* <ul>
* <li></li>
* <li>JSON</li>
* <li>JSON</li>
* </ul>
*
* @return JSONnull
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
@ -144,6 +240,21 @@ public class SqlData {
return js;
}
/**
* <p>ContentProvider</p>
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
*
* @param noteId 便ID
* @param validateVersion
* @param version
* @throws ActionFailureException
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
@ -183,6 +294,11 @@ public class SqlData {
mIsCreate = false;
}
/**
* <p>ID</p>
*
* @return ID
*/
public long getId() {
return mDataId;
}

@ -38,11 +38,50 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* <p>便Google便</p>
* <p></p>
* <ul>
* <li>便</li>
* <li>便{@link SqlData}</li>
* <li>便JSON</li>
* <li>便</li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>Google</li>
* <li>ContentProviderAPI</li>
* <li></li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>使{@link Context}访ContentResolver</li>
* <li>使{@link ContentProvider}</li>
* <li>{@link SqlData}便</li>
* <li>{@link GTaskManager}Google</li>
* </ul>
*/
public class SqlNote {
/**
* <p></p>
* <p>SqlNote便</p>
*/
private static final String TAG = SqlNote.class.getSimpleName();
/**
* <p>ID</p>
* <p>便ID</p>
* <p>-99999</p>
*/
private static final int INVALID_ID = -99999;
/**
* <p>便</p>
* <p>ContentProvider便</p>
* <p>IDID</p>
*/
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -52,76 +91,264 @@ public class SqlNote {
NoteColumns.VERSION
};
/**
* <p>ID</p>
* <p>PROJECTION_NOTEID</p>
* <p>0</p>
*/
public static final int ID_COLUMN = 0;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>1</p>
*/
public static final int ALERTED_DATE_COLUMN = 1;
/**
* <p>ID</p>
* <p>PROJECTION_NOTEID</p>
* <p>2</p>
*/
public static final int BG_COLOR_ID_COLUMN = 2;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>3</p>
*/
public static final int CREATED_DATE_COLUMN = 3;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>4</p>
*/
public static final int HAS_ATTACHMENT_COLUMN = 4;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>5</p>
*/
public static final int MODIFIED_DATE_COLUMN = 5;
/**
* <p>便</p>
* <p>PROJECTION_NOTE便</p>
* <p>6</p>
*/
public static final int NOTES_COUNT_COLUMN = 6;
/**
* <p>ID</p>
* <p>PROJECTION_NOTEID</p>
* <p>7</p>
*/
public static final int PARENT_ID_COLUMN = 7;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>8</p>
*/
public static final int SNIPPET_COLUMN = 8;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>9</p>
*/
public static final int TYPE_COLUMN = 9;
/**
* <p>ID</p>
* <p>PROJECTION_NOTEID</p>
* <p>10</p>
*/
public static final int WIDGET_ID_COLUMN = 10;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>11</p>
*/
public static final int WIDGET_TYPE_COLUMN = 11;
/**
* <p>ID</p>
* <p>PROJECTION_NOTEID</p>
* <p>12</p>
*/
public static final int SYNC_ID_COLUMN = 12;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>13</p>
*/
public static final int LOCAL_MODIFIED_COLUMN = 13;
/**
* <p>ID</p>
* <p>PROJECTION_NOTEID</p>
* <p>14</p>
*/
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
/**
* <p>GoogleID</p>
* <p>PROJECTION_NOTEGoogleID</p>
* <p>15</p>
*/
public static final int GTASK_ID_COLUMN = 15;
/**
* <p></p>
* <p>PROJECTION_NOTE</p>
* <p>16</p>
*/
public static final int VERSION_COLUMN = 16;
/**
* <p></p>
* <p>访ContentResolver</p>
* <p>使ContentProvider</p>
*/
private Context mContext;
/**
* <p></p>
* <p>ContentProvider</p>
* <p>使CRUD</p>
*/
private ContentResolver mContentResolver;
/**
* <p>便</p>
* <p>便</p>
* <p>使</p>
*/
private boolean mIsCreate;
/**
* <p>便ID</p>
* <p>便</p>
* <p>INVALID_ID-99999</p>
*/
private long mId;
/**
* <p></p>
* <p>便</p>
* <p>0</p>
*/
private long mAlertDate;
/**
* <p>ID</p>
* <p>便ID</p>
* <p>ResourceParser.getDefaultBgId(context)</p>
*/
private int mBgColorId;
/**
* <p></p>
* <p>便</p>
* <p></p>
*/
private long mCreatedDate;
/**
* <p></p>
* <p>便</p>
* <p>01</p>
* <p>0</p>
*/
private int mHasAttachment;
/**
* <p></p>
* <p>便</p>
* <p></p>
*/
private long mModifiedDate;
/**
* <p>便ID</p>
* <p>便ID</p>
* <p>0</p>
*/
private long mParentId;
/**
* <p>便</p>
* <p>便</p>
* <p></p>
*/
private String mSnippet;
/**
* <p>便</p>
* <p>便便</p>
* <p>Notes.TYPE_NOTE</p>
*/
private int mType;
/**
* <p>ID</p>
* <p>ID</p>
* <p>AppWidgetManager.INVALID_APPWIDGET_ID</p>
*/
private int mWidgetId;
/**
* <p></p>
* <p></p>
* <p>Notes.TYPE_WIDGET_INVALIDE</p>
*/
private int mWidgetType;
/**
* <p>便ID</p>
* <p>便ID</p>
* <p>0</p>
*/
private long mOriginParent;
/**
* <p></p>
* <p>便</p>
* <p>0</p>
*/
private long mVersion;
/**
* <p>便</p>
* <p>便</p>
* <p>使setContentcommit</p>
*/
private ContentValues mDiffNoteValues;
/**
* <p>便</p>
* <p>便</p>
* <p>使SqlData便</p>
*/
private ArrayList<SqlData> mDataList;
/**
* <p>SqlNote</p>
* <p>便</p>
* <p></p>
* <ul>
* <li>mIsCreatetrue便</li>
* <li></li>
* <li></li>
* </ul>
*
* @param context 访ContentResolver
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -143,6 +370,20 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>();
}
/**
* <p>CursorSqlNote</p>
* <p>便</p>
* <p></p>
* <ul>
* <li>mIsCreatefalse便</li>
* <li>Cursor便</li>
* <li>便便</li>
* <li></li>
* </ul>
*
* @param context 访ContentResolver
* @param c Cursor便
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -154,6 +395,20 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
}
/**
* <p>IDSqlNote</p>
* <p>便ID便</p>
* <p></p>
* <ul>
* <li>mIsCreatefalse便</li>
* <li>ID便</li>
* <li>便便</li>
* <li></li>
* </ul>
*
* @param context 访ContentResolver
* @param id 便ID便
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -163,7 +418,6 @@ public class SqlNote {
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
private void loadFromCursor(long id) {

@ -32,19 +32,55 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* <p>Google{@link Node}</p>
* <p>Google</p>
* <p></p>
* <ul>
* <li>Google</li>
* <li>//JSON</li>
* <li></li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>{@link Node}Google</li>
* <li>{@link TaskList}</li>
* <li>{@link MetaData}</li>
* <li>{@link GTaskStringUtils}使GoogleJSON</li>
* </ul>
*/
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
/**
*
*/
private boolean mCompleted;
/**
*
*/
private String mNotes;
/**
* JSON
*/
private JSONObject mMetaInfo;
/**
*
*/
private Task mPriorSibling;
/**
*
*/
private TaskList mParent;
/**
*
*/
public Task() {
super();
mCompleted = false;
@ -54,6 +90,26 @@ public class Task extends Node {
mMetaInfo = null;
}
/**
* <p>JSON</p>
* <p>GoogleJSON</p>
* <p>JSON
* <ul>
* <li>action_type: "create"</li>
* <li>action_id: ID</li>
* <li>index: </li>
* <li>entity_delta: ID</li>
* <li>parent_id: ID</li>
* <li>dest_parent_type: "group"</li>
* <li>list_id: ID</li>
* <li>prior_sibling_id: ID</li>
* </ul>
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -103,6 +159,22 @@ public class Task extends Node {
return js;
}
/**
* <p>JSON</p>
* <p>GoogleJSON</p>
* <p>JSON
* <ul>
* <li>action_type: "update"</li>
* <li>action_id: ID</li>
* <li>id: ID</li>
* <li>entity_delta: </li>
* </ul>
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -135,6 +207,23 @@ public class Task extends Node {
return js;
}
/**
* <p>JSON</p>
* <p>GoogleJSON</p>
* <p>JSON
* <ul>
* <li>id: IDGID</li>
* <li>last_modified: </li>
* <li>name: </li>
* <li>notes: </li>
* <li>deleted: </li>
* <li>completed: </li>
* </ul>
* </p>
*
* @param js JSONGoogle
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -175,6 +264,18 @@ public class Task extends Node {
}
}
/**
* <p>JSON</p>
* <p>JSON</p>
* <p>JSON
* <ul>
* <li>meta_note: </li>
* <li>meta_data: MIMENOTE</li>
* </ul>
* </p>
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@ -204,6 +305,24 @@ public class Task extends Node {
}
}
/**
* <p>JSON</p>
* <p>JSON</p>
* <p>JSON
* <ul>
* <li>meta_note: </li>
* <li>meta_data: MIMENOTE</li>
* </ul>
* </p>
* <p>
* <ol>
* <li>JSONWeb</li>
* <li></li>
* </ol>
* </p>
*
* @return JSON
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
@ -247,6 +366,19 @@ public class Task extends Node {
}
}
/**
* <p></p>
* <p>MetaDataJSON</p>
* <p>
* <ol>
* <li>MetaDatanotes</li>
* <li>notesJSONJSONObject</li>
* <li>null</li>
* </ol>
* </p>
*
* @param metaData MetaData
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -258,6 +390,30 @@ public class Task extends Node {
}
}
/**
* <p></p>
* <p></p>
* <p>
* <ul>
* <li>{@link Node#SYNC_ACTION_NONE}: </li>
* <li>{@link Node#SYNC_ACTION_UPDATE_LOCAL}: </li>
* <li>{@link Node#SYNC_ACTION_UPDATE_REMOTE}: </li>
* <li>{@link Node#SYNC_ACTION_UPDATE_CONFLICT}: </li>
* <li>{@link Node#SYNC_ACTION_ERROR}: </li>
* </ul>
* </p>
* <p>
* <ol>
* <li>ID</li>
* <li></li>
* <li>GTASK ID</li>
* <li></li>
* </ol>
* </p>
*
* @param c
* @return NodeSYNC_ACTION_*
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -311,39 +467,92 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
/**
* <p></p>
* <p></p>
* <p>
* <ul>
* <li>mMetaInfonull</li>
* <li>0</li>
* <li>0</li>
* </ul>
* </p>
*
* @return truefalse
*/
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
/**
*
*
* @param completed truefalse
*/
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
/**
*
*
* @param notes
*/
public void setNotes(String notes) {
this.mNotes = notes;
}
/**
*
*
* @param priorSibling
*/
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}
/**
*
*
* @param parent
*/
public void setParent(TaskList parent) {
this.mParent = parent;
}
/**
*
*
* @return truefalse
*/
public boolean getCompleted() {
return this.mCompleted;
}
/**
*
*
* @return
*/
public String getNotes() {
return this.mNotes;
}
/**
*
*
* @return null
*/
public Task getPriorSibling() {
return this.mPriorSibling;
}
/**
*
*
* @return null
*/
public TaskList getParent() {
return this.mParent;
}

@ -30,19 +30,53 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* GoogleNode
* <p>
* Google Tasks
*
* <ul>
* <li>/JSON</li>
* <li>/JSON</li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();
/**
* Google
*/
private int mIndex;
/**
*
*/
private ArrayList<Task> mChildren;
/**
*
* <p>
* 1
* </p>
*/
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
/**
* JSON
* <p>
* Google Tasks
* </p>
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -74,6 +108,15 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* <p>
* Google Tasks
* </p>
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -103,6 +146,14 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* <p>
* Google TasksJSON
* </p>
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -129,6 +180,13 @@ public class TaskList extends Node {
}
}
/**
* JSON
* <p>
* JSON
* </p>
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -157,6 +215,13 @@ public class TaskList extends Node {
}
}
/**
* JSON
* <p>
* JSON
* </p>
* @return JSONnull
*/
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();
@ -183,6 +248,20 @@ public class TaskList extends Node {
}
}
/**
*
* <p>
*
* </p>
* @param c
* @return
* <ul>
* <li>{@link Node#SYNC_ACTION_NONE} - </li>
* <li>{@link Node#SYNC_ACTION_UPDATE_LOCAL} - </li>
* <li>{@link Node#SYNC_ACTION_UPDATE_REMOTE} - </li>
* <li>{@link Node#SYNC_ACTION_ERROR} - </li>
* </ul>
*/
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
@ -216,10 +295,22 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
* @return
*/
public int getChildTaskCount() {
return mChildren.size();
}
/**
*
* <p>
*
* </p>
* @param task
* @return true if the task was added successfully, false otherwise
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
@ -234,6 +325,15 @@ public class TaskList extends Node {
return ret;
}
/**
*
* <p>
*
* </p>
* @param task
* @param index
* @return true if the task was added successfully, false otherwise
*/
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
@ -260,6 +360,14 @@ public class TaskList extends Node {
return true;
}
/**
*
* <p>
*
* </p>
* @param task
* @return true if the task was removed successfully, false otherwise
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -281,6 +389,15 @@ public class TaskList extends Node {
return ret;
}
/**
*
* <p>
*
* </p>
* @param task
* @param index
* @return true if the task was moved successfully, false otherwise
*/
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -299,6 +416,11 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
/**
* GoogleID
* @param gid GoogleID
* @return null
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,10 +431,20 @@ public class TaskList extends Node {
return null;
}
/**
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,6 +453,14 @@ public class TaskList extends Node {
return mChildren.get(index);
}
/**
* GoogleID
* <p>
* {@link #findChildTaskByGid(String)}
* </p>
* @param gid GoogleID
* @return null
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@ -329,14 +469,26 @@ public class TaskList extends Node {
return null;
}
/**
*
* @return
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
/**
*
* @param index
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
* @return
*/
public int getIndex() {
return this.mIndex;
}

@ -16,17 +16,37 @@
package net.micode.notes.gtask.exception;
/**
* <p>Google</p>
* <p>Google</p>
* <p>Google</p>
* <p>{@link RuntimeException}</p>
*/
public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L;
/**
*
*/
public ActionFailureException() {
super();
}
/**
* 使
*
* @param paramString
*/
public ActionFailureException(String paramString) {
super(paramString);
}
/**
* 使
*
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -16,17 +16,37 @@
package net.micode.notes.gtask.exception;
/**
* <p></p>
* <p>Google</p>
* <p></p>
* <p>{@link Exception}</p>
*/
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
/**
*
*/
public NetworkFailureException() {
super();
}
/**
* 使
*
* @param paramString
*/
public NetworkFailureException(String paramString) {
super(paramString);
}
/**
* 使
*
* @param paramString
* @param paramThrowable
*/
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}

@ -28,23 +28,68 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/**
* <p>Google</p>
* <p>使AsyncTaskGoogle线</p>
* <p></p>
* <ul>
* <li>线Google</li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>{@link AsyncTask}</li>
* <li>使{@link GTaskManager}</li>
* <li>{@link GTaskSyncService}广</li>
* <li>{@link OnCompleteListener}</li>
* </ul>
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
/**
* GoogleID
*/
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
/**
* <p></p>
* <p>Google</p>
*/
public interface OnCompleteListener {
/**
*
*/
void onComplete();
}
/**
* 访
*/
private Context mContext;
/**
*
*/
private NotificationManager mNotifiManager;
/**
* Google
*/
private GTaskManager mTaskManager;
/**
*
*/
private OnCompleteListener mOnCompleteListener;
/**
* Google
*
* @param context 访
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
@ -53,35 +98,81 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance();
}
/**
*
*/
public void cancelSync() {
mTaskManager.cancelSync();
}
/**
*
*
* @param message
*/
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
}
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
}
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
// private void showNotification(int tickerId, String content) {
// Notification notification = new Notification(R.drawable.notification, mContext
// .getString(tickerId), System.currentTimeMillis());
// notification.defaults = Notification.DEFAULT_LIGHTS;
// notification.flags = Notification.FLAG_AUTO_CANCEL;
// PendingIntent pendingIntent;
// if (tickerId != R.string.ticker_success) {
// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
// NotesPreferenceActivity.class), 0);
//
// } else {
// pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
// NotesListActivity.class), 0);
// }
// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
// pendingIntent);
// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
// }
/**
* <p></p>
* <p></p>
* <p>
* <ul>
* <li></li>
* <li></li>
* </ul>
* </p>
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
}
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(content)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification=builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
* <p>线</p>
* <p>GTaskManager</p>
*
* @param unused 使
* @return GTaskManagerSTATE_*
*/
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
@ -89,6 +180,12 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
return mTaskManager.sync(mContext, this);
}
/**
* <p></p>
* <p>广</p>
*
* @param progress
*/
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
@ -97,6 +194,20 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
/**
* <p></p>
* <p></p>
* <p>
* <ul>
* <li>STATE_SUCCESS</li>
* <li>STATE_NETWORK_ERROR</li>
* <li>STATE_INTERNAL_ERROR</li>
* <li>STATE_SYNC_CANCELLED</li>
* </ul>
* </p>
*
* @param result GTaskManagerSTATE_*
*/
@Override
protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) {

@ -61,35 +61,108 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* <p>GoogleAPI</p>
* <p>GoogleAPI</p>
* <p></p>
* <ul>
* <li>Google</li>
* <li>GoogleCRUD</li>
* <li>APICookie</li>
* <li></li>
* <li>GoogleAPIJSON</li>
* </ul>
* <p></p>
* <ul>
* <li>{@link GTaskManager}</li>
* <li>使{@link Task}{@link TaskList}Google</li>
* <li>{@link NetworkFailureException}{@link ActionFailureException}</li>
* <li>{@link GTaskStringUtils}API</li>
* </ul>
* <p></p>
* <ul>
* <li>GoogleAPI</li>
* <li></li>
* <li>API</li>
* <li>gzipdeflate</li>
* </ul>
*/
public class GTaskClient {
/**
*
*/
private static final String TAG = GTaskClient.class.getSimpleName();
/**
* GoogleURL
*/
private static final String GTASK_URL = "https://mail.google.com/tasks/";
/**
* GoogleGETURL
*/
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
/**
* GooglePOSTURL
*/
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
/**
* GTaskClient
*/
private static GTaskClient mInstance = null;
/**
* HTTPGoogleAPI
*/
private DefaultHttpClient mHttpClient;
/**
* 使GETURL
*/
private String mGetUrl;
/**
* 使POSTURL
*/
private String mPostUrl;
/**
* Google
*/
private long mClientVersion;
/**
*
*/
private boolean mLoggedin;
/**
*
*/
private long mLastLoginTime;
/**
* IDAPI
*/
private int mActionId;
/**
* Google
*/
private Account mAccount;
/**
* JSON
*/
private JSONArray mUpdateArray;
/**
* <p></p>
* <p></p>
* <p></p>
*/
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -102,6 +175,12 @@ public class GTaskClient {
mUpdateArray = null;
}
/**
* <p>GTaskClient</p>
* <p>使线</p>
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,6 +188,19 @@ public class GTaskClient {
return mInstance;
}
/**
* <p>GoogleGoogleAPI</p>
* <p></p>
* <ul>
* <li>Cookie</li>
* <li>Google</li>
* <li>使URL</li>
* <li>使URL</li>
* </ul>
*
* @param activity Activity
* @return truefalse
*/
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
@ -164,6 +256,20 @@ public class GTaskClient {
return true;
}
/**
* <p>Google</p>
* <p></p>
* <ul>
* <li>Google</li>
* <li>Account</li>
* <li>使AccountManager</li>
* <li>使</li>
* </ul>
*
* @param activity ActivityAccountManager
* @param invalidateToken 使
* @return null
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@ -207,6 +313,19 @@ public class GTaskClient {
return authToken;
}
/**
* <p>GoogleAPI</p>
* <p></p>
* <ul>
* <li>使</li>
* <li>使</li>
* <li>使</li>
* </ul>
*
* @param activity Activity
* @param authToken Google
* @return truefalse
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
@ -225,6 +344,20 @@ public class GTaskClient {
return true;
}
/**
* <p>GoogleAPI</p>
* <p></p>
* <ul>
* <li>HTTP</li>
* <li>Cookie</li>
* <li>HTTP GET</li>
* <li>Cookie</li>
* <li></li>
* </ul>
*
* @param authToken Google
* @return truefalse
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -280,10 +413,22 @@ public class GTaskClient {
return true;
}
/**
* <p>ID</p>
* <p>IDAPI</p>
*
* @return ID
*/
private int getActionId() {
return mActionId++;
}
/**
* <p>HTTP POST</p>
* <p>POSTURL</p>
*
* @return HttpPost
*/
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,6 +436,19 @@ public class GTaskClient {
return httpPost;
}
/**
* <p>HTTP</p>
* <p></p>
* <ul>
* <li></li>
* <li>gzipdeflate</li>
* <li></li>
* </ul>
*
* @param entity HTTP
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
@ -323,6 +481,21 @@ public class GTaskClient {
}
}
/**
* <p>POSTGoogleAPI</p>
* <p></p>
* <ul>
* <li></li>
* <li>HTTP POST</li>
* <li>JSON</li>
* <li></li>
* <li>JSON</li>
* </ul>
*
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
@ -360,6 +533,19 @@ public class GTaskClient {
}
}
/**
* <p>Google</p>
* <p></p>
* <ul>
* <li></li>
* <li>JSON</li>
* <li>POST</li>
* <li>GID</li>
* </ul>
*
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
@ -386,6 +572,19 @@ public class GTaskClient {
}
}
/**
* <p>Google</p>
* <p></p>
* <ul>
* <li></li>
* <li>JSON</li>
* <li>POST</li>
* <li>GID</li>
* </ul>
*
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
@ -412,6 +611,12 @@ public class GTaskClient {
}
}
/**
* <p></p>
* <p>mUpdateArrayGoogleAPI</p>
*
* @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
@ -433,6 +638,17 @@ public class GTaskClient {
}
}
/**
* <p></p>
* <p></p>
* <ul>
* <li>10</li>
* <li></li>
* </ul>
*
* @param node
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
@ -447,6 +663,21 @@ public class GTaskClient {
}
}
/**
* <p></p>
* <p></p>
* <ul>
* <li></li>
* <li>JSON</li>
* <li>ID</li>
* <li>POST</li>
* </ul>
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
@ -486,6 +717,20 @@ public class GTaskClient {
}
}
/**
* <p></p>
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li>JSON</li>
* <li>POST</li>
* <li></li>
* </ul>
*
* @param node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
@ -509,6 +754,18 @@ public class GTaskClient {
}
}
/**
* <p>Google</p>
* <p></p>
* <ul>
* <li></li>
* <li>GET</li>
* <li></li>
* </ul>
*
* @return JSON
* @throws NetworkFailureException
*/
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");

@ -48,45 +48,121 @@ import java.util.Iterator;
import java.util.Map;
/**
* <p>Google</p>
* <p>Google便</p>
* <p></p>
* <ul>
* <li>Google</li>
* <li>Google</li>
* <li>便Google</li>
* <li></li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>{@link GTaskClient}GoogleAPI</li>
* <li>使{@link SqlNote}便CRUD</li>
* <li>{@link TaskList}{@link Task}</li>
* <li>{@link MetaData}</li>
* </ul>
*/
public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName();
/**
*
*/
public static final int STATE_SUCCESS = 0;
/**
*
*/
public static final int STATE_NETWORK_ERROR = 1;
/**
*
*/
public static final int STATE_INTERNAL_ERROR = 2;
/**
*
*/
public static final int STATE_SYNC_IN_PROGRESS = 3;
/**
*
*/
public static final int STATE_SYNC_CANCELLED = 4;
/**
* GTaskManager
*/
private static GTaskManager mInstance = null;
/**
* GoogleActivity
*/
private Activity mActivity;
/**
*
*/
private Context mContext;
/**
* 访便
*/
private ContentResolver mContentResolver;
/**
*
*/
private boolean mSyncing;
/**
*
*/
private boolean mCancelled;
/**
* GooglekeyGID
*/
private HashMap<String, TaskList> mGTaskListHashMap;
/**
* GooglekeyGID
*/
private HashMap<String, Node> mGTaskHashMap;
/**
* keyGID
*/
private HashMap<String, MetaData> mMetaHashMap;
/**
*
*/
private TaskList mMetaList;
/**
* 便ID
*/
private HashSet<Long> mLocalDeleteIdMap;
/**
* GIDID
*/
private HashMap<String, Long> mGidToNid;
/**
* IDGID
*/
private HashMap<Long, String> mNidToGid;
/**
*
*/
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -99,6 +175,11 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
/**
* GTaskManager
*
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,11 +187,41 @@ public class GTaskManager {
return mInstance;
}
/**
* GoogleActivity
*
* @param activity Activity
*/
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity;
}
/**
* Google便
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li>Google</li>
* <li>Google</li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
*
* @param context
* @param asyncTask
* @return
* <ul>
* <li>{@link #STATE_SUCCESS}</li>
* <li>{@link #STATE_NETWORK_ERROR}</li>
* <li>{@link #STATE_INTERNAL_ERROR}</li>
* <li>{@link #STATE_SYNC_IN_PROGRESS}</li>
* <li>{@link #STATE_SYNC_CANCELLED}</li>
* </ul>
*/
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@ -168,6 +279,19 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/**
* GoogleGoogle
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
*
* @throws NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@ -247,6 +371,21 @@ public class GTaskManager {
}
}
/**
* 便Google
*
* <p></p>
* <ul>
* <li>便</li>
* <li></li>
* <li>便</li>
* <li>Google</li>
* <li>便</li>
* <li>ID</li>
* </ul>
*
* @throws NetworkFailureException
*/
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
@ -351,6 +490,19 @@ public class GTaskManager {
}
/**
*
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li>Google</li>
* </ul>
*
* @throws NetworkFailureException
*/
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -476,6 +628,21 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate();
}
/**
*
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
*
* @param syncType
* @param node Google
* @param c 便
* @throws NetworkFailureException
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -522,6 +689,21 @@ public class GTaskManager {
}
}
/**
* Google便
*
* <p></p>
* <ul>
* <li>SqlNote</li>
* <li>JSONID</li>
* <li>ID</li>
* <li></li>
* <li></li>
* </ul>
*
* @param node Google
* @throws NetworkFailureException
*/
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
@ -596,6 +778,21 @@ public class GTaskManager {
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
* 便
*
* <p></p>
* <ul>
* <li>SqlNote</li>
* <li>ID</li>
* <li></li>
* <li></li>
* </ul>
*
* @param node Google
* @param c 便
* @throws NetworkFailureException
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -619,6 +816,21 @@ public class GTaskManager {
updateRemoteMeta(node.getGid(), sqlNote);
}
/**
* 便Google
*
* <p></p>
* <ul>
* <li>便Google</li>
* <li></li>
* <li>便GID</li>
* <li></li>
* </ul>
*
* @param node Google
* @param c 便
* @throws NetworkFailureException
*/
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -692,6 +904,21 @@ public class GTaskManager {
mNidToGid.put(sqlNote.getId(), n.getGid());
}
/**
* Google
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
*
* @param node Google
* @param c 便
* @throws NetworkFailureException
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -730,6 +957,19 @@ public class GTaskManager {
sqlNote.commit(true);
}
/**
*
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* </ul>
*
* @param gid GID
* @param sqlNote 便
* @throws NetworkFailureException
*/
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
@ -746,6 +986,17 @@ public class GTaskManager {
}
}
/**
* 便ID
*
* <p></p>
* <ul>
* <li>Google</li>
* <li>便ID</li>
* </ul>
*
* @throws NetworkFailureException
*/
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
@ -790,10 +1041,18 @@ public class GTaskManager {
}
}
/**
*
*
* @return
*/
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
/**
*
*/
public void cancelSync() {
mCancelled = true;
}

@ -23,25 +23,81 @@ import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
/**
* <p>Google</p>
* <p>AndroidGoogle</p>
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li>广</li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>使{@link GTaskASyncTask}</li>
* <li>{@link GTaskManager}</li>
* <li>广UI</li>
* </ul>
*/
public class GTaskSyncService extends Service {
/**
* Intent extra
*/
public final static String ACTION_STRING_NAME = "sync_action_type";
/**
*
*/
public final static int ACTION_START_SYNC = 0;
/**
*
*/
public final static int ACTION_CANCEL_SYNC = 1;
/**
*
*/
public final static int ACTION_INVALID = 2;
/**
* 广
*/
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
/**
* 广extra
*/
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
/**
* 广extra
*/
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
/**
*
*/
private static GTaskASyncTask mSyncTask = null;
/**
*
*/
private static String mSyncProgress = "";
/**
* Google
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li>广</li>
* <li></li>
* </ul>
*/
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -56,17 +112,49 @@ public class GTaskSyncService extends Service {
}
}
/**
* Google
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* </ul>
*/
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
/**
*
*
* <p></p>
* <ul>
* <li>null</li>
* </ul>
*/
@Override
public void onCreate() {
mSyncTask = null;
}
/**
* Intent
*
* <p></p>
* <ul>
* <li>Intent</li>
* <li></li>
* <li>START_STICKY</li>
* </ul>
*
* @param intent Intent
* @param flags
* @param startId ID
* @return
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
@ -86,6 +174,14 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId);
}
/**
*
*
* <p></p>
* <ul>
* <li></li>
* </ul>
*/
@Override
public void onLowMemory() {
if (mSyncTask != null) {
@ -93,10 +189,33 @@ public class GTaskSyncService extends Service {
}
}
/**
*
*
* <p></p>
* <ul>
* <li>null</li>
* </ul>
*
* @param intent Intent
* @return null
*/
public IBinder onBind(Intent intent) {
return null;
}
/**
* 广
*
* <p></p>
* <ul>
* <li></li>
* <li>广Intent</li>
* <li>广UI</li>
* </ul>
*
* @param msg
*/
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -105,6 +224,18 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent);
}
/**
* Google
*
* <p></p>
* <ul>
* <li>GTaskManagerActivity</li>
* <li>Intent</li>
* <li></li>
* </ul>
*
* @param activity Activity
*/
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
@ -112,16 +243,47 @@ public class GTaskSyncService extends Service {
activity.startService(intent);
}
/**
* Google
*
* <p></p>
* <ul>
* <li>Intent</li>
* <li></li>
* </ul>
*
* @param context
*/
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
/**
*
*
* <p></p>
* <ul>
* <li>null</li>
* </ul>
*
* @return truefalse
*/
public static boolean isSyncing() {
return mSyncTask != null;
}
/**
*
*
* <p></p>
* <ul>
* <li></li>
* </ul>
*
* @return
*/
public static String getProgressString() {
return mSyncProgress;
}

@ -34,12 +34,61 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
* <p></p>
* <p></p>
* <ul>
* <li>{@link #mNoteDiffValues}</li>
* <li>{@link NoteData}</li>
* <li>ContentResolver</li>
* </ul>
* <p></p>
* <ul>
* <li>{@link net.micode.notes.data.NotesProvider}CRUD</li>
* <li>使{@link android.content.ContentValues}</li>
* <li>{@link android.content.ContentProviderOperation}</li>
* </ul>
*/
public class Note {
/**
* <p></p>
* <p></p>
* <p></p>
*/
private ContentValues mNoteDiffValues;
/**
* <p></p>
* <p></p>
*/
private NoteData mNoteData;
/**
* <p></p>
* <p>Note</p>
*/
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
* <p>ID</p>
* <p>ID</p>
* <p>线使synchronized线</p>
*
* @param context ContentResolver
* @param folderId ID
* @return ID
* @throws IllegalStateException ID-1
*
* <p></p>
* <ul>
* <li>{@link Context#getContentResolver()}ContentResolver</li>
* <li>{@link android.content.ContentResolver#insert(Uri, ContentValues)}{@link Notes#CONTENT_NOTE_URI}</li>
* </ul>
*
* <p></p>
* <ul>
* <li>NumberFormatException0</li>
* <li>ID-1IllegalStateException</li>
* </ul>
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
@ -65,41 +114,143 @@ public class Note {
return noteId;
}
/**
* <p>Note</p>
* <p></p>
* <ul>
* <li>{@link #mNoteDiffValues}ContentValues</li>
* <li>{@link #mNoteData}NoteData</li>
* </ul>
*/
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
}
/**
* <p></p>
* <p></p>
*
* @param key
* @param value
*
* <p></p>
* <ul>
* <li>{@link NoteColumns#LOCAL_MODIFIED}1</li>
* <li>{@link NoteColumns#MODIFIED_DATE}</li>
* </ul>
*/
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* <p></p>
* <p>{@link NoteData}</p>
*
* @param key
* @param value
*/
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
/**
* <p>ID</p>
* <p>{@link NoteData}ID</p>
*
* @param id ID
*/
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
/**
* <p>ID</p>
* <p>{@link NoteData}ID</p>
*
* @return ID
*/
public long getTextDataId() {
return mNoteData.mTextDataId;
}
/**
* <p>ID</p>
* <p>{@link NoteData}ID</p>
*
* @param id ID
*/
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
/**
* <p></p>
* <p>{@link NoteData}</p>
*
* @param key
* @param value
*/
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
/**
* <p></p>
* <p></p>
*
* @return truefalse
*
* <p></p>
* <ul>
* <li>{@link #mNoteDiffValues}0</li>
* <li>{@link NoteData#isLocalModified()}</li>
* </ul>
*/
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
* <p>ContentResolver</p>
* <p></p>
*
* @param context ContentResolver
* @param noteId ID
* @return truefalse
* @throws IllegalArgumentException noteId<=0
*
* <p></p>
* <ol>
* <li>noteId</li>
* <li>true</li>
* <li>ContentResolver</li>
* <li>ContentResolver</li>
* <li></li>
* </ol>
*
* <p></p>
* <ul>
* <li>{@link #mNoteDiffValues}ContentResolver.update()</li>
* <li>{@link NoteData#pushIntoContentResolver(Context, long)}</li>
* </ul>
*
* <p></p>
* <ul>
* <li></li>
* <li>false</li>
* </ul>
*
* <p></p>
* <ul>
* <li>{@link Context#getContentResolver()}ContentResolver</li>
* <li>{@link android.content.ContentResolver#update(Uri, ContentValues, String, String[])}</li>
* <li>{@link NoteData#pushIntoContentResolver(Context, long)}</li>
* </ul>
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -130,17 +281,65 @@ public class Note {
return true;
}
/**
* <p></p>
* <p></p>
* <p>{@link Note}</p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li>ContentResolver</li>
* </ul>
* <p></p>
* <ul>
* <li>{@link Note}</li>
* <li>使{@link ContentValues}</li>
* <li>{@link ContentProviderOperation}</li>
* </ul>
*/
private class NoteData {
/**
* <p>ID</p>
* <p></p>
* <p>0</p>
*/
private long mTextDataId;
/**
* <p></p>
* <p></p>
*/
private ContentValues mTextDataValues;
/**
* <p>ID</p>
* <p></p>
* <p>0</p>
*/
private long mCallDataId;
/**
* <p></p>
* <p></p>
*/
private ContentValues mCallDataValues;
/**
* <p></p>
* <p>NoteData</p>
*/
private static final String TAG = "NoteData";
/**
* <p>NoteData</p>
* <p>ID</p>
* <ul>
* <li>{@link #mTextDataValues}ContentValues</li>
* <li>{@link #mCallDataValues}ContentValues</li>
* <li>{@link #mTextDataId}{@link #mCallDataId}0</li>
* </ul>
*/
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
@ -148,10 +347,29 @@ public class Note {
mCallDataId = 0;
}
/**
* <p></p>
* <p></p>
*
* @return truefalse
*
* <p></p>
* <ul>
* <li>{@link #mTextDataValues}0</li>
* <li>{@link #mCallDataValues}0</li>
* </ul>
*/
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
/**
* <p>ID</p>
* <p></p>
*
* @param id ID
* @throws IllegalArgumentException id<=0
*/
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +377,13 @@ public class Note {
mTextDataId = id;
}
/**
* <p>ID</p>
* <p></p>
*
* @param id ID
* @throws IllegalArgumentException id<=0
*/
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,18 +391,82 @@ public class Note {
mCallDataId = id;
}
/**
* <p></p>
* <p></p>
*
* @param key
* @param value
*
* <p></p>
* <ul>
* <li>{@link Note}{@link Note#mNoteDiffValues}{@link NoteColumns#LOCAL_MODIFIED}1</li>
* <li>{@link Note}{@link Note#mNoteDiffValues}{@link NoteColumns#MODIFIED_DATE}</li>
* </ul>
*/
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* <p></p>
* <p></p>
*
* @param key
* @param value
*
* <p></p>
* <ul>
* <li>{@link Note}{@link Note#mNoteDiffValues}{@link NoteColumns#LOCAL_MODIFIED}1</li>
* <li>{@link Note}{@link Note#mNoteDiffValues}{@link NoteColumns#MODIFIED_DATE}</li>
* </ul>
*/
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* <p>ContentResolver</p>
* <p></p>
*
* @param context ContentResolver
* @param noteId ID
* @return Urinull
* @throws IllegalArgumentException noteId<=0
*
* <p></p>
* <ol>
* <li>noteId</li>
* <li></li>
* <ul>
* <li>{@link #mTextDataId}0</li>
* <li></li>
* </ul>
* <li></li>
* <ul>
* <li>{@link #mCallDataId}0</li>
* <li></li>
* </ul>
* <li>ContentProviderOperation</li>
* </ol>
*
* <p></p>
* <ul>
* <li>{@link Context#getContentResolver()}ContentResolver</li>
* <li>{@link android.content.ContentResolver#insert(Uri, ContentValues)}</li>
* <li>{@link android.content.ContentResolver#applyBatch(String, ArrayList)}</li>
* </ul>
*
* <p></p>
* <ul>
* <li>null</li>
* <li>RemoteExceptionOperationApplicationExceptionnull</li>
* </ul>
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety

@ -32,36 +32,116 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* <p></p>
* <p>Note便</p>
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* <p></p>
* <ul>
* <li>{@link Note}</li>
* <li>{@link Context}</li>
* <li>使{@link NotesProvider}</li>
* <li>{@link NoteSettingChangedListener}</li>
* </ul>
*/
public class WorkingNote {
// Note for the working note
/**
* <p></p>
* <p></p>
*/
private Note mNote;
// Note Id
/**
* <p></p>
* <p></p>
* <p>0</p>
*/
private long mNoteId;
// Note content
/**
* <p></p>
* <p></p>
*/
private String mContent;
// Note mode
/**
* <p></p>
* <p></p>
*/
private int mMode;
/**
* <p></p>
* <p></p>
* <p>0</p>
*/
private long mAlertDate;
/**
* <p></p>
* <p></p>
*/
private long mModifiedDate;
/**
* <p>ID</p>
* <p>使</p>
*/
private int mBgColorId;
/**
* <p>ID</p>
* <p></p>
* <p>{@link AppWidgetManager#INVALID_APPWIDGET_ID}</p>
*/
private int mWidgetId;
/**
* <p></p>
* <p></p>
* <p>{@link Notes#TYPE_WIDGET_INVALIDE}</p>
*/
private int mWidgetType;
/**
* <p>ID</p>
* <p></p>
*/
private long mFolderId;
/**
* <p></p>
* <p>访</p>
*/
private Context mContext;
/**
* <p></p>
* <p>WorkingNote</p>
*/
private static final String TAG = "WorkingNote";
/**
* <p></p>
* <p></p>
*/
private boolean mIsDeleted;
/**
* <p></p>
* <p></p>
*/
private NoteSettingChangedListener mNoteSettingStatusListener;
/**
* <p></p>
* <p>Notes.CONTENT_DATA_URI</p>
*/
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,6 +152,10 @@ public class WorkingNote {
DataColumns.DATA4,
};
/**
* <p></p>
* <p>Notes.CONTENT_NOTE_URI</p>
*/
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -81,27 +165,73 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE
};
/**
* <p>DATA_PROJECTIONID</p>
*/
private static final int DATA_ID_COLUMN = 0;
/**
* <p>DATA_PROJECTIONCONTENT</p>
*/
private static final int DATA_CONTENT_COLUMN = 1;
/**
* <p>DATA_PROJECTIONMIME_TYPE</p>
*/
private static final int DATA_MIME_TYPE_COLUMN = 2;
/**
* <p>DATA_PROJECTIONDATA1</p>
*/
private static final int DATA_MODE_COLUMN = 3;
/**
* <p>NOTE_PROJECTIONPARENT_ID</p>
*/
private static final int NOTE_PARENT_ID_COLUMN = 0;
/**
* <p>NOTE_PROJECTIONALERTED_DATE</p>
*/
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
/**
* <p>NOTE_PROJECTIONBG_COLOR_ID</p>
*/
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
/**
* <p>NOTE_PROJECTIONWIDGET_ID</p>
*/
private static final int NOTE_WIDGET_ID_COLUMN = 3;
/**
* <p>NOTE_PROJECTIONWIDGET_TYPE</p>
*/
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
/**
* <p>NOTE_PROJECTIONMODIFIED_DATE</p>
*/
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
/**
* <p></p>
* <p></p>
*
* @param context 访
* @param folderId ID
*
* <p></p>
* <ul>
* <li>0</li>
* <li></li>
* <li>ID0</li>
* <li>false</li>
* <li>0</li>
* <li></li>
* </ul>
*/
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -114,7 +244,21 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
// Existing note construct
/**
* <p></p>
* <p></p>
*
* @param context 访
* @param noteId ID
* @param folderId ID
*
* <p></p>
* <ul>
* <li></li>
* <li>{@link #loadNote()}</li>
* <li>{@link #loadNoteData()}</li>
* </ul>
*/
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
@ -124,6 +268,35 @@ public class WorkingNote {
loadNote();
}
/**
* <p></p>
* <p></p>
*
* <p></p>
* <ol>
* <li>ContentResolver{@link Notes#CONTENT_NOTE_URI}</li>
* <li></li>
* <li>Cursor</li>
* <li></li>
* <li>{@link #loadNoteData()}</li>
* </ol>
*
* <p></p>
* <ul>
* <li>ID</li>
* <li>ID</li>
* <li>ID</li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
*
* <p></p>
* <ul>
* <li></li>
* <li>IllegalArgumentException</li>
* </ul>
*/
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
@ -146,6 +319,30 @@ public class WorkingNote {
loadNoteData();
}
/**
* <p></p>
* <p></p>
*
* <p></p>
* <ol>
* <li>ContentResolver{@link Notes#CONTENT_DATA_URI}</li>
* <li></li>
* <li></li>
* <ul>
* <li>ID</li>
* <li>ID</li>
* <li></li>
* </ul>
* <li>Cursor</li>
* <li></li>
* </ol>
*
* <p></p>
* <ul>
* <li></li>
* <li>IllegalArgumentException</li>
* </ul>
*/
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
@ -174,6 +371,27 @@ public class WorkingNote {
}
}
/**
* <p></p>
* <p></p>
*
* @param context 访
* @param folderId ID
* @param widgetId ID
* @param widgetType
* @param defaultBgColorId ID
*
* @return
*
* <p></p>
* <ol>
* <li>WorkingNote</li>
* <li></li>
* <li>ID</li>
* <li></li>
* <li></li>
* </ol>
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
@ -183,10 +401,50 @@ public class WorkingNote {
return note;
}
/**
* <p></p>
* <p>ID</p>
*
* @param context 访
* @param id ID
*
* @return
*
* <p></p>
* <ul>
* <li>WorkingNote</li>
* <li>{@link #loadNote()}</li>
* <li>loadNote(){@link #loadNoteData()}</li>
* </ul>
*/
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
/**
* <p></p>
* <p></p>
*
* @return
*
* <p></p>
* <ol>
* <li>{@link #isWorthSaving()}</li>
* <li></li>
* <ul>
* <li>{@link Note#getNewNoteId(Context, long)}ID</li>
* <li>false</li>
* </ul>
* <li>{@link Note#syncNote(Context, long)}</li>
* <li></li>
* <li></li>
* </ol>
*
* <p>线</p>
* <ul>
* <li>使synchronized线</li>
* </ul>
*/
public synchronized boolean saveNote() {
if (isWorthSaving()) {
if (!existInDatabase()) {
@ -212,10 +470,42 @@ public class WorkingNote {
}
}
/**
* <p></p>
* <p>ID</p>
*
* @return truefalse
*
* <p></p>
* <ul>
* <li>ID0</li>
* <li>ID0</li>
* </ul>
*/
public boolean existInDatabase() {
return mNoteId > 0;
}
/**
* <p></p>
* <p></p>
*
* @return truefalse
*
* <p></p>
* <ul>
* <li> </li>
* <li> </li>
* <li> </li>
* <li> </li>
* </ul>
*
* <p></p>
* <ul>
* <li></li>
* <li></li>
* </ul>
*/
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +515,33 @@ public class WorkingNote {
}
}
/**
* <p></p>
* <p></p>
*
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
/**
* <p></p>
* <p></p>
*
* @param date
* @param set truefalse
*
* <p></p>
* <ol>
* <li></li>
* <ul>
* <li></li>
* <li>{@link Note#setNoteValue(String, String)}</li>
* </ul>
* <li></li>
* </ol>
*/
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
@ -239,6 +552,18 @@ public class WorkingNote {
}
}
/**
* <p></p>
* <p></p>
*
* @param mark truefalse
*
* <p></p>
* <ol>
* <li></li>
* <li></li>
* </ol>
*/
public void markDeleted(boolean mark) {
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
@ -288,56 +613,126 @@ public class WorkingNote {
}
}
/**
* <p></p>
* <p></p>
*
* @param phoneNumber
* @param callDate
*
* <p></p>
* <ol>
* <li></li>
* <li></li>
* <li></li>
* </ol>
*/
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
/**
* <p></p>
* <p></p>
*
* @return truefalse
*
* <p></p>
* <ul>
* <li>0</li>
* <li>0</li>
* </ul>
*/
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
/**
* <p></p>
* @return
*/
public String getContent() {
return mContent;
}
/**
* <p></p>
* @return
*/
public long getAlertDate() {
return mAlertDate;
}
/**
* <p></p>
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* <p>ID</p>
* @return ID
*/
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
/**
* <p>ID</p>
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* <p>ID</p>
* @return ID
*/
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
/**
* <p></p>
* @return 01
*/
public int getCheckListMode() {
return mMode;
}
/**
* <p>ID</p>
* @return
*/
public long getNoteId() {
return mNoteId;
}
/**
* <p>ID</p>
* @return ID
*/
public long getFolderId() {
return mFolderId;
}
/**
* <p>ID</p>
* @return ID{@link AppWidgetManager#INVALID_APPWIDGET_ID}
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* <p></p>
* @return {@link Notes#TYPE_WIDGET_INVALIDE}
*/
public int getWidgetType() {
return mWidgetType;
}

@ -36,11 +36,20 @@ import java.io.IOException;
import java.io.PrintStream;
/**
* 便便SD便便
* BackupUtils
*/
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
private static final String TAG = "BackupUtils"; // 日志标签
// 单例实例
private static BackupUtils sInstance;
/**
*
* @param context 访Context访便SDAndroid
* @return BackupUtilsBackupUtils
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
@ -49,251 +58,326 @@ public class BackupUtils {
}
/**
* Following states are signs to represents backup or restore
* status
* /
*/
// Currently, the sdcard is not mounted
// SD卡未挂载无法读写
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
// 备份文件不存在(恢复时使用)
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
// 数据格式损坏(可能被其他程序修改)
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
// 运行时异常导致操作失败
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
// 备份/恢复成功
public static final int STATE_SUCCESS = 4;
// 文本导出的具体实现类
private TextExport mTextExport;
/**
*
* @param context
*/
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
/**
* SD
* @return truefalse
*/
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());// 返回存储状态
}
/**
*
* @return STATE_SUCCESSSTATE_SD_CARD_UNMOUONTED
*/
public int exportToText() {
return mTextExport.exportToText();
}
/**
*
* @return notes_20240520.txt
*/
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
/**
*
* @return /sdcard/NotesBackup/
*/
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
/**
*
*/
private static class TextExport {
// 查询便签时需要的字段投影(只查询需要的列,优化性能)
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
NoteColumns.ID, // 便签/文件夹ID
NoteColumns.MODIFIED_DATE,// 最后修改时间
NoteColumns.SNIPPET, // 文件夹名或便签摘要
NoteColumns.TYPE // 类型(文件夹/便签)
};
// 字段索引常量用于从Cursor中快速获取对应值
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,
DataColumns.DATA1,
DataColumns.CONTENT, // 内容(文本/位置)
DataColumns.MIME_TYPE, // 类型(普通便签/通话便签)
DataColumns.DATA1, // 通话便签的通话时间getFormat函数定义的
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA3, // 通话便签的电话号码getFormat函数定义的
DataColumns.DATA4,
};
/*
* private String getFormat(int id) {
return TEXT_FORMAT[id];
}*/
// 数据字段索引常量
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中getFormat函数定义的
private static final int DATA_COLUMN_PHONE_NUMBER = 4; // 电话号码在DATA3中getFormat函数定义的
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 文本格式化模板(从资源文件读取,如文件夹名、时间、内容的格式)
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 static final int FORMAT_FOLDER_NAME = 0; // 文件夹名格式
private static final int FORMAT_NOTE_DATE = 1; // 便签时间格式
private static final int FORMAT_NOTE_CONTENT = 2; // 便签内容格式
private Context mContext;
private String mFileName;
private String mFileDirectory;
private Context mContext; // 上下文
private String mFileName; // 导出的文件名
private String mFileDirectory; // 导出的文件目录
/**
*
* @param context
*/
public TextExport(Context context) {
// 从资源文件读取格式化模板如strings.xml中的format_for_exported_note数组
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
}
/**
*
* @param id FORMAT_FOLDER_NAME
* @return
*/
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
/**
* Export the folder identified by folder id to text
* 便
* @param folderId ID
* @param ps
*/
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
}, null);
// 查询该文件夹下的所有便签通过parent_id关联
Cursor notesCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, // 便签数据库的URI
NOTE_PROJECTION, // 要查询的字段
NoteColumns.PARENT_ID + "=?", // 查询条件parent_id=folderId
new String[] {folderId}, // 条件参数
null); // 排序方式(默认)
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
if (notesCursor.moveToFirst()) { // 遍历所有便签
do {
// Print note's last modified date
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 打印便签的最后修改时间(格式化显示)
ps.println(String.format(
getFormat(FORMAT_NOTE_DATE),
DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), // 时间格式(月日时分)
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)
)
));
// 导出该便签的详细内容
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
}
notesCursor.close();
notesCursor.close(); // 关闭游标,释放资源
}
}
/**
* Export note identified by id to a print stream
* 便
* 便便
* @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 + "=?", new String[] {
noteId
}, null);
// 查询该便签的详细数据(如文本内容、通话记录信息)
Cursor dataCursor = mContext.getContentResolver().query(
Notes.CONTENT_DATA_URI, // 便签数据的URI
DATA_PROJECTION, // 要查询的字段
DataColumns.NOTE_ID + "=?", // 查询条件note_id=noteId
new String[] {noteId}, // 条件参数
null); // 排序方式
if (dataCursor != null) {
if (dataCursor.moveToFirst()) {
if (dataCursor.moveToFirst()) { // 遍历便签的所有数据
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
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));
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber));
}
// Print call date
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
// 打印通话时间(格式化)
ps.println(String.format(
getFormat(FORMAT_NOTE_CONTENT),
DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
callDate
)
));
// 打印位置信息(非空时)
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
} 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));
if (!TextUtils.isEmpty(content)) { // 打印文本内容
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
}
}
} while (dataCursor.moveToNext());
}
dataCursor.close();
dataCursor.close(); // 关闭游标,释放资源
}
// print a line separator between note
// 便签之间添加分隔符(换行)
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
});
ps.write(new byte[] {Character.LINE_SEPARATOR, Character.LINE_SEPARATOR});
} catch (IOException e) {
Log.e(TAG, e.toString());
Log.e(TAG, "写入分隔符失败:" + e.toString());
}
}
/**
* Note will be exported as text which is user readable
* SD
* @return STATE_SUCCESS
*/
public int exportToText() {
// 检查SD卡是否可用
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
Log.d(TAG, "SD卡未挂载无法导出");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取指向备份文件的输出流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
Log.e(TAG, "创建输出流失败");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 1. 导出所有文件夹及其包含的便签(排除回收站,包含通话记录文件夹)
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
// 查询条件:文件夹类型且不在回收站,或通话记录文件夹
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER,
null,
null);
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
if (folderCursor.moveToFirst()) { // 遍历所有文件夹
do {
// Print folder's name
// 获取文件夹名(通话记录文件夹使用固定名称)
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
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);
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());
}
folderCursor.close();
folderCursor.close(); // 关闭游标
}
// Export notes in root's folder
// 2. 导出根目录下的便签无文件夹归属的便签parent_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);
NoteColumns.TYPE + "=" + Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + "=0",
null,
null);
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
if (noteCursor.moveToFirst()) { // 遍历根目录便签
do {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 打印修改时间
ps.println(String.format(
getFormat(FORMAT_NOTE_DATE),
DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)
)
));
// 导出便签内容
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
}
noteCursor.close();
noteCursor.close(); // 关闭游标
}
ps.close();
return STATE_SUCCESS;
ps.close(); // 关闭输出流
return STATE_SUCCESS; // 导出成功
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
* SDPrintStream
* @return PrintStreamnull
*/
private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
// 在SD卡上生成备份文件路径和名称从资源获取包含当前日期
File file = generateFileMountedOnSDcard(
mContext,
R.string.file_path, // 目录路径(如/sdcard/NotesBackup/
R.string.file_name_txt_format // 文件名格式如notes_%s.txt%s为日期
);
if (file == null) {
Log.e(TAG, "create file to exported failed");
Log.e(TAG, "创建备份文件失败");
return null;
}
// 记录文件名和目录
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
// 创建输出流
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(file);
@ -310,35 +394,43 @@ public class BackupUtils {
}
/**
* Generate the text file to store imported data
* 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) {
StringBuilder sb = new StringBuilder();
// 拼接路径SD卡根目录 + 应用备份目录(如/sdcard/NotesBackup/
sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));
File filedir = new File(sb.toString());
// 拼接文件名:目录 + 格式化名称含当前日期如notes_20240520.txt
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
DateFormat.format(
context.getString(R.string.format_date_ymd), // 日期格式(年月日)
System.currentTimeMillis()
)
));
File file = new File(sb.toString());
// 创建目录和文件
try {
if (!filedir.exists()) {
filedir.mkdir();
filedir.mkdir(); // 目录不存在则创建
}
if (!file.exists()) {
file.createNewFile();
file.createNewFile(); // 文件不存在则创建
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
e.printStackTrace(); // 权限不足
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace(); // 创建文件失败
}
return null;
}
}
}

@ -35,88 +35,127 @@ import java.util.ArrayList;
import java.util.HashSet;
/**
* 便
* ContentProviderUI
*/
public class DataUtils {
public static final String TAG = "DataUtils";
/**
* 便
* @param resolver
* @param ids 便/ID
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
if (ids == null) {
Log.d(TAG, "the ids is null");
Log.d(TAG, "待删除的ID集合为null");
return true;
}
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
Log.d(TAG, "待删除的ID集合为空");
return true;
}
// 创建批量删除操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
// 禁止删除系统根目录
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
Log.e(TAG, "不能删除系统根目录文件夹");
continue;
}
// 构建删除操作根据ID删除便签
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, "delete notes failed, ids:" + ids.toString());
Log.d(TAG, "删除失败ID集合:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("远程异常: %s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("操作应用异常: %s: %s", e.toString(), e.getMessage()));
}
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();
values.put(NoteColumns.PARENT_ID, desFolderId);
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, desFolderId); // 更新父目录ID为目标文件夹
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 记录原始文件夹ID
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 truefalse
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
long folderId) {
if (ids == null) {
Log.d(TAG, "the ids is null");
Log.d(TAG, "待移动的ID集合为null");
return true;
}
// 创建批量更新操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
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);
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, "delete notes failed, ids:" + ids.toString());
Log.d(TAG, "移动失败ID集合:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("远程异常: %s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
Log.e(TAG, String.format("操作应用异常: %s: %s", e.toString(), e.getMessage()));
}
return false;
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*
* @param resolver
* @return
*/
public static int getUserFolderCount(ContentResolver resolver) {
// 查询非系统的文件夹且不在垃圾站中的文件夹数量
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
new String[] { "COUNT(*)" }, // 统计数量
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
@ -127,7 +166,7 @@ public class DataUtils {
try {
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "get folder count failed:" + e.toString());
Log.e(TAG, "获取文件夹数量失败:" + e.toString());
} finally {
cursor.close();
}
@ -136,6 +175,13 @@ public class DataUtils {
return count;
}
/**
* 便
* @param resolver
* @param noteId 便ID
* @param type 便Notes.TYPE_NOTE
* @return truefalse
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
@ -145,62 +191,78 @@ public class DataUtils {
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
exist = cursor.getCount() > 0; // 游标有数据则存在
cursor.close();
}
return exist;
}
/**
* 便便
* @param resolver
* @param noteId 便ID
* @return truefalse
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
exist = cursor.getCount() > 0;
cursor.close();
}
return exist;
}
/**
* 便
* @param resolver
* @param dataId ID
* @return truefalse
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
exist = cursor.getCount() > 0;
cursor.close();
}
return exist;
}
/**
*
* @param resolver
* @param name
* @return truefalse
*/
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 + "=?",
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?", // SNIPPET字段存储文件夹名称
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
if(cursor.getCount() > 0) {
exist = true;
}
exist = cursor.getCount() > 0;
cursor.close();
}
return exist;
}
/**
* 便
* @param resolver
* @param folderId ID
* @return widgetIdwidgetType
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, // 查询小部件ID和类型
NoteColumns.PARENT_ID + "=?", // 筛选指定文件夹下的便签
new String[] { String.valueOf(folderId) },
null);
@ -224,10 +286,16 @@ public class DataUtils {
return set;
}
/**
* 便ID便
* @param resolver
* @param noteId 便ID
* @return
*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { CallNote.PHONE_NUMBER }, // 查询电话号码字段
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", // 筛选通话便签数据
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);
@ -235,7 +303,7 @@ public class DataUtils {
try {
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
Log.e(TAG, "获取电话号码失败 " + e.toString());
} finally {
cursor.close();
}
@ -243,11 +311,18 @@ public class DataUtils {
return "";
}
/**
* 便ID
* @param resolver
* @param phoneNumber
* @param callDate
* @return 便ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
new String [] { CallNote.NOTE_ID }, // 查询关联的便签ID
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 },
null);
@ -256,7 +331,7 @@ public class DataUtils {
try {
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
Log.e(TAG, "获取通话便签ID失败 " + e.toString());
}
}
cursor.close();
@ -264,9 +339,15 @@ public class DataUtils {
return 0;
}
/**
* 便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 },
new String [] { NoteColumns.SNIPPET }, // 查询摘要字段
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
@ -279,17 +360,22 @@ public class DataUtils {
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
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');
snippet = snippet.trim(); // 去除首尾空格
int index = snippet.indexOf('\n'); // 查找第一个换行符
if (index != -1) {
snippet = snippet.substring(0, index);
snippet = snippet.substring(0, index); // 截取首行内容
}
}
return snippet;
}
}
}

@ -13,101 +13,157 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.tool;
/**
* GTask便GTaskGoogle Tasks使
* JSON
*/
public class GTaskStringUtils {
// ========================== GTask JSON动作相关键名 ==========================
/** JSON中动作ID的键名用于标识同步操作的唯一ID如创建/更新任务的动作ID */
public final static String GTASK_JSON_ACTION_ID = "action_id";
/** JSON中动作列表的键名用于包装多个同步动作如批量创建/更新任务) */
public final static String GTASK_JSON_ACTION_LIST = "action_list";
/** JSON中动作类型的键名用于标识当前动作是创建/更新/移动等类型 */
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
/** 动作类型创建操作用于标识在GTask中创建新任务或文件夹 */
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
/** 动作类型获取全部数据用于请求GTask中的所有任务和文件夹数据 */
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
/** 动作类型:移动操作,用于标识将任务/文件夹移动到新位置 */
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
/** 动作类型更新操作用于标识修改GTask中已有的任务或文件夹 */
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// ========================== GTask JSON实体属性相关键名 ==========================
/** JSON中创建者ID的键名标识任务/文件夹的创建者(小米便签中暂用"null" */
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
/** JSON中子实体的键名用于存储子任务信息 */
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
/** JSON中客户端版本的键名标识当前同步客户端的版本 */
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
/** JSON中任务完成状态的键名标识任务是否已完成true/false */
public final static String GTASK_JSON_COMPLETED = "completed";
/** JSON中当前列表ID的键名标识当前操作的任务列表ID */
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
/** JSON中默认列表ID的键名标识GTask中的默认任务列表ID */
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
/** JSON中删除状态的键名标识任务/文件夹是否已删除true/false */
public final static String GTASK_JSON_DELETED = "deleted";
/** JSON中目标列表的键名用于移动操作时指定目标列表 */
public final static String GTASK_JSON_DEST_LIST = "dest_list";
/** JSON中目标父节点的键名用于移动操作时指定目标父节点 */
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
/** JSON中目标父节点类型的键名标识目标父节点是任务TASK还是文件夹GROUP */
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
/** JSON中实体增量的键名用于存储任务/文件夹的修改内容(如名称、状态等) */
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
/** JSON中实体类型的键名标识当前实体是任务TASK还是文件夹GROUP */
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
/** JSON中获取已删除实体的键名用于请求GTask中已删除的任务/文件夹 */
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
/** JSON中实体ID的键名标识任务/文件夹在GTask中的唯一ID */
public final static String GTASK_JSON_ID = "id";
/** JSON中排序索引的键名标识任务/文件夹在列表中的位置(用于排序) */
public final static String GTASK_JSON_INDEX = "index";
/** JSON中最后修改时间的键名标识任务/文件夹的最近修改时间(用于同步冲突判断) */
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
/** JSON中最新同步点的键名标识上次同步的时间点用于增量同步 */
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
/** JSON中列表ID的键名标识当前任务所属的列表ID */
public final static String GTASK_JSON_LIST_ID = "list_id";
/** JSON中列表集合的键名用于存储多个任务列表数据 */
public final static String GTASK_JSON_LISTS = "lists";
/** JSON中名称的键名标识任务/文件夹的名称 */
public final static String GTASK_JSON_NAME = "name";
/** JSON中新ID的键名用于标识创建操作后GTask返回的新实体ID */
public final static String GTASK_JSON_NEW_ID = "new_id";
/** JSON中备注的键名标识任务的备注内容 */
public final static String GTASK_JSON_NOTES = "notes";
/** JSON中父节点ID的键名标识当前实体的父节点ID用于层级结构 */
public final static String GTASK_JSON_PARENT_ID = "parent_id";
/** JSON中前序兄弟节点ID的键名标识当前实体的前一个兄弟节点用于排序 */
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
/** JSON中结果集合的键名用于存储GTask返回的同步结果 */
public final static String GTASK_JSON_RESULTS = "results";
/** JSON中源列表的键名用于移动操作时指定源列表 */
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
/** JSON中任务集合的键名用于存储多个任务数据 */
public final static String GTASK_JSON_TASKS = "tasks";
/** JSON中类型的键名与ENTITY_TYPE配合使用 */
public final static String GTASK_JSON_TYPE = "type";
/** 实体类型文件夹分组标识当前实体是GTask中的文件夹 */
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
/** 实体类型任务标识当前实体是GTask中的任务 */
public final static String GTASK_JSON_TYPE_TASK = "TASK";
/** JSON中用户信息的键名标识当前同步的用户 */
public final static String GTASK_JSON_USER = "user";
// ========================== 小米便签专属文件夹标识 ==========================
/** 小米便签文件夹前缀用于在GTask中区分小米便签创建的文件夹避免与其他应用冲突 */
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
/** 小米便签默认文件夹名称,拼接前缀后为"[MIUI_Notes]Default" */
public final static String FOLDER_DEFAULT = "Default";
/** 小米便签通话记录文件夹名称,拼接前缀后为"[MIUI_Notes]Call_Note" */
public final static String FOLDER_CALL_NOTE = "Call_Note";
/** 小米便签元数据文件夹名称用于存储便签的额外信息如本地ID、附件信息等 */
public final static String FOLDER_META = "METADATA";
// ========================== 元数据相关键名 ==========================
/** 元数据中GTask ID的键名用于存储实体在GTask中的ID */
public final static String META_HEAD_GTASK_ID = "meta_gid";
/** 元数据中便签信息的键名用于存储便签的核心信息如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";
}
}

@ -22,151 +22,238 @@ 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 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 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 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 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
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
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 // 红色标题栏
};
/**
* 便
* @param id YELLOWBLUE
* @return ID
*/
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
/**
* 便
* @param id YELLOWBLUE
* @return ID
*/
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
/**
* ID
*
* @param context
* @return
*/
public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 随机选择背景颜色0到背景资源数量-1之间
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 返回默认背景色
return BG_DEFAULT_COLOR;
}
}
/**
* 便
*
*/
public static class NoteItemBgResources {
// 列表首项背景资源数组
private final static int [] BG_FIRST_RESOURCES = new int [] {
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
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
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,
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
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 // 红色唯一项
};
/**
*
* @param id
* @return ID
*/
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
/**
*
* @param id
* @return ID
*/
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
/**
*
* @param id
* @return ID
*/
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
/**
*
* @param id
* @return ID
*/
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
/**
*
* @return ID
*/
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
/**
* Widget
* Widget
*/
public static class WidgetBgResources {
// 2x尺寸Widget背景资源数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
R.drawable.widget_2x_yellow, // 2x黄色Widget
R.drawable.widget_2x_blue, // 2x蓝色Widget
R.drawable.widget_2x_white, // 2x白色Widget
R.drawable.widget_2x_green, // 2x绿色Widget
R.drawable.widget_2x_red, // 2x红色Widget
};
/**
* 2xWidget
* @param id
* @return 2x WidgetID
*/
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 4x尺寸Widget背景资源数组
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
R.drawable.widget_4x_yellow, // 4x黄色Widget
R.drawable.widget_4x_blue, // 4x蓝色Widget
R.drawable.widget_4x_white, // 4x白色Widget
R.drawable.widget_4x_green, // 4x绿色Widget
R.drawable.widget_4x_red // 4x红色Widget
};
/**
* 4xWidget
* @param id
* @return 4x WidgetID
*/
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
R.style.TextAppearanceNormal, // 小字体样式
R.style.TextAppearanceMedium, // 中字体样式
R.style.TextAppearanceLarge, // 大字体样式
R.style.TextAppearanceSuper // 超大字体样式
};
/**
*
* @param id TEXT_SMALLTEXT_MEDIUM
* @return IDid
*/
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
* ID
* id
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
@ -174,8 +261,12 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id];
}
/**
*
* @return
*/
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}
}

@ -40,20 +40,31 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException;
/**
* 便便
*
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
// 提醒的便签ID
private long mNoteId;
// 便签内容摘要(用于提醒对话框展示)
private String mSnippet;
// 摘要最大显示长度(超出部分用省略号处理)
private static final int SNIPPET_PREW_MAX_LEN = 60;
// 媒体播放器,用于播放闹钟声音
MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 去除标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
final Window win = getWindow();
// 允许在锁屏时显示窗口
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 如果屏幕处于关闭状态,添加额外窗口标志:保持屏幕常亮、点亮屏幕、允许锁屏时显示、布局适配
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
@ -61,11 +72,15 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
}
// 获取启动当前Activity的Intent由AlarmReceiver传递
Intent intent = getIntent();
try {
// 从Intent的Data中解析便签IDData格式为content://.../notes/{id}取路径的第2段
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 通过便签ID获取内容摘要用于提醒展示
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 处理摘要长度:超过最大长度时截断并添加省略提示
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
@ -74,85 +89,115 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
return;
}
// 初始化媒体播放器
mPlayer = new MediaPlayer();
// 检查便签是否存在且可见(未被删除)
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 显示提醒对话框
showActionDialog();
// 播放闹钟声音
playAlarmSound();
} else {
// 便签不存在则直接结束活动
finish();
}
}
/**
*
* @return truefalse
*/
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
/**
*
*/
private void playAlarmSound() {
// 获取系统默认闹钟铃声的Uri
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取系统静音模式影响的音频流(判断闹钟是否被静音)
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 设置媒体播放器的音频流类型:若闹钟流被静音模式影响,则使用该流;否则默认使用闹钟流
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
// 设置铃声数据源并准备播放
mPlayer.setDataSource(this, url);
mPlayer.prepare();
// 设置为循环播放(直到用户操作停止)
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
/**
* 便
*/
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
// 设置对话框标题为应用名称(小米便签)
dialog.setTitle(R.string.app_name);
// 显示便签摘要内容
dialog.setMessage(mSnippet);
// 确定按钮:关闭提醒(默认行为)
dialog.setPositiveButton(R.string.notealert_ok, this);
// 若屏幕亮着,添加“进入”按钮(跳转到便签编辑页)
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
// 显示对话框,并设置消失监听(用于停止铃声)
dialog.show().setOnDismissListener(this);
}
/**
*
* @param dialog
* @param which BUTTON_POSITIVE/BUTTON_NEGATIVE
*/
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 点击“进入”按钮:跳转到便签编辑页查看完整内容
case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
intent.setAction(Intent.ACTION_VIEW); // 动作:查看便签
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递便签ID
startActivity(intent);
break;
// 点击“确定”按钮:默认不做额外操作,对话框消失后会停止铃声并结束活动
default:
break;
}
}
/**
*
* @param dialog
*/
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
}
/**
*
*/
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放资源
mPlayer = null;
}
}
}
}

@ -27,39 +27,74 @@ import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
* 便
* 便
*/
public class AlarmInitReceiver extends BroadcastReceiver {
/**
* 便ID
*
*/
private static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE // 提醒时间戳
};
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;
// 字段索引常量用于快速访问Cursor中的数据
private static final int COLUMN_ID = 0; // 便签ID在投影中的索引
private static final int COLUMN_ALERTED_DATE = 1; // 提醒时间在投影中的索引
/**
* 广
* 便AlarmManager
* @param context
* @param intent 广
*/
@Override
public void onReceive(Context context, Intent intent) {
// 获取当前系统时间,用于筛选未过期的提醒
long currentDate = System.currentTimeMillis();
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
// 查询数据库中所有未过期的便签提醒
// 条件:提醒时间 > 当前时间 且 便签类型为普通便签TYPE_NOTE
Cursor c = context.getContentResolver().query(
Notes.CONTENT_NOTE_URI, // 查询的内容URI指向便签表
PROJECTION, // 需要查询的字段
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) },
null);
new String[] { String.valueOf(currentDate) }, // 筛选条件参数(当前时间)
null // 排序方式(无需排序)
);
if (c != null) {
// 遍历查询结果,为每个未过期的提醒注册闹钟
if (c.moveToFirst()) {
do {
// 获取便签的提醒时间
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建触发提醒时的意图指向AlarmReceiver
Intent sender = new Intent(context, AlarmReceiver.class);
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 为意图附加便签ID便于后续定位具体便签
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(COLUMN_ID)));
// 创建延迟执行的PendingIntent用于触发提醒
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, sender, 0);
// 获取AlarmManager服务用于设置系统闹钟
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 注册闹钟在指定时间alertDate唤醒设备并发送广播
// RTC_WAKEUP模式确保在设备休眠时也能触发
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
} while (c.moveToNext()); // 继续处理下一个便签
}
// 关闭Cursor释放资源
c.close();
}
}
}
}

@ -20,11 +20,27 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* 便广广
* 便
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
* @param context Activity
* @param intent 便便ID
*/
@Override
public void onReceive(Context context, Intent intent) {
// 将意图的目标组件设置为AlarmAlertActivity便签提醒展示界面
// 确保广播中携带的便签信息如Data中的便签ID被传递给目标界面
intent.setClass(context, AlarmAlertActivity.class);
// 添加FLAG_ACTIVITY_NEW_TASK标志在BroadcastReceiver中启动Activity必须设置此标志
// 因为BroadcastReceiver本身没有任务栈需要为启动的Activity创建新任务栈
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动AlarmAlertActivity展示便签提醒对话框并播放铃声
context.startActivity(intent);
}
}
}

@ -28,57 +28,75 @@ import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
/**
*
* 便12/24
*/
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;
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
private Calendar mDate;
// 时间计算常量定义
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; // 24小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时制小时最大值
private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟选择器最小值
private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟选择器最大值
private static final int AMPM_SPINNER_MIN_VAL = 0; // 上下午选择器最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // 上下午选择器最大值
// 选择器组件
private final NumberPicker mDateSpinner; // 日期选择器(显示近一周日期)
private final NumberPicker mHourSpinner; // 小时选择器
private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // 上下午选择器12小时制用
private Calendar mDate; // 日期时间计算工具
// 日期显示值数组(存储近一周的日期文本)
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm;
private boolean mIs24HourView;
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
private boolean mInitialising;
// 时间状态变量
private boolean mIsAm; // 是否为上午12小时制
private boolean mIs24HourView; // 是否为24小时制显示
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 组件是否启用
private boolean mInitialising; // 是否处于初始化状态
// 日期时间变更监听器
private OnDateTimeChangedListener mOnDateTimeChangedListener;
/**
*
*
*/
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 计算日期偏移量并更新
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
}
};
/**
*
* 23012/24
*/
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) {
// 12小时制处理跨天情况如11PM到12AM需加一天12AM到11PM需减一天
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
@ -88,12 +106,14 @@ public class DateTimePicker extends FrameLayout {
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
// 12点和11点切换时切换上下午状态
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}
} else {
// 24小时制处理跨天情况如23点到0点加一天0点到23点减一天
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
@ -104,9 +124,13 @@ public class DateTimePicker extends FrameLayout {
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));
@ -115,39 +139,55 @@ public class DateTimePicker extends FrameLayout {
}
};
/**
*
* 5901
*/
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;
// 判断是否跨小时59->0加1小时0->59减1小时
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();
// 更新上下午状态12小时制
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
updateAmPmControl();
}
// 更新分钟并触发事件
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
}
};
/**
*
* /12
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
// 切换上下午时调整小时上午转下午加12小时反之减12小时
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
@ -158,39 +198,65 @@ public class DateTimePicker extends FrameLayout {
}
};
/**
*
*
*/
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
int dayOfMonth, int hourOfDay, int minute);
}
/**
* 使使12/24
* @param context
*/
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
/**
* 使使12/24
* @param context
* @param date
*/
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
/**
* 使
* @param context
* @param date
* @param is24HourView 使24
*/
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
mDate = Calendar.getInstance();
mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
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.setOnLongPressUpdateInterval(100); // 长按更新间隔(毫秒)
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化上下午选择器使用系统本地化的AM/PM文本
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
@ -198,22 +264,28 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
// 更新控件到初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
// 设置时间格式12/24小时制
set24HourView(is24HourView);
// set to current time
// 设置初始时间
setCurrentDate(date);
// 设置启用状态
setEnabled(isEnabled());
// set the content descriptions
// 初始化完成
mInitialising = false;
}
/**
*
* @param enabled
*/
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
@ -227,24 +299,26 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled;
}
/**
*
* @return
*/
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Get the current date in millis
*
* @return the current date in millis
*
* @return
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
* Set the current date
*
* @param date The current date in millis
*
* @param date
*/
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
@ -254,16 +328,15 @@ 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
*
* @param year
* @param month 0-11
* @param dayOfMonth
* @param hourOfDay 240-23
* @param minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
@ -272,18 +345,16 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current year
*
* @return The current year
*
* @return
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
/**
* Set current year
*
* @param year The current year
*
* @param year
*/
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
@ -295,18 +366,16 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current month in the year
*
* @return The current month in the year
* 0-11
* @return
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
/**
* Set current month in the year
*
* @param month The month in the year
*
* @param month 0-11
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
@ -318,18 +387,16 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current day of the month
*
* @return The day of the month
*
* @return
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
/**
* Set current day of the month
*
* @param dayOfMonth The day of the month
*
* @param dayOfMonth
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
@ -341,18 +408,23 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode
* 240-23
* @return
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
/**
* 12/24
* @return
*/
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
} else {
int hour = getCurrentHourOfDay();
// 12小时制转换13->10->12
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
} else {
@ -362,16 +434,17 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
* 24
* @param hourOfDay 0-23
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) {
// 12小时制处理更新上下午状态和小时显示值
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) {
@ -385,21 +458,22 @@ public class DateTimePicker extends FrameLayout {
}
updateAmPmControl();
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
}
/**
* Get currentMinute
*
* @return The Current Minute
*
* @return
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
/**
* Set current minute
*
* @param minute 0-59
*/
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
@ -411,22 +485,23 @@ public class DateTimePicker extends FrameLayout {
}
/**
* @return true if this is in 24 hour view else false.
* 24
* @return 24
*/
public boolean is24HourView () {
return mIs24HourView;
}
/**
* Set whether in 24 hour or AM/PM mode.
*
* @param is24HourView True for 24 hour mode. False for AM/PM mode.
* 24/12
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
// 24小时制隐藏上下午选择器12小时制显示
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
@ -434,20 +509,30 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl();
}
/**
* .
*/
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
// 计算起始日期当前日期减去3天用于显示近一周
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
// 生成近一周的日期文本
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); // 默认选中当前日期
mDateSpinner.invalidate();
}
/**
* 12
*/
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
@ -458,6 +543,9 @@ public class DateTimePicker extends FrameLayout {
}
}
/**
* 12/24
*/
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
@ -469,17 +557,20 @@ 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
*
* @param callback
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
/**
*
*/
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}
}

@ -29,60 +29,107 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
/**
* 便
* AlertDialogDateTimePicker
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 用于维护当前选中的日期时间
private Calendar mDate = Calendar.getInstance();
// 是否采用24小时制显示时间
private boolean mIs24HourView;
// 日期时间选择完成后的回调监听器由调用者实现如NoteEditActivity
private OnDateTimeSetListener mOnDateTimeSetListener;
// 自定义的日期时间选择器视图,负责用户选择交互
private DateTimePicker mDateTimePicker;
/**
*
* "确定"
*/
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
*
* @param context NoteEditActivity
* @param date 便
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 初始化自定义的日期时间选择器
mDateTimePicker = new DateTimePicker(context);
// 将选择器设置为对话框的内容视图
setView(mDateTimePicker);
// 为日期时间选择器设置变化监听器:当用户选择的日期或时间变化时触发
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
// 更新内部维护的日期时间
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
// 根据新选择的时间更新对话框标题
updateTitle(mDate.getTimeInMillis());
}
});
// 设置初始日期时间(忽略秒数,确保提醒时间精确到分钟)
mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0);
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置对话框按钮:"确定"按钮触发onClick方法"取消"按钮不执行操作
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置初始化24小时制显示模式
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 初始化对话框标题为初始日期时间
updateTitle(mDate.getTimeInMillis());
}
/**
* 24/12
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
/**
*
* @param callBack OnDateTimeSetListenerActivity
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
* @param date
*/
private void updateTitle(long date) {
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 定义日期时间的显示格式:包含年、月、日、时间
int flag = DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME;
// 根据24小时制模式调整显示格式
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
// 格式化时间并设置为对话框标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
* "确定"
*
*/
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
// 回调传递选中的时间(毫秒级时间戳)
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}

@ -27,17 +27,35 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
* 便
*
*/
public class DropdownMenu {
// 触发下拉菜单的按钮
private Button mButton;
// 系统提供的弹出式菜单组件,负责显示下拉选项
private PopupMenu mPopupMenu;
// 菜单容器,存储从资源文件加载的菜单项
private Menu mMenu;
/**
*
* @param context 访
* @param button
* @param menuId IDres/menu
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置按钮背景为下拉图标(箭头图标)
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 初始化PopupMenu绑定到触发按钮
mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单容器
mMenu = mPopupMenu.getMenu();
// 从资源文件加载菜单项到菜单容器
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击事件:点击时显示下拉菜单
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
@ -45,17 +63,30 @@ public class DropdownMenu {
});
}
/**
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
/**
* ID
* @param id ID
* @return MenuItem
*/
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
/**
*
* @param title "已选择3项"
*/
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}
}

@ -28,53 +28,103 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便便
* CursorAdapter
*/
public class FoldersListAdapter extends CursorAdapter {
/**
*
* IDSNIPPET
*/
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
NoteColumns.ID, // 文件夹ID
NoteColumns.SNIPPET // 文件夹名称(小米便签中文件夹名称存储在此字段)
};
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
/**
* Cursor
*/
public static final int ID_COLUMN = 0; // PROJECTION中ID字段的索引
public static final int NAME_COLUMN = 1; // PROJECTION中SNIPPET名称字段的索引
/**
*
* @param context Activity
* @param c
*/
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
/**
*
* @param context
* @param cursor 使
* @param parent ListView
* @return FolderListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
}
/**
*
* @param view FolderListItem
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
// 处理根文件夹的特殊名称根文件夹ID为Notes.ID_ROOT_FOLDER显示为“移动到父文件夹”
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 将文件夹名称绑定到列表项视图
((FolderListItem) view).bind(folderName);
}
}
/**
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
// 根文件夹特殊处理其他文件夹直接取SNIPPET字段值
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
/**
* LinearLayout
*/
private class FolderListItem extends LinearLayout {
private TextView mName;
private TextView mName; // 用于显示文件夹名称的文本控件
/**
*
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 加载文件夹列表项的布局文件folder_list_item.xml
inflate(context, R.layout.folder_list_item, this);
// 获取布局中的文本控件,用于显示文件夹名称
mName = (TextView) findViewById(R.id.tv_folder_name);
}
/**
*
* @param name
*/
public void bind(String name) {
mName.setText(name);
}
}
}
}

File diff suppressed because it is too large Load Diff

@ -37,73 +37,114 @@ import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
/**
* 便EditText便
*
*/
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
// 当前输入框在多输入框列表中的索引(用于区分不同输入框)
private int mIndex;
// 记录删除键按下前的光标起始位置(用于判断是否删除当前输入框)
private int mSelectionStartBeforeDelete;
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
// 支持的链接协议常量
private static final String SCHEME_TEL = "tel:" ; // 电话协议(如"tel:10086"
private static final String SCHEME_HTTP = "http:" ; // 网页协议(如"http://www.micode.net"
private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议(如"mailto:test@micode.net"
// 链接协议与对应菜单资源的映射(用于上下文菜单显示对应操作文字)
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话链接对应"拨打"菜单
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网页链接对应"打开网页"菜单
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮件链接对应"发送邮件"菜单
}
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
* {@link NoteEditActivity}
*/
public interface OnTextViewChangeListener {
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*
* @param index
* @param text
*/
void onEditTextDelete(int index, String text);
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*
* @param index +1
* @param text
*/
void onEditTextEnter(int index, String text);
/**
* Hide or show item option when text change
*
* @param index
* @param hasText /
*/
void onTextChange(int index, boolean hasText);
}
// 文本变化监听器实例由NoteEditActivity设置
private OnTextViewChangeListener mOnTextViewChangeListener;
/**
*
* @param context NoteEditActivity
*/
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
mIndex = 0; // 默认索引为0
}
/**
*
* @param index
*/
public void setIndex(int index) {
mIndex = index;
}
/**
* NoteEditActivity
* @param listener OnTextViewChangeListener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
/**
* +
* @param context
* @param attrs
*/
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
/**
* ++
* @param context
* @param attrs
* @param defStyle
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/**
*
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 计算触摸点在文本中的实际坐标(扣除内边距并加上滚动偏移)
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft();
@ -111,25 +152,33 @@ public class NoteEditText extends EditText {
x += getScrollX();
y += getScrollY();
// 根据坐标获取对应的文本行和偏移量,设置光标位置
Layout layout = getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off);
int line = layout.getLineForVertical(y); // 触摸点所在的文本行
int off = layout.getOffsetForHorizontal(line, x); // 行内的水平偏移(光标位置)
Selection.setSelection(getText(), off); // 设置光标
break;
}
return super.onTouchEvent(event);
}
/**
*
* @param keyCode KEYCODE_DELKEYCODE_ENTER
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
// 回车键事件由onKeyUp处理此处返回false让事件继续传递
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
// 记录删除键按下前的光标起始位置,用于判断是否需要删除输入框
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
@ -138,11 +187,18 @@ public class NoteEditText extends EditText {
return super.onKeyDown(keyCode, event);
}
/**
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
// 若光标在起始位置且不是第一个输入框,通知删除当前输入框
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
@ -153,10 +209,11 @@ public class NoteEditText extends EditText {
break;
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
// 处理回车键:将光标后的文本移至新输入框
int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString();
setText(getText().subSequence(0, selectionStart));
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
String text = getText().subSequence(selectionStart, length()).toString(); // 光标后文本
setText(getText().subSequence(0, selectionStart)); // 保留光标前文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 通知新增输入框
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
@ -167,9 +224,16 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event);
}
/**
*
* @param focused
* @param direction
* @param previouslyFocusedRect
*/
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
// 失去焦点且文本为空时,通知无文本;否则通知有文本
if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false);
} else {
@ -179,18 +243,24 @@ public class NoteEditText extends EditText {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
*
* @param menu
*/
@Override
protected void onCreateContextMenu(ContextMenu menu) {
// 仅处理富文本中的链接
if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 获取选中区域内的链接
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
if (urls.length == 1) { // 仅处理单个链接的情况
int defaultResId = 0;
// 识别链接协议,匹配对应的菜单资源
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
@ -198,15 +268,16 @@ public class NoteEditText extends EditText {
}
}
// 未匹配到已知协议时,使用默认菜单文本
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}
// 向菜单添加链接操作项,点击后触发链接的默认行为(如拨号、打开浏览器)
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
urls[0].onClick(NoteEditText.this);
urls[0].onClick(NoteEditText.this); // 触发URLSpan的点击事件
return true;
}
});
@ -214,4 +285,4 @@ public class NoteEditText extends EditText {
}
super.onCreateContextMenu(menu);
}
}
}

@ -26,57 +26,70 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
/**
* 便便UI
*/
public class NoteItemData {
// 数据库查询的列名数组,对应便签表的核心字段
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE, // 提醒时间
NoteColumns.BG_COLOR_ID, // 背景色ID
NoteColumns.CREATED_DATE, // 创建时间
NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.MODIFIED_DATE, // 修改时间
NoteColumns.NOTES_COUNT, // 文件夹包含的便签数量(仅文件夹类型有效)
NoteColumns.PARENT_ID, // 父文件夹ID
NoteColumns.SNIPPET, // 内容摘要(文件夹名或便签内容片段)
NoteColumns.TYPE, // 类型(便签/文件夹/系统文件夹)
NoteColumns.WIDGET_ID, // 桌面插件ID
NoteColumns.WIDGET_TYPE, // 桌面插件类型
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
// 上述PROJECTION数组中各列的索引常量用于从Cursor中提取数据
private static final int ID_COLUMN = 0; // 便签ID索引
private static final int ALERTED_DATE_COLUMN = 1; // 提醒时间索引
private static final int BG_COLOR_ID_COLUMN = 2; // 背景色ID索引
private static final int CREATED_DATE_COLUMN = 3; // 创建时间索引
private static final int HAS_ATTACHMENT_COLUMN = 4; // 是否有附件索引
private static final int MODIFIED_DATE_COLUMN = 5; // 修改时间索引
private static final int NOTES_COUNT_COLUMN = 6; // 文件夹便签数量索引
private static final int PARENT_ID_COLUMN = 7; // 父文件夹ID索引
private static final int SNIPPET_COLUMN = 8; // 内容摘要索引
private static final int TYPE_COLUMN = 9; // 类型索引
private static final int WIDGET_ID_COLUMN = 10; // 桌面插件ID索引
private static final int WIDGET_TYPE_COLUMN = 11; // 桌面插件类型索引
// 便签核心数据字段
private long mId; // 便签唯一ID
private long mAlertDate; // 提醒时间(毫秒时间戳)
private int mBgColorId; // 背景色ID对应资源文件
private long mCreatedDate; // 创建时间(毫秒时间戳)
private boolean mHasAttachment; // 是否有附件(如图片等)
private long mModifiedDate; // 最后修改时间(毫秒时间戳)
private int mNotesCount; // 文件夹包含的便签数量(仅文件夹类型使用)
private long mParentId; // 所属文件夹ID
private String mSnippet; // 内容摘要(文件夹名或便签内容的简短展示)
private int mType; // 类型Notes.TYPE_NOTE便签TYPE_FOLDER文件夹等
private int mWidgetId; // 关联的桌面插件ID无则为无效值
private int mWidgetType; // 桌面插件类型(无则为无效值)
private String mName; // 通话记录便签的联系人姓名(非通话记录则为空)
private String mPhoneNumber; // 通话记录便签的电话号码(非通话记录则为空)
// 列表位置属性用于UI背景样式适配
private boolean mIsLastItem; // 是否为列表最后一项
private boolean mIsFirstItem; // 是否为列表第一项
private boolean mIsOnlyOneItem; // 是否为列表中唯一一项
private boolean mIsOneNoteFollowingFolder; // 是否为文件夹后的唯一便签项
private boolean mIsMultiNotesFollowingFolder; // 是否为文件夹后的多个便签项之一
/**
* 便
* @param context
* @param cursor 便
*/
public NoteItemData(Context context, Cursor cursor) {
// 从游标中提取核心数据字段
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
@ -86,19 +99,21 @@ public class NoteItemData {
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
// 移除检查列表标记(用于纯文本展示)
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
// 处理通话记录便签:提取电话号码并关联联系人姓名
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { // 若属于通话记录文件夹
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
mName = Contact.getContact(context, mPhoneNumber); // 获取联系人姓名
if (mName == null) {
mName = mPhoneNumber;
mName = mPhoneNumber; // 无联系人时显示电话号码
}
}
}
@ -106,27 +121,39 @@ public class NoteItemData {
if (mName == null) {
mName = "";
}
// 计算当前项在列表中的位置属性
checkPostion(cursor);
}
/**
* UI
* @param cursor
*/
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
mIsLastItem = cursor.isLast() ? true : false; // 是否为最后一项
mIsFirstItem = cursor.isFirst() ? true : false; // 是否为第一项
mIsOnlyOneItem = (cursor.getCount() == 1); // 是否为唯一一项
// 初始化文件夹后便签的位置属性
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
// 若当前是便签项且不是第一项,检查前一项是否为文件夹
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
if (cursor.moveToPrevious()) { // 移动到前一项
// 前一项是文件夹或系统文件夹
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
// 若游标总数大于当前位置+1说明文件夹后有多个便签
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
} else {
// 否则文件夹后只有当前一个便签
mIsOneNoteFollowingFolder = true;
}
}
// 移回原位置,避免游标错乱
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
@ -134,91 +161,159 @@ public class NoteItemData {
}
}
/**
* 便
*/
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
/**
* 便
*/
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
/**
*
*/
public boolean isLast() {
return mIsLastItem;
}
/**
* 便
*/
public String getCallName() {
return mName;
}
/**
*
*/
public boolean isFirst() {
return mIsFirstItem;
}
/**
*
*/
public boolean isSingle() {
return mIsOnlyOneItem;
}
/**
* 便ID
*/
public long getId() {
return mId;
}
/**
*
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
*/
public long getCreatedDate() {
return mCreatedDate;
}
/**
*
*/
public boolean hasAttachment() {
return mHasAttachment;
}
/**
*
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
*/
public long getParentId() {
return mParentId;
}
/**
* 便
*/
public int getNotesCount() {
return mNotesCount;
}
/**
* IDgetParentId
*/
public long getFolderId () {
return mParentId;
}
/**
* 便//
*/
public int getType() {
return mType;
}
/**
*
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* 便
*/
public String getSnippet() {
return mSnippet;
}
/**
* >0
*/
public boolean hasAlert() {
return (mAlertDate > 0);
}
/**
* 便
*/
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
* 便
* @param cursor
* @return 便Notes.TYPE_NOTE
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}
}

File diff suppressed because it is too large Load Diff

@ -31,18 +31,30 @@ import java.util.HashSet;
import java.util.Iterator;
/**
* 便便
* CursorAdapterCursor便
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter";
private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount;
private boolean mChoiceMode;
private Context mContext; // 上下文对象
private HashMap<Integer, Boolean> mSelectedIndex; // 存储选中项的位置和状态
private int mNotesCount; // 便签总数(不包含文件夹)
private boolean mChoiceMode; // 是否处于选择模式
/**
*
*
*/
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
public int widgetId; // 插件ID
public int widgetType; // 插件类型
};
/**
*
* @param context
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
@ -50,38 +62,71 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0;
}
/**
*
* @param context
* @param cursor
* @param parent
* @return NotesListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
// 从游标中解析便签数据
NoteItemData itemData = new NoteItemData(context, cursor);
// 绑定数据到视图,设置选择模式和选中状态
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
/**
*
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
notifyDataSetChanged(); // 通知列表刷新
}
/**
*
* @return
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
* @param mode
*/
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mSelectedIndex.clear(); // 清除选中状态
mChoiceMode = mode;
}
/**
* 便便
* @param checked
*/
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
// 仅处理类型为普通便签的项
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
@ -89,11 +134,16 @@ public class NotesListAdapter extends CursorAdapter {
}
}
/**
* ID
* @return IDHashSet
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
// 过滤根文件夹ID不应被选中
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
@ -101,10 +151,13 @@ public class NotesListAdapter extends CursorAdapter {
}
}
}
return itemSet;
}
/**
*
* @return HashSet
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
@ -116,9 +169,7 @@ public class NotesListAdapter extends CursorAdapter {
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*/
// 注意:此处不关闭游标,游标由适配器管理
} else {
Log.e(TAG, "Invalid cursor");
return null;
@ -128,6 +179,10 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
* @return
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
@ -143,11 +198,20 @@ public class NotesListAdapter extends CursorAdapter {
return count;
}
/**
* 便
* @return
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
}
/**
*
* @param position
* @return
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
@ -155,23 +219,34 @@ public class NotesListAdapter extends CursorAdapter {
return mSelectedIndex.get(position);
}
/**
* 便
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
}
/**
* 便
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
}
/**
* 便
*/
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
// 仅统计类型为普通便签的项
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
@ -181,4 +256,4 @@ public class NotesListAdapter extends CursorAdapter {
}
}
}
}
}

@ -30,17 +30,27 @@ import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
* 便
* 便
*/
public class NotesListItem extends LinearLayout {
private ImageView mAlert;
private TextView mTitle;
private TextView mTime;
private TextView mCallName;
private NoteItemData mItemData;
private CheckBox mCheckBox;
private ImageView mAlert; // 提醒图标(显示闹钟或通话记录图标)
private TextView mTitle; // 标题/内容文本(显示便签内容、文件夹名称等)
private TextView mTime; // 时间文本(显示最后修改时间)
private TextView mCallName; // 通话记录联系人名称(仅通话记录便签显示)
private NoteItemData mItemData; // 当前项对应的数据模型
private CheckBox mCheckBox; // 多选模式下的复选框
/**
*
* @param context
*/
public NotesListItem(Context context) {
super(context);
// 加载列表项布局文件
inflate(context, R.layout.note_item, this);
// 绑定UI控件
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
@ -48,7 +58,15 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
/**
*
* @param context
* @param data 便
* @param choiceMode
* @param checked
*/
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 处理多选模式:仅普通便签显示复选框并同步选中状态
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
@ -57,33 +75,44 @@ public class NotesListItem extends LinearLayout {
}
mItemData = data;
// 处理通话记录文件夹(特殊系统文件夹)
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 显示文件夹名称和包含的便签数量
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);
mAlert.setImageResource(R.drawable.call_record); // 显示通话记录图标
// 处理通话记录文件夹下的便签
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
mCallName.setText(data.getCallName()); // 显示联系人名称
mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 显示便签内容片段
// 显示提醒图标(如有)
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
// 处理普通文件夹和普通便签
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 普通文件夹:显示名称和包含的便签数量
if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
// 普通便签:显示内容片段和提醒状态
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
@ -94,29 +123,47 @@ public class NotesListItem extends LinearLayout {
}
}
}
// 显示最后修改时间(相对时间格式,如"1小时前"
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 设置项背景样式
setBackground(data);
}
/**
* 便
* @param data 便
*/
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
int bgColorId = data.getBgColorId(); // 获取背景色ID
// 普通便签:根据位置(首项/末项/单项等)设置不同背景
if (data.getType() == Notes.TYPE_NOTE) {
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
// 单项或文件夹后的唯一便签
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(bgColorId));
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
// 列表中的最后一项
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(bgColorId));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
// 首项或文件夹后的多个便签中的第一项
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(bgColorId));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
// 中间项
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(bgColorId));
}
} else {
// 文件夹:使用固定的文件夹背景
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
/**
*
* @return 便
*/
public NoteItemData getItemData() {
return mItemData;
}
}
}

@ -48,41 +48,52 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
/**
* 便
* 便
*/
public class NotesPreferenceActivity extends PreferenceActivity {
// 偏好设置存储名称
public static final String PREFERENCE_NAME = "notes_preferences";
// 同步账号名称的偏好键
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
// 最后同步时间的偏好键
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
// 背景颜色设置的偏好键
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
// 同步账号设置分类的键
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
// 账号权限过滤键
private static final String AUTHORITIES_FILTER_KEY = "authorities";
// 账号设置分类
private PreferenceCategory mAccountCategory;
// 同步服务广播接收器
private GTaskReceiver mReceiver;
// 原始账号列表(用于检测新添加的账号)
private Account[] mOriAccounts;
// 是否添加了新账号的标记
private boolean mHasAddedAccount;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
// 设置ActionBar支持返回导航
getActionBar().setDisplayHomeAsUpEnabled(true);
// 加载偏好设置布局
addPreferencesFromResource(R.xml.preferences);
// 获取账号设置分类
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
// 初始化广播接收器并注册,监听同步服务广播
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);
// 初始化账号列表和头部视图
mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);
@ -92,8 +103,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
// 如果检测到新添加的账号,自动设置为同步账号
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
@ -113,17 +123,22 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
// 刷新UI显示
refreshUI();
}
@Override
protected void onDestroy() {
// 注销广播接收器
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
}
/**
*
*/
private void loadAccountPreference() {
mAccountCategory.removeAll();
@ -131,20 +146,21 @@ public class NotesPreferenceActivity extends PreferenceActivity {
final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary));
// 设置账号项点击事件
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
// 首次设置账号,显示账号选择对话框
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
// 已设置账号,显示账号变更确认对话框
showChangeAccountConfirmAlertDialog();
}
} else {
// 同步中不允许变更账号
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
@ -154,15 +170,19 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref);
}
/**
*
*/
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
// 设置同步按钮状态
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 取消同步
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
@ -170,13 +190,15 @@ public class NotesPreferenceActivity extends PreferenceActivity {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 立即同步
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
}
// 未设置账号时禁用同步按钮
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
// 设置最后同步时间显示
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
@ -193,23 +215,30 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
/**
* UI
*/
private void refreshUI() {
loadAccountPreference();
loadSyncButton();
}
/**
*
*/
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 自定义对话框标题
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
// 获取谷歌账号列表
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
@ -221,12 +250,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
final CharSequence[] itemMapping = items;
int checkedItem = -1;
int index = 0;
// 构建账号选择列表
for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
}
items[index++] = account.name;
}
// 设置单选列表点击事件
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
@ -237,6 +268,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
});
}
// 添加"添加账号"选项
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
@ -244,9 +276,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
// 跳转到添加账号设置页面
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
"gmail-ls"
});
startActivityForResult(intent, -1);
dialog.dismiss();
@ -254,9 +287,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
});
}
/**
*
*/
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 自定义对话框标题
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
@ -265,6 +302,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
// 对话框选项:变更账号、移除账号、取消
CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account),
@ -273,8 +311,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// 变更账号:显示账号选择对话框
showSelectAccountAlertDialog();
} else if (which == 1) {
// 移除账号
removeSyncAccount();
refreshUI();
}
@ -283,11 +323,19 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.show();
}
/**
*
* @return
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
/**
*
* @param account
*/
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
@ -299,10 +347,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up last sync time
// 清除最后同步时间
setLastSyncTime(this, 0);
// clean up local gtask related info
// 清除本地GTASK相关信息异步执行
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
@ -318,6 +366,9 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
/**
*
*/
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
@ -329,7 +380,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
editor.commit();
// clean up local gtask related info
// 清除本地GTASK相关信息异步执行
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
@ -340,12 +391,22 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start();
}
/**
*
* @param context
* @return
*/
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
/**
*
* @param context
* @param time
*/
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
@ -354,16 +415,26 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit();
}
/**
*
* @param context
* @return 0
*/
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
/**
* 广
* UI
*/
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 刷新UI显示同步状态
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
@ -374,9 +445,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
/**
*
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// 返回便签列表页面
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
@ -385,4 +460,4 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return false;
}
}
}
}

@ -32,24 +32,36 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
/**
* 便
*
*/
public abstract class NoteWidgetProvider extends AppWidgetProvider {
// 查询便签数据时使用的字段投影
public static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
NoteColumns.ID, // 便签ID
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.SNIPPET // 便签内容摘要
};
// 投影字段对应的索引值
public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
private static final String TAG = "NoteWidgetProvider";
/**
*
*
*/
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues();
// 将小部件ID设为无效值
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < appWidgetIds.length; i++) {
// 更新数据库中关联该小部件的便签记录
context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
@ -57,76 +69,119 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
}
}
/**
* 便
* @param context
* @param widgetId ID
* @return 便
*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
// 查询条件小部件ID匹配且不在回收站中
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null);
}
/**
*
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false);
}
/**
* UI
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
* @param privacyMode
*/
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) {
boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {
// 只处理有效的小部件ID
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 默认背景颜色ID
int bgId = ResourceParser.getDefaultBgId(context);
// 便签内容摘要
String snippet = "";
// 点击小部件时的跳转意图
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
// 查询与当前小部件关联的便签数据
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) {
// 检查是否有多个便签关联到同一小部件(异常情况)
if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return;
}
// 从游标中获取数据
snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID);
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW);
intent.setAction(Intent.ACTION_VIEW); // 查看已有便签
} else {
// 无关联便签时显示默认文本
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 新建便签
}
// 关闭游标释放资源
if (c != null) {
c.close();
}
// 加载小部件布局
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
// 设置背景图片
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
/**
* Generate the pending intent to start host for the widget
*/
// 创建点击事件的PendingIntent
PendingIntent pendingIntent = null;
if (privacyMode) {
// 隐私模式下显示提示文本,点击跳转至便签列表
rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else {
// 正常模式下显示便签内容,点击跳转至编辑页
rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
// 设置点击事件
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
}
/**
* ID
*
*/
protected abstract int getBgResourceId(int bgId);
/**
* ID
*
*/
protected abstract int getLayoutId();
/**
*
* 2x4x
*/
protected abstract int getWidgetType();
}
}

@ -23,25 +23,54 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 2x便
* NoteWidgetProvider2x
*/
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
/**
*
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的update方法执行通用更新逻辑如查询数据、绑定事件
super.update(context, appWidgetManager, appWidgetIds);
}
/**
* 2xID
* UI
* @return 2xIDR.layout.widget_2x
*/
@Override
protected int getLayoutId() {
return R.layout.widget_2x;
}
/**
* 2xID
* 便IDbgId2x
* @param bgId 便ID
* @return 2xID
*/
@Override
protected int getBgResourceId(int bgId) {
// 通过资源解析工具获取2x尺寸的背景资源
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}
/**
* 2x
*
* @return 2xNotes.TYPE_WIDGET_2X
*/
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X;
}
}
}

@ -24,23 +24,49 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* 便4xNoteWidgetProvider4x
*/
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
/**
*
* update便
* @param context 访
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
}
/**
* 4xID
* widget_4x.xmlUI
* @return 4xID
*/
protected int getLayoutId() {
return R.layout.widget_4x;
}
/**
* IDbgId4x
* ResourceParser便
* @param bgId ID
* @return 4xID
*/
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
}
/**
* 4x
* NotesTYPE_WIDGET_4X
* @return 4x
*/
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X;
}
}
}
Loading…
Cancel
Save