master^2
Fivepace 2 months ago
parent 61fb312c25
commit 275bf0d478

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : Contact.java
* :
* : 便便
*/
package net.micode.notes.data; package net.micode.notes.data;
import android.content.Context; import android.content.Context;
@ -25,10 +30,24 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
/**
*
*
* 使
*/
public class Contact { public class Contact {
/** 联系人缓存,键为电话号码,值为联系人姓名 */
private static HashMap<String, String> sContactCache; private static HashMap<String, String> sContactCache;
/** 日志标签 */
private static final String TAG = "Contact"; private static final String TAG = "Contact";
/**
* SQL
* 使PHONE_NUMBERS_EQUAL
* MIMETYPE
* phone_lookupmin_match
*/
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,17 +55,29 @@ public class Contact {
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/**
*
*
* @param context 访ContentResolver
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 初始化缓存(如果需要)
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
// 检查缓存中是否已有该号码对应的联系人
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber);
} }
// 替换SQL查询条件中的占位符转换电话号码为标准格式
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 执行查询,获取联系人姓名
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI, Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME }, new String [] { Phone.DISPLAY_NAME },
@ -54,18 +85,23 @@ public class Contact {
new String[] { phoneNumber }, new String[] { phoneNumber },
null); null);
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
// 获取联系人姓名并存入缓存
String name = cursor.getString(0); String name = cursor.getString(0);
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);
return name; return name;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 处理索引越界异常
Log.e(TAG, " Cursor get string error " + e.toString()); Log.e(TAG, " Cursor get string error " + e.toString());
return null; return null;
} finally { } finally {
// 确保关闭游标,释放资源
cursor.close(); cursor.close();
} }
} else { } else {
// 未找到匹配的联系人
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null; return null;
} }

@ -14,14 +14,41 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : Notes.java
* : 便
* : URIID
*/
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
/**
* 便
*
* 便
* -
* - 便
* - ID
* - Intent
* -
* -
* - URI
*/
public class Notes { public class Notes {
/** 内容提供者的权限名称 */
public static final String AUTHORITY = "micode_notes"; public static final String AUTHORITY = "micode_notes";
/** 日志标签 */
public static final String TAG = "Notes"; public static final String TAG = "Notes";
/** 便签类型:普通便签 */
public static final int TYPE_NOTE = 0; public static final int TYPE_NOTE = 0;
/** 便签类型:文件夹 */
public static final int TYPE_FOLDER = 1; public static final int TYPE_FOLDER = 1;
/** 便签类型:系统文件夹 */
public static final int TYPE_SYSTEM = 2; public static final int TYPE_SYSTEM = 2;
/** /**
@ -30,37 +57,73 @@ public class Notes {
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/ */
/** 系统文件夹ID根文件夹默认文件夹 */
public static final int ID_ROOT_FOLDER = 0; public static final int ID_ROOT_FOLDER = 0;
/** 系统文件夹ID临时文件夹不属于任何文件夹的便签 */
public static final int ID_TEMPARAY_FOLDER = -1; public static final int ID_TEMPARAY_FOLDER = -1;
/** 系统文件夹ID通话记录文件夹 */
public static final int ID_CALL_RECORD_FOLDER = -2; public static final int ID_CALL_RECORD_FOLDER = -2;
/** 系统文件夹ID回收站文件夹 */
public static final int ID_TRASH_FOLER = -3; public static final int ID_TRASH_FOLER = -3;
/** Intent参数提醒日期 */
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date"; public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
/** Intent参数背景颜色ID */
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id"; public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
/** Intent参数小部件ID */
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id"; public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
/** Intent参数小部件类型 */
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type"; public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
/** Intent参数文件夹ID */
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_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"; public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
/** 小部件类型:无效 */
public static final int TYPE_WIDGET_INVALIDE = -1; public static final int TYPE_WIDGET_INVALIDE = -1;
/** 小部件类型2x小部件 */
public static final int TYPE_WIDGET_2X = 0; public static final int TYPE_WIDGET_2X = 0;
/** 小部件类型4x小部件 */
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_4X = 1;
/**
*
* 便MIME
*/
public static class DataConstants { public static class DataConstants {
/** 文本便签的MIME类型 */
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE; public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
/** 通话记录便签的MIME类型 */
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE; public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
} }
/** /**
* Uri to query all notes and folders * Uri to query all notes and folders
*/ */
/** 查询所有便签和文件夹的URI */
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/** /**
* Uri to query data * Uri to query data
*/ */
/** 查询便签数据的URI */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
/**
* 便
* note
*/
public interface NoteColumns { public interface NoteColumns {
/** /**
* The unique ID for a row * The unique ID for a row
@ -167,6 +230,10 @@ public class Notes {
public static final String VERSION = "version"; public static final String VERSION = "version";
} }
/**
*
* data
*/
public interface DataColumns { public interface DataColumns {
/** /**
* The unique ID for a row * The unique ID for a row
@ -241,6 +308,10 @@ public class Notes {
public static final String DATA5 = "data5"; public static final String DATA5 = "data5";
} }
/**
* 便
* 便
*/
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not * Mode to indicate the text in check list mode or not
@ -248,15 +319,23 @@ public class Notes {
*/ */
public static final String MODE = DATA1; public static final String MODE = DATA1;
/** 便签模式:清单模式(可勾选的项目列表) */
public static final int MODE_CHECK_LIST = 1; public static final int MODE_CHECK_LIST = 1;
/** 文本便签内容类型:多条记录 */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note"; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
/** 文本便签内容类型:单条记录 */
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
/** 文本便签内容URI */
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
} }
/**
* 便
* 便
*/
public static final class CallNote implements DataColumns { public static final class CallNote implements DataColumns {
/** /**
* Call date for this record * Call date for this record
@ -270,10 +349,13 @@ public class Notes {
*/ */
public static final String PHONE_NUMBER = DATA3; public static final String PHONE_NUMBER = DATA3;
/** 通话记录便签内容类型:多条记录 */
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
/** 通话记录便签内容类型:单条记录 */
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
/** 通话记录便签内容URI */
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
} }
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NotesDatabaseHelper.java
* : 便SQLite
* :
*/
package net.micode.notes.data; package net.micode.notes.data;
import android.content.ContentValues; import android.content.ContentValues;
@ -26,22 +31,42 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
*
* SQLiteOpenHelper便
* 便
* 使
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** 数据库名称 */
private static final String DB_NAME = "note.db"; private static final String DB_NAME = "note.db";
/** 数据库版本号 */
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;
/**
*
*
*/
public interface TABLE { public interface TABLE {
/** 便签表名 */
public static final String NOTE = "note"; public static final String NOTE = "note";
/** 数据表名 */
public static final String DATA = "data"; public static final String DATA = "data";
} }
/** 日志标签 */
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";
/** 单例实例 */
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
/**
* 便SQL
* 便
*/
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -63,6 +88,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")"; ")";
/**
* SQL
* 便
*/
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -78,12 +107,17 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")"; ")";
/**
* NOTE_IDSQL
* 便ID
*/
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
/** /**
* Increase folder's note count when move note to the folder * 便
* 便便
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+ "CREATE TRIGGER increase_folder_count_on_update "+
@ -95,7 +129,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Decrease folder's note count when move note from folder * 便
* 便便
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " + "CREATE TRIGGER decrease_folder_count_on_update " +
@ -108,7 +143,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Increase folder's note count when insert new note to the folder * 便
* 便便
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " + "CREATE TRIGGER increase_folder_count_on_insert " +
@ -120,7 +156,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Decrease folder's note count when delete note from the folder * 便
* 便便
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " + "CREATE TRIGGER decrease_folder_count_on_delete " +
@ -133,7 +170,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE} * 便
* NOTE便
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " + "CREATE TRIGGER update_note_content_on_insert " +
@ -146,7 +184,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changed * 便
* NOTE便
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " + "CREATE TRIGGER update_note_content_on_update " +
@ -159,7 +198,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted * 便
* NOTE便
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " + "CREATE TRIGGER update_note_content_on_delete " +
@ -172,7 +212,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Delete datas belong to note which has been deleted * 便
* 便便
*/ */
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " + "CREATE TRIGGER delete_data_on_delete " +
@ -183,7 +224,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Delete notes belong to folder which has been deleted * 便
* 便
*/ */
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " + "CREATE TRIGGER folder_delete_notes_on_delete " +
@ -194,7 +236,8 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Move notes belong to folder which has been moved to trash folder * 便
* 便
*/ */
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " + "CREATE TRIGGER folder_move_notes_on_trash " +
@ -206,18 +249,38 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/**
*
*
* @param context
*/
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION);
} }
/**
* 便
*
* @param db
*/
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
// 执行创建便签表的SQL语句
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL);
// 重新创建便签表的触发器
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
// 创建系统文件夹
createSystemFolder(db); createSystemFolder(db);
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created");
} }
/**
* 便
*
*
* @param db
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) { private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除已存在的触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,6 +289,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash"); db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
// 创建新的触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER); db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -235,12 +299,19 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
} }
/**
*
*
*
* @param db
*/
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
/** /**
* call record foler for call notes * call record foler for call notes
*/ */
// 创建通话记录文件夹
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
@ -248,6 +319,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* root folder which is default folder * root folder which is default folder
*/ */
// 创建根文件夹(默认文件夹)
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -256,6 +328,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* temporary folder which is used for moving note * temporary folder which is used for moving note
*/ */
// 创建临时文件夹(用于移动便签)
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER); values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -264,29 +337,52 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/** /**
* create trash folder * create trash folder
*/ */
// 创建回收站文件夹
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/**
*
*
* @param db
*/
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
// 执行创建数据表的SQL语句
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL);
// 重新创建数据表的触发器
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
// 创建数据表的索引
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL); db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created");
} }
/**
*
*
*
* @param db
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) { private void reCreateDataTableTriggers(SQLiteDatabase db) {
// 删除已存在的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
// 创建新的触发器
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
} }
/**
* NotesDatabaseHelper
*
* @param context
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context);
@ -294,68 +390,108 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance; return mInstance;
} }
/**
*
*
*
* @param db
*/
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
} }
/**
*
*
*
* @param db
* @param oldVersion
* @param newVersion
*/
@Override @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false; boolean reCreateTriggers = false;
boolean skipV2 = false; boolean skipV2 = false;
// 从版本1升级到版本2
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // 这个升级包含了从v2到v3的升级
oldVersion++; oldVersion++;
} }
// 从版本2升级到版本3
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true; reCreateTriggers = true;
oldVersion++; oldVersion++;
} }
// 从版本3升级到版本4
if (oldVersion == 3) { if (oldVersion == 3) {
upgradeToV4(db); upgradeToV4(db);
oldVersion++; oldVersion++;
} }
// 如果需要,重新创建触发器
if (reCreateTriggers) { if (reCreateTriggers) {
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
} }
// 验证升级是否成功
if (oldVersion != newVersion) { if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails"); + "fails");
} }
} }
/**
* 2
*
*
* @param db
*/
private void upgradeToV2(SQLiteDatabase db) { private void upgradeToV2(SQLiteDatabase db) {
// 删除旧表
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE); db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA); db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
// 创建新表
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
} }
/**
* 3
* Google Tasks ID
*
* @param db
*/
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers // 删除未使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id // 添加Google Tasks ID列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''"); + " TEXT NOT NULL DEFAULT ''");
// add a trash system folder // 添加回收站系统文件夹
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER); values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/**
* 4
*
*
* @param db
*/
private void upgradeToV4(SQLiteDatabase db) { private void upgradeToV4(SQLiteDatabase db) {
// 添加版本列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0"); + " INTEGER NOT NULL DEFAULT 0");
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NotesProvider.java
* : 便便访
* : 便访
*/
package net.micode.notes.data; package net.micode.notes.data;
@ -34,24 +39,41 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* 便
*
* ContentProvider便访
* CRUD
* 便
*/
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
/** URI匹配器用于匹配请求的URI类型 */
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
/** 数据库帮助类实例 */
private NotesDatabaseHelper mHelper; private NotesDatabaseHelper mHelper;
/** 日志标签 */
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
/** 便签表URI类型 */
private static final int URI_NOTE = 1; private static final int URI_NOTE = 1;
/** 单个便签项URI类型 */
private static final int URI_NOTE_ITEM = 2; private static final int URI_NOTE_ITEM = 2;
/** 数据表URI类型 */
private static final int URI_DATA = 3; private static final int URI_DATA = 3;
/** 单个数据项URI类型 */
private static final int URI_DATA_ITEM = 4; private static final int URI_DATA_ITEM = 4;
/** 搜索URI类型 */
private static final int URI_SEARCH = 5; private static final int URI_SEARCH = 5;
/** 搜索建议URI类型 */
private static final int URI_SEARCH_SUGGEST = 6; private static final int URI_SEARCH_SUGGEST = 6;
// 静态初始化块配置URI匹配器
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 添加各种URI匹配规则
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM); mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA); mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
@ -62,8 +84,9 @@ 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. * x'0A'SQLite'\n'
* '\n'
*/ */
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
@ -73,50 +96,79 @@ public class NotesProvider extends ContentProvider {
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
/**
* 便SQL
* 便便便
*/
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?" + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE; + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
/**
*
*
* @return
*/
@Override @Override
public boolean onCreate() { public boolean onCreate() {
// 获取数据库帮助类实例
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
/**
*
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return
*/
@Override @Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
Cursor c = null; Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
// 根据URI类型执行不同的查询操作
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE:
// 查询便签表
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
// 查询单个便签项
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_DATA: case URI_DATA:
// 查询数据表
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM:
// 查询单个数据项
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_SEARCH: case URI_SEARCH:
case URI_SEARCH_SUGGEST: case URI_SEARCH_SUGGEST:
// 处理搜索和搜索建议请求
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
} }
// 获取搜索字符串
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
@ -126,12 +178,14 @@ public class NotesProvider extends ContentProvider {
searchString = uri.getQueryParameter("pattern"); searchString = uri.getQueryParameter("pattern");
} }
// 如果搜索字符串为空则返回null
if (TextUtils.isEmpty(searchString)) { if (TextUtils.isEmpty(searchString)) {
return null; return null;
} }
// 执行搜索查询
try { try {
searchString = String.format("%%%s%%", searchString); searchString = String.format("%%%s%%", searchString); // 添加通配符以进行模糊匹配
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); new String[] { searchString });
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
@ -141,21 +195,35 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// 设置通知URI当数据变化时通知观察者
if (c != null) { if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); c.setNotificationUri(getContext().getContentResolver(), uri);
} }
return c; return c;
} }
/**
*
*
* @param uri URI
* @param values
* @return URI
*/
@Override @Override
public Uri insert(Uri uri, ContentValues values) { public Uri insert(Uri uri, ContentValues values) {
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0; long dataId = 0, noteId = 0, insertedId = 0;
// 根据URI类型执行不同的插入操作
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE:
// 插入便签
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break; break;
case URI_DATA: case URI_DATA:
// 插入数据
if (values.containsKey(DataColumns.NOTE_ID)) { if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID); noteId = values.getAsLong(DataColumns.NOTE_ID);
} else { } else {
@ -166,13 +234,14 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri
// 通知便签URI的观察者
if (noteId > 0) { if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
} }
// Notify the data uri // 通知数据URI的观察者
if (dataId > 0) { if (dataId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
@ -181,22 +250,34 @@ public class NotesProvider extends ContentProvider {
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId);
} }
/**
*
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
*/
@Override @Override
public int delete(Uri uri, String selection, String[] selectionArgs) { public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false; boolean deleteData = false;
// 根据URI类型执行不同的删除操作
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE:
// 删除便签ID必须大于0系统文件夹ID小于等于0
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs); count = db.delete(TABLE.NOTE, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
// 删除单个便签项
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
/** /**
* ID that smaller than 0 is system folder which is not allowed to * ID0
* trash
*/ */
long noteId = Long.valueOf(id); long noteId = Long.valueOf(id);
if (noteId <= 0) { if (noteId <= 0) {
@ -206,10 +287,12 @@ public class NotesProvider extends ContentProvider {
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs); NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA: case URI_DATA:
// 删除数据
count = db.delete(TABLE.DATA, selection, selectionArgs); count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true; deleteData = true;
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM:
// 删除单个数据项
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA, count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs); DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
@ -218,6 +301,8 @@ public class NotesProvider extends ContentProvider {
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// 如果有删除操作,通知观察者
if (count > 0) { if (count > 0) {
if (deleteData) { if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -227,28 +312,44 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
/**
*
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
*/
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0; int count = 0;
String id = null; String id = null;
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false; boolean updateData = false;
// 根据URI类型执行不同的更新操作
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs); // 更新便签表
increaseNoteVersion(-1, selection, selectionArgs); // 增加便签版本号
count = db.update(TABLE.NOTE, values, selection, selectionArgs); count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
// 更新单个便签项
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 增加便签版本号
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA: case URI_DATA:
// 更新数据表
count = db.update(TABLE.DATA, values, selection, selectionArgs); count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true; updateData = true;
break; break;
case URI_DATA_ITEM: case URI_DATA_ITEM:
// 更新单个数据项
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
@ -258,6 +359,7 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// 如果有更新操作,通知观察者
if (count > 0) { if (count > 0) {
if (updateData) { if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
@ -267,11 +369,27 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
/**
*
*
*
* @param selection
* @return
*/
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
} }
/**
* 便
* 便便
*
* @param id 便ID-1使selectionselectionArgs
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
// 构建更新版本号的SQL语句
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
sql.append(TABLE.NOTE); sql.append(TABLE.NOTE);
@ -279,6 +397,7 @@ public class NotesProvider extends ContentProvider {
sql.append(NoteColumns.VERSION); sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append("=" + NoteColumns.VERSION + "+1 ");
// 添加WHERE条件
if (id > 0 || !TextUtils.isEmpty(selection)) { if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE "); sql.append(" WHERE ");
} }
@ -287,19 +406,26 @@ public class NotesProvider extends ContentProvider {
} }
if (!TextUtils.isEmpty(selection)) { if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection; String selectString = id > 0 ? parseSelection(selection) : selection;
// 替换参数占位符
for (String args : selectionArgs) { for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args); selectString = selectString.replaceFirst("\\?", args);
} }
sql.append(selectString); sql.append(selectString);
} }
// 执行SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString());
} }
/**
*
*
* @param uri URI
* @return
*/
@Override @Override
public String getType(Uri uri) { public String getType(Uri uri) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return null; return null;
} }
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : MetaData.java
* : Google Tasks便Google Tasks
* : 便便Google Tasks
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
@ -24,37 +29,71 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* MetaDataTask
* Google Tasks便
*
*/
public class MetaData extends Task { public class MetaData extends Task {
/** 日志标签 */
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName();
/** 关联的Google Task ID */
private String mRelatedGid = null; private String mRelatedGid = null;
/**
*
*
* @param gid Google Task ID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
// 将Google Task ID添加到元数据信息中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid");
} }
// 将元数据JSON字符串设置为任务的备注
setNotes(metaInfo.toString()); setNotes(metaInfo.toString());
// 设置元数据任务的名称为固定值
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
/**
* Google Task ID
*
* @return Google Task ID
*/
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
/**
*
*
* @return truefalse
*/
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }
/**
* JSON
* Google Task ID
*
* @param js JSON
*/
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
// 调用父类方法设置基本内容
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js);
if (getNotes() != null) { if (getNotes() != null) {
try { try {
// 解析备注中的JSON数据
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());
// 获取关联的Google Task ID
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, "failed to get related gid"); Log.w(TAG, "failed to get related gid");
@ -63,17 +102,39 @@ public class MetaData extends Task {
} }
} }
/**
* JSON
*
*
* @param js JSON
* @throws IllegalAccessError
*/
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called // 此方法不应被调用
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
/**
* JSON
*
*
* @return JSONObject JSON
* @throws IllegalAccessError
*/
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
} }
/**
*
* GTaskManager
*
* @param c
* @return
* @throws IllegalAccessError
*/
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called");

@ -14,39 +14,66 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : Node.java
* :
* : TaskListTaskMetaData
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Node
* TaskListTaskMetaData
*
*/
public abstract class Node { public abstract class Node {
/** 同步操作:无操作 */
public static final int SYNC_ACTION_NONE = 0; public static final int SYNC_ACTION_NONE = 0;
/** 同步操作:添加到远程 */
public static final int SYNC_ACTION_ADD_REMOTE = 1; public static final int SYNC_ACTION_ADD_REMOTE = 1;
/** 同步操作:添加到本地 */
public static final int SYNC_ACTION_ADD_LOCAL = 2; 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_REMOTE = 3;
/** 同步操作:从本地删除 */
public static final int SYNC_ACTION_DEL_LOCAL = 4; 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_REMOTE = 5;
/** 同步操作:更新本地 */
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
/** 同步操作:更新冲突 */
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
/** 同步操作:错误 */
public static final int SYNC_ACTION_ERROR = 8; public static final int SYNC_ACTION_ERROR = 8;
/** Google Task ID */
private String mGid; private String mGid;
/** 节点名称 */
private String mName; private String mName;
/** 最后修改时间 */
private long mLastModified; private long mLastModified;
/** 是否已删除 */
private boolean mDeleted; private boolean mDeleted;
/**
*
*
*/
public Node() { public Node() {
mGid = null; mGid = null;
mName = ""; mName = "";
@ -54,46 +81,119 @@ public abstract class Node {
mDeleted = false; mDeleted = false;
} }
/**
* JSON
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
*
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
*
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
*
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent();
/**
*
*
* @param c
* @return
*/
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
/**
* Google Task ID
*
* @param gid Google Task ID
*/
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
/**
*
*
* @param name
*/
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name;
} }
/**
*
*
* @param lastModified
*/
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified;
} }
/**
*
*
* @param deleted
*/
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted;
} }
/**
* Google Task ID
*
* @return Google Task ID
*/
public String getGid() { public String getGid() {
return this.mGid; return this.mGid;
} }
/**
*
*
* @return
*/
public String getName() { public String getName() {
return this.mName; return this.mName;
} }
/**
*
*
* @return
*/
public long getLastModified() { public long getLastModified() {
return this.mLastModified; return this.mLastModified;
} }
/**
*
*
* @return
*/
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : SqlData.java
* : 便SQL
* : 便CRUD
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.content.ContentResolver; import android.content.ContentResolver;
@ -34,43 +39,68 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* SqlData
* 便
* 便
*/
public class SqlData { public class SqlData {
/** 日志标签 */
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName();
/** 无效ID标识 */
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
/** 数据表查询投影列 */
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1, DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3 DataColumns.DATA3
}; };
/** 数据ID列索引 */
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;
/** 数据MIME类型列索引 */
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
/** 数据内容列索引 */
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;
/** 数据DATA1列索引 */
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
/** 数据DATA3列索引 */
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
/** 内容解析器 */
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
/** 是否为新建数据标志 */
private boolean mIsCreate; private boolean mIsCreate;
/** 数据ID */
private long mDataId; private long mDataId;
/** 数据MIME类型 */
private String mDataMimeType; private String mDataMimeType;
/** 数据内容 */
private String mDataContent; private String mDataContent;
/** 数据DATA1值 */
private long mDataContentData1; private long mDataContentData1;
/** 数据DATA3值 */
private String mDataContentData3; private String mDataContentData3;
/** 数据变更值集合 */
private ContentValues mDiffDataValues; private ContentValues mDiffDataValues;
/**
* -
*
* @param context
*/
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
@ -82,6 +112,12 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
* -
*
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
@ -89,6 +125,11 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
*
*
* @param c
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,13 +138,22 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
} }
/**
* JSON
*
*
* @param js JSON
* @throws JSONException JSON
*/
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
// 处理数据ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId); mDiffDataValues.put(DataColumns.ID, dataId);
} }
mDataId = dataId; mDataId = dataId;
// 处理MIME类型
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE; : DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
@ -111,18 +161,21 @@ public class SqlData {
} }
mDataMimeType = dataMimeType; mDataMimeType = dataMimeType;
// 处理内容
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) { if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent); mDiffDataValues.put(DataColumns.CONTENT, dataContent);
} }
mDataContent = dataContent; mDataContent = dataContent;
// 处理DATA1
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) { if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
} }
mDataContentData1 = dataContentData1; mDataContentData1 = dataContentData1;
// 处理DATA3
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3); mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
@ -130,6 +183,12 @@ public class SqlData {
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3;
} }
/**
* JSON
*
* @return JSON
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
@ -144,13 +203,22 @@ public class SqlData {
return js; return js;
} }
/**
*
*
* @param noteId 便ID
* @param validateVersion
* @param version
*/
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
// 新建数据
if (mIsCreate) { if (mIsCreate) {
// 处理无效ID
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); mDiffDataValues.remove(DataColumns.ID);
} }
// 设置关联的便签ID
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try { try {
@ -160,12 +228,15 @@ public class SqlData {
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed");
} }
} else { } else {
// 更新现有数据
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) {
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
// 不验证版本的更新
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null); Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else { } else {
// 验证版本的更新
result = mContentResolver.update(ContentUris.withAppendedId( result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
@ -179,10 +250,16 @@ public class SqlData {
} }
} }
// 清空变更记录并更新状态
mDiffDataValues.clear(); mDiffDataValues.clear();
mIsCreate = false; mIsCreate = false;
} }
/**
* ID
*
* @return ID
*/
public long getId() { public long getId() {
return mDataId; return mDataId;
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : SqlNote.java
* : 便SQL
* : 便便CRUD
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -37,12 +42,19 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/**
* SqlNote
* 便
* 便Google Tasks
*/
public class SqlNote { public class SqlNote {
/** 日志标签 */
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName();
/** 无效ID标识 */
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
/** 便签表查询投影列 */
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -52,76 +64,116 @@ public class SqlNote {
NoteColumns.VERSION NoteColumns.VERSION
}; };
/** ID列索引 */
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
/** 提醒日期列索引 */
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
/** 背景颜色ID列索引 */
public static final int BG_COLOR_ID_COLUMN = 2; public static final int BG_COLOR_ID_COLUMN = 2;
/** 创建日期列索引 */
public static final int CREATED_DATE_COLUMN = 3; public static final int CREATED_DATE_COLUMN = 3;
/** 是否有附件列索引 */
public static final int HAS_ATTACHMENT_COLUMN = 4; public static final int HAS_ATTACHMENT_COLUMN = 4;
/** 修改日期列索引 */
public static final int MODIFIED_DATE_COLUMN = 5; public static final int MODIFIED_DATE_COLUMN = 5;
/** 便签数量列索引 */
public static final int NOTES_COUNT_COLUMN = 6; public static final int NOTES_COUNT_COLUMN = 6;
/** 父ID列索引 */
public static final int PARENT_ID_COLUMN = 7; public static final int PARENT_ID_COLUMN = 7;
/** 摘要列索引 */
public static final int SNIPPET_COLUMN = 8; public static final int SNIPPET_COLUMN = 8;
/** 类型列索引 */
public static final int TYPE_COLUMN = 9; public static final int TYPE_COLUMN = 9;
/** 小部件ID列索引 */
public static final int WIDGET_ID_COLUMN = 10; public static final int WIDGET_ID_COLUMN = 10;
/** 小部件类型列索引 */
public static final int WIDGET_TYPE_COLUMN = 11; public static final int WIDGET_TYPE_COLUMN = 11;
/** 同步ID列索引 */
public static final int SYNC_ID_COLUMN = 12; public static final int SYNC_ID_COLUMN = 12;
/** 本地修改标志列索引 */
public static final int LOCAL_MODIFIED_COLUMN = 13; public static final int LOCAL_MODIFIED_COLUMN = 13;
/** 原始父ID列索引 */
public static final int ORIGIN_PARENT_ID_COLUMN = 14; public static final int ORIGIN_PARENT_ID_COLUMN = 14;
/** Google Task ID列索引 */
public static final int GTASK_ID_COLUMN = 15; public static final int GTASK_ID_COLUMN = 15;
/** 版本列索引 */
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
/** 应用上下文 */
private Context mContext; private Context mContext;
/** 内容解析器 */
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
/** 是否为新建便签标志 */
private boolean mIsCreate; private boolean mIsCreate;
/** 便签ID */
private long mId; private long mId;
/** 提醒日期 */
private long mAlertDate; private long mAlertDate;
/** 背景颜色ID */
private int mBgColorId; private int mBgColorId;
/** 创建日期 */
private long mCreatedDate; private long mCreatedDate;
/** 是否有附件 */
private int mHasAttachment; private int mHasAttachment;
/** 修改日期 */
private long mModifiedDate; private long mModifiedDate;
/** 父ID */
private long mParentId; private long mParentId;
/** 摘要 */
private String mSnippet; private String mSnippet;
/** 类型 */
private int mType; private int mType;
/** 小部件ID */
private int mWidgetId; private int mWidgetId;
/** 小部件类型 */
private int mWidgetType; private int mWidgetType;
/** 原始父ID */
private long mOriginParent; private long mOriginParent;
/** 版本号 */
private long mVersion; private long mVersion;
/** 便签变更值集合 */
private ContentValues mDiffNoteValues; private ContentValues mDiffNoteValues;
/** 便签数据列表 */
private ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
/**
* - 便
*
* @param context
*/
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -143,6 +195,12 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
} }
/**
* - 便
*
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -154,6 +212,12 @@ public class SqlNote {
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/**
* - ID便
*
* @param context
* @param id 便ID
*/
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -163,9 +227,13 @@ public class SqlNote {
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/**
* ID便
*
* @param id 便ID
*/
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;
try { try {
@ -185,6 +253,11 @@ public class SqlNote {
} }
} }
/**
* 便
*
* @param c
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -200,10 +273,15 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
/**
* 便
* 便
*/
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
try { try {
// 查询与当前便签ID关联的所有数据
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] { "(note_id=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
@ -213,6 +291,7 @@ public class SqlNote {
Log.w(TAG, "it seems that the note has not data"); Log.w(TAG, "it seems that the note has not data");
return; return;
} }
// 遍历所有数据项并添加到数据列表中
while (c.moveToNext()) { while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c); SqlData data = new SqlData(mContext, c);
mDataList.add(data); mDataList.add(data);
@ -226,13 +305,22 @@ public class SqlNote {
} }
} }
/**
* JSON便
* JSON便
*
* @param js JSON便
* @return
*/
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
// 获取便签基本信息
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 系统文件夹不允许更新
Log.w(TAG, "cannot set system folder"); Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// for folder we can only update the snnipet and type // 对于文件夹类型,只能更新摘要和类型
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
@ -247,6 +335,7 @@ public class SqlNote {
} }
mType = type; mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
// 对于便签类型,处理所有属性
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) { if (mIsCreate || mId != id) {
@ -331,9 +420,11 @@ public class SqlNote {
} }
mOriginParent = originParent; mOriginParent = originParent;
// 处理便签的数据内容
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null; SqlData sqlData = null;
// 查找是否存在匹配的数据项
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) { for (SqlData temp : mDataList) {
@ -343,11 +434,13 @@ public class SqlNote {
} }
} }
// 如果没有找到匹配的数据项,则创建新的
if (sqlData == null) { if (sqlData == null) {
sqlData = new SqlData(mContext); sqlData = new SqlData(mContext);
mDataList.add(sqlData); mDataList.add(sqlData);
} }
// 设置数据内容
sqlData.setContent(data); sqlData.setContent(data);
} }
} }
@ -359,6 +452,12 @@ public class SqlNote {
return true; return true;
} }
/**
* 便JSON
* 便JSON
*
* @return 便JSON
*/
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -370,6 +469,7 @@ public class SqlNote {
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
// 便签类型,包含所有属性
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate); note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId); note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
@ -384,6 +484,7 @@ public class SqlNote {
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent); note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
// 添加便签的数据内容
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent(); JSONObject data = sqlData.getContent();
@ -393,6 +494,7 @@ public class SqlNote {
} }
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray); js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) { } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
// 文件夹或系统类型,只包含基本属性
note.put(NoteColumns.ID, mId); note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType); note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet); note.put(NoteColumns.SNIPPET, mSnippet);
@ -407,45 +509,92 @@ public class SqlNote {
return null; return null;
} }
/**
* 便ID
*
* @param id 便ID
*/
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }
/**
* 便Google Task ID
*
* @param gid Google Task ID
*/
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
/**
* 便ID
*
* @param syncId ID
*/
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
/**
*
* 便
*/
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
/**
* 便ID
*
* @return 便ID
*/
public long getId() { public long getId() {
return mId; return mId;
} }
/**
* 便ID
*
* @return 便ID
*/
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
/**
* 便
*
* @return 便
*/
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
/**
* 便
*
* @return 便truefalse
*/
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
/**
* 便
*
*
* @param validateVersion
*/
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) {
// 处理新建便签
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID); mDiffNoteValues.remove(NoteColumns.ID);
} }
// 插入新便签到数据库
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues); Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try { try {
mId = Long.valueOf(uri.getPathSegments().get(1)); mId = Long.valueOf(uri.getPathSegments().get(1));
@ -457,25 +606,30 @@ public class SqlNote {
throw new IllegalStateException("Create thread id failed"); throw new IllegalStateException("Create thread id failed");
} }
// 提交便签关联的数据内容
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1); sqlData.commit(mId, false, -1);
} }
} }
} else { } else {
// 处理更新便签
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) { if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note"); Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id"); throw new IllegalStateException("Try to update note with invalid id");
} }
if (mDiffNoteValues.size() > 0) { if (mDiffNoteValues.size() > 0) {
// 更新版本号
mVersion ++; mVersion ++;
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
// 不验证版本的更新
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] { + NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
}); });
} else { } else {
// 验证版本的更新,防止冲突
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] { new String[] {
@ -487,6 +641,7 @@ public class SqlNote {
} }
} }
// 提交便签关联的数据内容
if (mType == Notes.TYPE_NOTE) { if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) { for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion); sqlData.commit(mId, validateVersion, mVersion);
@ -494,11 +649,12 @@ public class SqlNote {
} }
} }
// refresh local info // 刷新本地信息
loadFromCursor(mId); loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
// 清空变更记录并更新状态
mDiffNoteValues.clear(); mDiffNoteValues.clear();
mIsCreate = false; mIsCreate = false;
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : Task.java
* : Google Tasks
* : Google TasksGoogle Tasks
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
@ -31,20 +36,34 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Google Tasks
*
* NodeGoogle Tasks
*
*/
public class Task extends Node { public class Task extends Node {
/** 日志标签 */
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName();
/** 任务完成状态 */
private boolean mCompleted; private boolean mCompleted;
/** 任务备注内容 */
private String mNotes; private String mNotes;
/** 任务元数据信息存储为JSON格式 */
private JSONObject mMetaInfo; private JSONObject mMetaInfo;
/** 前一个兄弟任务 */
private Task mPriorSibling; private Task mPriorSibling;
/** 所属任务列表 */
private TaskList mParent; private TaskList mParent;
/**
*
*/
public Task() { public Task() {
super(); super();
mCompleted = false; mCompleted = false;
@ -54,6 +73,13 @@ public class Task extends Node {
mMetaInfo = null; mMetaInfo = null;
} }
/**
* JSON
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -103,6 +129,13 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -135,6 +168,12 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
*
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
@ -175,6 +214,11 @@ public class Task extends Node {
} }
} }
/**
* JSON
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@ -182,14 +226,17 @@ public class Task extends Node {
} }
try { try {
// 获取便签和数据信息
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 验证便签类型
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type");
return; return;
} }
// 查找便签内容并设置为任务名称
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
@ -204,16 +251,22 @@ public class Task extends Node {
} }
} }
/**
* JSON
*
* @return JSONnull
*/
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
String name = getName(); String name = getName();
try { try {
if (mMetaInfo == null) { if (mMetaInfo == null) {
// new task created from web // 从网络创建的新任务
if (name == null) { if (name == null) {
Log.w(TAG, "the note seems to be an empty one"); Log.w(TAG, "the note seems to be an empty one");
return null; return null;
} }
// 创建新的JSON数据结构
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
@ -225,10 +278,11 @@ public class Task extends Node {
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js; return js;
} else { } else {
// synced task // 已同步的任务
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 更新便签内容
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
@ -247,6 +301,11 @@ public class Task extends Node {
} }
} }
/**
*
*
* @param metaData
*/
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) {
try { try {
@ -258,8 +317,15 @@ public class Task extends Node {
} }
} }
/**
*
*
* @param c 便
* @return
*/
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
// 获取便签元数据信息
JSONObject noteInfo = null; JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) { if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -275,31 +341,32 @@ public class Task extends Node {
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
// validate the note id now // 验证便签ID
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match"); Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // 本地没有更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // 两端都没有更新
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local // 应用远程更新到本地
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// validate gtask id // 验证Google Tasks ID
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // 仅本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// 两端都有修改,存在冲突
return SYNC_ACTION_UPDATE_CONFLICT; return SYNC_ACTION_UPDATE_CONFLICT;
} }
} }
@ -311,41 +378,85 @@ public class Task extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/**
*
*
* @return truefalse
*/
public boolean isWorthSaving() { public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0); || (getNotes() != null && getNotes().trim().length() > 0);
} }
/**
*
*
* @param completed
*/
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }
/**
*
*
* @param notes
*/
public void setNotes(String notes) { public void setNotes(String notes) {
this.mNotes = notes; this.mNotes = notes;
} }
/**
*
*
* @param priorSibling
*/
public void setPriorSibling(Task priorSibling) { public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; this.mPriorSibling = priorSibling;
} }
/**
*
*
* @param parent
*/
public void setParent(TaskList parent) { public void setParent(TaskList parent) {
this.mParent = parent; this.mParent = parent;
} }
/**
*
*
* @return
*/
public boolean getCompleted() { public boolean getCompleted() {
return this.mCompleted; return this.mCompleted;
} }
/**
*
*
* @return
*/
public String getNotes() { public String getNotes() {
return this.mNotes; return this.mNotes;
} }
/**
*
*
* @return
*/
public Task getPriorSibling() { public Task getPriorSibling() {
return this.mPriorSibling; return this.mPriorSibling;
} }
/**
*
*
* @return
*/
public TaskList getParent() { public TaskList getParent() {
return this.mParent; return this.mParent;
} }
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : TaskList.java
* : Google Tasks
* :
*/
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
@ -29,35 +34,56 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/**
*
*
* Google TasksNode
*
*
*
* 便便
*/
public class TaskList extends Node { public class TaskList extends Node {
/** 日志标签 */
private static final String TAG = TaskList.class.getSimpleName(); private static final String TAG = TaskList.class.getSimpleName();
/** 任务列表索引 */
private int mIndex; private int mIndex;
/** 子任务列表 */
private ArrayList<Task> mChildren; private ArrayList<Task> mChildren;
/**
*
*
*/
public TaskList() { public TaskList() {
super(); super();
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>();
mIndex = 1; mIndex = 1;
} }
/**
* JSON
*
* @param actionId ID
* @return JSON
*/
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// action_type // 设置操作类型为创建
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// action_id // 设置操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// index // 设置索引
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// entity_delta // 设置实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
@ -74,21 +100,27 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
*
* @param actionId ID
* @return JSON
*/
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// action_type // 设置操作类型为更新
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id // 设置操作ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id // 设置任务列表ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta // 设置实体数据
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
@ -103,20 +135,25 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
*
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// id // 设置ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// last_modified // 设置最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// name // 设置名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
@ -129,6 +166,11 @@ public class TaskList extends Node {
} }
} }
/**
* JSON
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -137,6 +179,7 @@ public class TaskList extends Node {
try { try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 根据便签类型设置任务列表名称
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
@ -157,11 +200,17 @@ public class TaskList extends Node {
} }
} }
/**
* JSON
*
* @return JSON
*/
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject();
// 提取文件夹名称并设置类型
String folderName = getName(); String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
@ -183,28 +232,35 @@ public class TaskList extends Node {
} }
} }
/**
*
*
*
* @param c
* @return
*/
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update // 本地未修改
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side // 双方都未更新
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// apply remote to local // 应用远程更新到本地
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// validate gtask id // 验证Google任务ID
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only // 仅本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// for folder conflicts, just apply local modification // 对于文件夹冲突,应用本地修改
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
@ -216,16 +272,27 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/**
*
*
* @return
*/
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
/**
*
*
* @param task
* @return
*/
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task); ret = mChildren.add(task);
if (ret) { if (ret) {
// need to set prior sibling and parent // 设置任务的前一个兄弟任务和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1));
task.setParent(this); task.setParent(this);
@ -234,6 +301,13 @@ public class TaskList extends Node {
return ret; return ret;
} }
/**
*
*
* @param task
* @param index
* @return
*/
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index");
@ -244,7 +318,7 @@ public class TaskList extends Node {
if (task != null && pos == -1) { if (task != null && pos == -1) {
mChildren.add(index, task); mChildren.add(index, task);
// update the task list // 更新任务列表关系
Task preTask = null; Task preTask = null;
Task afterTask = null; Task afterTask = null;
if (index != 0) if (index != 0)
@ -260,6 +334,12 @@ public class TaskList extends Node {
return true; return true;
} }
/**
*
*
* @param task
* @return
*/
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task);
@ -267,11 +347,11 @@ public class TaskList extends Node {
ret = mChildren.remove(task); ret = mChildren.remove(task);
if (ret) { if (ret) {
// reset prior sibling and parent // 重置前一个兄弟任务和父任务
task.setPriorSibling(null); task.setPriorSibling(null);
task.setParent(null); task.setParent(null);
// update the task list // 更新任务列表
if (index != mChildren.size()) { if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling( mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1)); index == 0 ? null : mChildren.get(index - 1));
@ -281,6 +361,13 @@ public class TaskList extends Node {
return ret; return ret;
} }
/**
*
*
* @param task
* @param index
* @return
*/
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
@ -299,6 +386,12 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
} }
/**
* GoogleID
*
* @param gid GoogleID
* @return null
*/
public Task findChildTaskByGid(String gid) { public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) { for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i); Task t = mChildren.get(i);
@ -309,10 +402,22 @@ public class TaskList extends Node {
return null; return null;
} }
/**
*
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }
/**
*
*
* @param index
* @return null
*/
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,6 +426,12 @@ public class TaskList extends Node {
return mChildren.get(index); return mChildren.get(index);
} }
/**
* GoogleID
*
* @param gid GoogleID
* @return null
*/
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) { for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))
@ -329,14 +440,29 @@ public class TaskList extends Node {
return null; return null;
} }
/**
*
*
* @return
*/
public ArrayList<Task> getChildTaskList() { public ArrayList<Task> getChildTaskList() {
return this.mChildren; return this.mChildren;
} }
/**
*
*
* @param index
*/
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index;
} }
/**
*
*
* @return
*/
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex;
} }

@ -14,19 +14,46 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : ActionFailureException.java
* : Google Tasks
* : Google Tasks
*/
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
*
*
* RuntimeExceptionGoogle Tasks
*
*/
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
/** 序列化版本ID */
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
/**
*
*
*/
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
/**
*
*
* @param paramString
*/
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString);
} }
/**
*
*
* @param paramString
* @param paramThrowable
*/
public ActionFailureException(String paramString, Throwable paramThrowable) { public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }

@ -14,19 +14,46 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NetworkFailureException.java
* : Google Tasks
* : Google Tasks
*/
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
*
*
* ExceptionGoogle Tasks
*
*/
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
/** 序列化版本ID */
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
/**
*
*
*/
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
/**
*
*
* @param paramString
*/
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString);
} }
/**
*
*
* @param paramString
* @param paramThrowable
*/
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }

@ -1,4 +1,3 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
@ -15,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : GTaskASyncTask.java
* : Google Tasks线
* : UI线
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Notification; import android.app.Notification;
@ -28,23 +32,52 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/**
* Google Tasks
*
* AsyncTask线Google Tasks
* UI线
*
*
* 1. 线
* 2.
* 3.
* 4.
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
/** 同步通知的唯一ID */
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
/**
*
*
*/
public interface OnCompleteListener { public interface OnCompleteListener {
/**
*
*/
void onComplete(); void onComplete();
} }
/** 应用上下文 */
private Context mContext; private Context mContext;
/** 通知管理器 */
private NotificationManager mNotifiManager; private NotificationManager mNotifiManager;
/** Google Tasks同步管理器 */
private GTaskManager mTaskManager; private GTaskManager mTaskManager;
/** 同步完成监听器 */
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
/**
*
*
* @param context
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
@ -53,16 +86,31 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
/**
*
* GTaskManager
*/
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
/**
*
*
* @param message
*/
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
} }
/**
*
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent; PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
@ -74,7 +122,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE); NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
} }
// Use modern notification builder (API 21+ support) // 使用现代通知构建器支持API 21+
Notification notification = new Notification.Builder(mContext) Notification notification = new Notification.Builder(mContext)
.setContentTitle(mContext.getString(R.string.app_name)) .setContentTitle(mContext.getString(R.string.app_name))
.setContentText(content) .setContentText(content)
@ -87,6 +135,12 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
/**
* 线
*
* @param unused 使
* @return
*/
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
@ -94,6 +148,12 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
/**
*
* UI线
*
* @param progress
*/
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
@ -102,6 +162,12 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
} }
/**
*
*
*
* @param result
*/
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : GTaskClient.java
* : Google TasksGoogle Tasks API
* : Google Tasks
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.accounts.Account; import android.accounts.Account;
@ -60,36 +65,65 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
/**
* Google Tasks
*
* Google Tasks API
* 使Google Tasks
*
*
* 1. Google
* 2.
* 3.
* 4. HTTP
*/
public class GTaskClient { public class GTaskClient {
/** 日志标签 */
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
/** Google Tasks基础URL */
private static final String GTASK_URL = "https://mail.google.com/tasks/"; private static final String GTASK_URL = "https://mail.google.com/tasks/";
/** Google Tasks GET请求URL */
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig"; private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
/** Google Tasks POST请求URL */
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig"; private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
/** 单例实例 */
private static GTaskClient mInstance = null; private static GTaskClient mInstance = null;
/** HTTP客户端 */
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
/** GET请求URL */
private String mGetUrl; private String mGetUrl;
/** POST请求URL */
private String mPostUrl; private String mPostUrl;
/** 客户端版本号 */
private long mClientVersion; private long mClientVersion;
/** 登录状态标志 */
private boolean mLoggedin; private boolean mLoggedin;
/** 最后登录时间 */
private long mLastLoginTime; private long mLastLoginTime;
/** 操作ID计数器 */
private int mActionId; private int mActionId;
/** Google账户 */
private Account mAccount; private Account mAccount;
/** 更新操作数组 */
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
/**
* Google Tasks
* getInstance
*/
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -102,6 +136,11 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
/**
* GTaskClient
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -109,26 +148,33 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
/**
* Google Tasks
*
* @param activity
* @return
*/
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // 检查登录会话是否过期5分钟
// then we need to re-login
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// need to re-login after account switch // 切换账户后需要重新登录
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
// 如果已登录,直接返回
if (mLoggedin) { if (mLoggedin) {
Log.d(TAG, "already logged in"); Log.d(TAG, "already logged in");
return true; return true;
} }
// 更新最后登录时间并获取授权令牌
mLastLoginTime = System.currentTimeMillis(); mLastLoginTime = System.currentTimeMillis();
String authToken = loginGoogleAccount(activity, false); String authToken = loginGoogleAccount(activity, false);
if (authToken == null) { if (authToken == null) {
@ -136,7 +182,7 @@ public class GTaskClient {
return false; return false;
} }
// login with custom domain if necessary // 如果是自定义域名账户,需要特殊处理
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) { .endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -151,7 +197,7 @@ public class GTaskClient {
} }
} }
// try to login with google official url // 尝试使用官方URL登录
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -164,16 +210,25 @@ public class GTaskClient {
return true; return true;
} }
/**
* Google
*
* @param activity
* @param invalidateToken 使
* @return null
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google"); Account[] accounts = accountManager.getAccountsByType("com.google");
// 检查是否有可用的Google账户
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account");
return null; return null;
} }
// 根据设置中的账户名找到对应账户
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null; Account account = null;
for (Account a : accounts) { for (Account a : accounts) {
@ -189,13 +244,14 @@ public class GTaskClient {
return null; return null;
} }
// get the token now // 获取授权令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
try { try {
Bundle authTokenBundle = accountManagerFuture.getResult(); Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN); authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
if (invalidateToken) { if (invalidateToken) {
// 使令牌失效并重新获取
accountManager.invalidateAuthToken("com.google", authToken); accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false); loginGoogleAccount(activity, false);
} }
@ -207,10 +263,16 @@ public class GTaskClient {
return authToken; return authToken;
} }
/**
* Google Tasks
*
* @param activity
* @param authToken
* @return
*/
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the // 如果令牌过期,使其失效并重新尝试
// token and try again
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
@ -225,7 +287,14 @@ public class GTaskClient {
return true; return true;
} }
/**
* 使Google Tasks
*
* @param authToken
* @return
*/
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
// 设置HTTP连接参数
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
HttpParams httpParameters = new BasicHttpParams(); HttpParams httpParameters = new BasicHttpParams();
@ -236,14 +305,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask // 登录Google Tasks
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the cookie now // 获取认证Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -255,7 +324,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie");
} }
// get the client version // 获取客户端版本号
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -272,7 +341,7 @@ public class GTaskClient {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} catch (Exception e) { } catch (Exception e) {
// simply catch all exceptions // 捕获所有异常
Log.e(TAG, "httpget gtask_url failed"); Log.e(TAG, "httpget gtask_url failed");
return false; return false;
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : GTaskManager.java
* : Google Tasks便Google Tasks
* : Google Tasks
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Activity; import android.app.Activity;
@ -47,46 +52,80 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
/**
* Google Tasks
*
* 便Google Tasks
*
*
*
* 1. Google
* 2.
* 3.
* 4.
*/
public class GTaskManager { public class GTaskManager {
/** 日志标签 */
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();
/** 同步状态:成功 */
public static final int STATE_SUCCESS = 0; public static final int STATE_SUCCESS = 0;
/** 同步状态:网络错误 */
public static final int STATE_NETWORK_ERROR = 1; public static final int STATE_NETWORK_ERROR = 1;
/** 同步状态:内部错误 */
public static final int STATE_INTERNAL_ERROR = 2; public static final int STATE_INTERNAL_ERROR = 2;
/** 同步状态:同步进行中 */
public static final int STATE_SYNC_IN_PROGRESS = 3; public static final int STATE_SYNC_IN_PROGRESS = 3;
/** 同步状态:同步已取消 */
public static final int STATE_SYNC_CANCELLED = 4; public static final int STATE_SYNC_CANCELLED = 4;
/** 单例实例 */
private static GTaskManager mInstance = null; private static GTaskManager mInstance = null;
/** 活动上下文,用于获取授权令牌 */
private Activity mActivity; private Activity mActivity;
/** 应用上下文 */
private Context mContext; private Context mContext;
/** 内容解析器,用于访问数据库 */
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
/** 同步状态标志 */
private boolean mSyncing; private boolean mSyncing;
/** 取消同步标志 */
private boolean mCancelled; private boolean mCancelled;
/** Google任务列表映射表 <任务列表ID, TaskList对象> */
private HashMap<String, TaskList> mGTaskListHashMap; private HashMap<String, TaskList> mGTaskListHashMap;
/** Google任务节点映射表 <节点ID, Node对象> */
private HashMap<String, Node> mGTaskHashMap; private HashMap<String, Node> mGTaskHashMap;
/** 元数据映射表 <关联ID, 元数据对象> */
private HashMap<String, MetaData> mMetaHashMap; private HashMap<String, MetaData> mMetaHashMap;
/** 元数据任务列表 */
private TaskList mMetaList; private TaskList mMetaList;
/** 本地已删除ID集合 */
private HashSet<Long> mLocalDeleteIdMap; private HashSet<Long> mLocalDeleteIdMap;
/** Google ID到本地笔记ID的映射 */
private HashMap<String, Long> mGidToNid; private HashMap<String, Long> mGidToNid;
/** 本地笔记ID到Google ID的映射 */
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
/**
*
* getInstance
*/
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false;
mCancelled = false; mCancelled = false;
@ -99,6 +138,11 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>();
} }
/**
* GTaskManager
*
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
@ -106,16 +150,32 @@ public class GTaskManager {
return mInstance; return mInstance;
} }
/**
*
* Google
*
* @param activity
*/
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken // used for getting authtoken
mActivity = activity; mActivity = activity;
} }
/**
*
*
* @param context
* @param asyncTask
* @return
*/
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
// 检查是否已有同步进行中
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS; return STATE_SYNC_IN_PROGRESS;
} }
// 初始化同步环境
mContext = context; mContext = context;
mContentResolver = mContext.getContentResolver(); mContentResolver = mContext.getContentResolver();
mSyncing = true; mSyncing = true;
@ -128,34 +188,39 @@ public class GTaskManager {
mNidToGid.clear(); mNidToGid.clear();
try { try {
// 获取GTaskClient实例并重置更新数组
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); client.resetUpdateArray();
// login google task // 登录Google Tasks服务
if (!mCancelled) { if (!mCancelled) {
if (!client.login(mActivity)) { if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed"); throw new NetworkFailureException("login google task failed");
} }
} }
// get the task list from google // 获取远程任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); initGTaskList();
// do content sync work // 执行内容同步
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent(); syncContent();
} catch (NetworkFailureException e) { } catch (NetworkFailureException e) {
// 处理网络错误
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR; return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) { } catch (ActionFailureException e) {
// 处理内部错误
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} catch (Exception e) { } catch (Exception e) {
// 处理其他异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
return STATE_INTERNAL_ERROR; return STATE_INTERNAL_ERROR;
} finally { } finally {
// 清理资源
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -165,29 +230,40 @@ public class GTaskManager {
mSyncing = false; mSyncing = false;
} }
// 返回同步结果
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
/**
* Google
*
*
* @throws NetworkFailureException
*/
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
// 检查是否已取消同步
if (mCancelled) if (mCancelled)
return; return;
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
try { try {
// 获取所有任务列表
JSONArray jsTaskLists = client.getTaskLists(); JSONArray jsTaskLists = client.getTaskLists();
// init meta list first // 首先初始化元数据列表
mMetaList = null; mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 查找元数据列表
if (name if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) { .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object); mMetaList.setContentByRemoteJSON(object);
// load meta data // 加载元数据
JSONArray jsMetas = client.getTaskList(gid); JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) { for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j); object = (JSONObject) jsMetas.getJSONObject(j);
@ -203,7 +279,7 @@ public class GTaskManager {
} }
} }
// create meta list if not existed // 如果元数据列表不存在,则创建一个
if (mMetaList == null) { if (mMetaList == null) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -211,12 +287,13 @@ public class GTaskManager {
GTaskClient.getInstance().createTaskList(mMetaList); GTaskClient.getInstance().createTaskList(mMetaList);
} }
// init task list // 初始化任务列表
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME); String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 处理MIUI文件夹前缀的任务列表排除元数据列表
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) { + GTaskStringUtils.FOLDER_META)) {
@ -225,7 +302,7 @@ public class GTaskManager {
mGTaskListHashMap.put(gid, tasklist); mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist);
// load tasks // 加载任务
JSONArray jsTasks = client.getTaskList(gid); JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) { for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j); object = (JSONObject) jsTasks.getJSONObject(j);
@ -241,6 +318,7 @@ public class GTaskManager {
} }
} }
} catch (JSONException e) { } catch (JSONException e) {
// 处理JSON解析异常
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
e.printStackTrace(); e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed"); throw new ActionFailureException("initGTaskList: handing JSONObject failed");

@ -14,6 +14,12 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : GTaskSyncService.java
* : Google Tasks便Google Tasks
* : 便Google Tasks
* :
*/
package net.micode.notes.gtask.remote; package net.micode.notes.gtask.remote;
import android.app.Activity; import android.app.Activity;
@ -23,43 +29,85 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
/**
* Google Tasks
*
* 便Google Tasks
* 广
*
*/
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
/** Intent参数同步动作类型 */
public final static String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
/** 同步动作:开始同步 */
public final static int ACTION_START_SYNC = 0; public final static int ACTION_START_SYNC = 0;
/** 同步动作:取消同步 */
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_CANCEL_SYNC = 1;
/** 同步动作:无效动作 */
public final static int ACTION_INVALID = 2; public final static int ACTION_INVALID = 2;
/** 广播Action名称用于通知同步状态 */
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service"; public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
/** 广播参数:是否正在同步 */
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing"; public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
/** 广播参数:同步进度消息 */
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// /** 同步任务对象 */
// private static GTaskASyncTask mSyncTask = null; // private static GTaskASyncTask mSyncTask = null;
/** 同步进度消息 */
private static String mSyncProgress = ""; private static String mSyncProgress = "";
/**
*
*
*
*/
private void startSync() { private void startSync() {
// Temporarily disabled sync functionality // Temporarily disabled sync functionality
sendBroadcast("Sync functionality temporarily disabled"); sendBroadcast("Sync functionality temporarily disabled");
stopSelf(); stopSelf();
} }
/**
*
*
*
*/
private void cancelSync() { private void cancelSync() {
// Temporarily disabled sync functionality // Temporarily disabled sync functionality
sendBroadcast("Sync cancelled"); sendBroadcast("Sync cancelled");
} }
/**
*
*
*
*/
@Override @Override
public void onCreate() { public void onCreate() {
// Temporarily disabled sync functionality // Temporarily disabled sync functionality
} }
/**
*
*
* Intent
*
* @param intent Intent
* @param flags
* @param startId ID
* @return
*/
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
// 从Intent中获取同步动作类型
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
@ -77,23 +125,48 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
/**
*
*
*
*/
@Override @Override
public void onLowMemory() { public void onLowMemory() {
// Temporarily disabled sync functionality // Temporarily disabled sync functionality
} }
/**
*
*
* @param intent Intent
* @return null
*/
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
/**
* 广
*
* @param msg
*/
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
// 保存同步进度消息
mSyncProgress = msg; mSyncProgress = msg;
// 创建广播Intent
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
// 设置同步状态参数
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, false); intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, false);
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
// 发送广播
sendBroadcast(intent); sendBroadcast(intent);
} }
/**
*
*
* @param activity
*/
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
// Temporarily disabled sync functionality // Temporarily disabled sync functionality
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
@ -101,16 +174,31 @@ public class GTaskSyncService extends Service {
activity.startService(intent); activity.startService(intent);
} }
/**
*
*
* @param context
*/
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);
} }
/**
*
*
* @return false
*/
public static boolean isSyncing() { public static boolean isSyncing() {
return false; // Temporarily disabled sync functionality return false; // Temporarily disabled sync functionality
} }
/**
*
*
* @return
*/
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : Note.java
* : 便便
* : 便CRUD
*/
package net.micode.notes.model; package net.micode.notes.model;
import android.content.ContentProviderOperation; import android.content.ContentProviderOperation;
import android.content.ContentProviderResult; import android.content.ContentProviderResult;
@ -33,16 +38,31 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
/**
* 便
*
* 便便便
* 便便
*/
public class Note { public class Note {
/** 便签差异值,用于记录便签属性的更改 */
private ContentValues mNoteDiffValues; private ContentValues mNoteDiffValues;
/** 便签数据,包括文本数据和通话记录数据 */
private NoteData mNoteData; private NoteData mNoteData;
/** 日志标签 */
private static final String TAG = "Note"; private static final String TAG = "Note";
/** /**
* Create a new note id for adding a new note to databases * 便便ID
*
* @param context
* @param folderId ID便
* @return 便ID
*/ */
public static synchronized long getNewNoteId(Context context, long folderId) { public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database // 创建便签基本信息
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis(); long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime); values.put(NoteColumns.CREATED_DATE, createdTime);
@ -50,8 +70,11 @@ public class Note {
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId); values.put(NoteColumns.PARENT_ID, folderId);
// 插入便签记录并获取URI
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
// 从URI中提取便签ID
long noteId = 0; long noteId = 0;
try { try {
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1));
@ -59,52 +82,106 @@ public class Note {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0; noteId = 0;
} }
// 验证便签ID有效性
if (noteId == -1) { if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId); throw new IllegalStateException("Wrong note id:" + noteId);
} }
return noteId; return noteId;
} }
/**
* 便
*/
public Note() { public Note() {
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
} }
/**
* 便
*
* @param key
* @param value
*/
public void setNoteValue(String key, String value) { public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value); mNoteDiffValues.put(key, value);
// 标记为本地已修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新修改时间
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
/**
* 便
*
* @param key
* @param value
*/
public void setTextData(String key, String value) { public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); mNoteData.setTextData(key, value);
} }
/**
* ID
*
* @param id ID
*/
public void setTextDataId(long id) { public void setTextDataId(long id) {
mNoteData.setTextDataId(id); mNoteData.setTextDataId(id);
} }
/**
* ID
*
* @return ID
*/
public long getTextDataId() { public long getTextDataId() {
return mNoteData.mTextDataId; return mNoteData.mTextDataId;
} }
/**
* ID
*
* @param id ID
*/
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
} }
/**
*
*
* @param key
* @param value
*/
public void setCallData(String key, String value) { public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); mNoteData.setCallData(key, value);
} }
/**
* 便
*
* @return 便truefalse
*/
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
/**
* 便
*
* @param context
* @param noteId 便ID
* @return truefalse
*/
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
// 验证便签ID有效性
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
// 如果没有本地修改,直接返回成功
if (!isLocalModified()) { if (!isLocalModified()) {
return true; return true;
} }
@ -114,6 +191,7 @@ public class Note {
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info * note data info
*/ */
// 更新便签基本信息
if (context.getContentResolver().update( if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) { null) == 0) {
@ -122,6 +200,7 @@ public class Note {
} }
mNoteDiffValues.clear(); mNoteDiffValues.clear();
// 更新便签内容数据
if (mNoteData.isLocalModified() if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) { && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false; return false;
@ -130,17 +209,30 @@ public class Note {
return true; return true;
} }
/**
* 便
*
* 便
*/
private class NoteData { private class NoteData {
/** 文本数据ID */
private long mTextDataId; private long mTextDataId;
/** 文本数据值 */
private ContentValues mTextDataValues; private ContentValues mTextDataValues;
/** 通话记录数据ID */
private long mCallDataId; private long mCallDataId;
/** 通话记录数据值 */
private ContentValues mCallDataValues; private ContentValues mCallDataValues;
/** 日志标签 */
private static final String TAG = "NoteData"; private static final String TAG = "NoteData";
/**
* 便
*/
public NoteData() { public NoteData() {
mTextDataValues = new ContentValues(); mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); mCallDataValues = new ContentValues();
@ -148,10 +240,20 @@ public class Note {
mCallDataId = 0; mCallDataId = 0;
} }
/**
*
*
* @return truefalse
*/
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
/**
* ID
*
* @param id ID
*/
void setTextDataId(long id) { void setTextDataId(long id) {
if(id <= 0) { if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0"); throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +261,11 @@ public class Note {
mTextDataId = id; mTextDataId = id;
} }
/**
* ID
*
* @param id ID
*/
void setCallDataId(long id) { void setCallDataId(long id) {
if (id <= 0) { if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0"); throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,32 +273,59 @@ public class Note {
mCallDataId = id; mCallDataId = id;
} }
/**
*
*
* @param key
* @param value
*/
void setCallData(String key, String value) { void setCallData(String key, String value) {
mCallDataValues.put(key, value); mCallDataValues.put(key, value);
// 标记便签为本地已修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新修改时间
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
/**
*
*
* @param key
* @param value
*/
void setTextData(String key, String value) { void setTextData(String key, String value) {
mTextDataValues.put(key, value); mTextDataValues.put(key, value);
// 标记便签为本地已修改
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新修改时间
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
} }
/**
* 便ContentResolver
*
* @param context
* @param noteId 便ID
* @return 便URInull
*/
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety * Check for safety
*/ */
// 验证便签ID有效性
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
} }
// 创建批量操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null; ContentProviderOperation.Builder builder = null;
// 处理文本数据
if(mTextDataValues.size() > 0) { if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId); mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) { if (mTextDataId == 0) {
// 新建文本数据
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues); mTextDataValues);
@ -203,6 +337,7 @@ public class Note {
return null; return null;
} }
} else { } else {
// 更新现有文本数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId)); Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues); builder.withValues(mTextDataValues);
@ -211,9 +346,11 @@ public class Note {
mTextDataValues.clear(); mTextDataValues.clear();
} }
// 处理通话记录数据
if(mCallDataValues.size() > 0) { if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) { if (mCallDataId == 0) {
// 新建通话记录数据
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues); mCallDataValues);
@ -225,6 +362,7 @@ public class Note {
return null; return null;
} }
} else { } else {
// 更新现有通话记录数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId( builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId)); Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues); builder.withValues(mCallDataValues);
@ -233,6 +371,7 @@ public class Note {
mCallDataValues.clear(); mCallDataValues.clear();
} }
// 执行批量操作
if (operationList.size() > 0) { if (operationList.size() > 0) {
try { try {
ContentProviderResult[] results = context.getContentResolver().applyBatch( ContentProviderResult[] results = context.getContentResolver().applyBatch(

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : WorkingNote.java
* : 便UI
* : 便便
*/
package net.micode.notes.model; package net.micode.notes.model;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -31,37 +36,59 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote; import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* 便
*
* 便
* 便访
* UI便
*/
public class WorkingNote { public class WorkingNote {
// Note for the working note /** 底层便签数据模型 */
private Note mNote; private Note mNote;
// Note Id
/** 便签ID */
private long mNoteId; private long mNoteId;
// Note content
/** 便签内容 */
private String mContent; private String mContent;
// Note mode
/** 便签模式(普通模式或清单模式) */
private int mMode; private int mMode;
/** 提醒时间 */
private long mAlertDate; private long mAlertDate;
/** 修改时间 */
private long mModifiedDate; private long mModifiedDate;
/** 背景颜色ID */
private int mBgColorId; private int mBgColorId;
/** 小部件ID */
private int mWidgetId; private int mWidgetId;
/** 小部件类型 */
private int mWidgetType; private int mWidgetType;
/** 所属文件夹ID */
private long mFolderId; private long mFolderId;
/** 上下文环境 */
private Context mContext; private Context mContext;
/** 日志标签 */
private static final String TAG = "WorkingNote"; private static final String TAG = "WorkingNote";
/** 是否已删除标记 */
private boolean mIsDeleted; private boolean mIsDeleted;
/** 便签设置变更监听器 */
private NoteSettingChangedListener mNoteSettingStatusListener; private NoteSettingChangedListener mNoteSettingStatusListener;
/**
* 便便
*/
public static final String[] DATA_PROJECTION = new String[] { public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, DataColumns.ID,
DataColumns.CONTENT, DataColumns.CONTENT,
@ -72,6 +99,9 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
/**
* 便便
*/
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -81,27 +111,42 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE NoteColumns.MODIFIED_DATE
}; };
/** 数据ID列索引 */
private static final int DATA_ID_COLUMN = 0; private static final int DATA_ID_COLUMN = 0;
/** 数据内容列索引 */
private static final int DATA_CONTENT_COLUMN = 1; private static final int DATA_CONTENT_COLUMN = 1;
/** 数据MIME类型列索引 */
private static final int DATA_MIME_TYPE_COLUMN = 2; private static final int DATA_MIME_TYPE_COLUMN = 2;
/** 数据模式列索引 */
private static final int DATA_MODE_COLUMN = 3; private static final int DATA_MODE_COLUMN = 3;
/** 便签父ID列索引 */
private static final int NOTE_PARENT_ID_COLUMN = 0; private static final int NOTE_PARENT_ID_COLUMN = 0;
/** 便签提醒时间列索引 */
private static final int NOTE_ALERTED_DATE_COLUMN = 1; private static final int NOTE_ALERTED_DATE_COLUMN = 1;
/** 便签背景颜色ID列索引 */
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
/** 便签小部件ID列索引 */
private static final int NOTE_WIDGET_ID_COLUMN = 3; private static final int NOTE_WIDGET_ID_COLUMN = 3;
/** 便签小部件类型列索引 */
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
/** 便签修改时间列索引 */
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct /**
* 便
*
* @param context
* @param folderId ID
*/
private WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
mAlertDate = 0; mAlertDate = 0;
@ -114,7 +159,13 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
// Existing note construct /**
* 便
*
* @param context
* @param noteId 便ID
* @param folderId ID
*/
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
mNoteId = noteId; mNoteId = noteId;
@ -124,13 +175,18 @@ public class WorkingNote {
loadNote(); loadNote();
} }
/**
* 便
*/
private void loadNote() { private void loadNote() {
// 查询便签基本信息
Cursor cursor = mContext.getContentResolver().query( Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null); null, null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
// 从查询结果中提取便签属性
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
@ -143,10 +199,15 @@ public class WorkingNote {
Log.e(TAG, "No note with id:" + mNoteId); Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId); throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
} }
// 加载便签内容数据
loadNoteData(); loadNoteData();
} }
/**
* 便
*/
private void loadNoteData() { private void loadNoteData() {
// 查询便签内容数据
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] { DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId) String.valueOf(mNoteId)
@ -155,12 +216,15 @@ public class WorkingNote {
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
// 根据数据类型处理不同的便签内容
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
// 处理文本便签数据
mContent = cursor.getString(DATA_CONTENT_COLUMN); mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN); mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) { } else if (DataConstants.CALL_NOTE.equals(type)) {
// 处理通话记录便签数据
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else { } else {
Log.d(TAG, "Wrong note type with type:" + type); Log.d(TAG, "Wrong note type with type:" + type);
@ -174,6 +238,16 @@ public class WorkingNote {
} }
} }
/**
* 便
*
* @param context
* @param folderId ID
* @param widgetId ID
* @param widgetType
* @param defaultBgColorId ID
* @return WorkingNote
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId, public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) { int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId); WorkingNote note = new WorkingNote(context, folderId);
@ -183,12 +257,26 @@ public class WorkingNote {
return note; return note;
} }
/**
* 便
*
* @param context
* @param id 便ID
* @return WorkingNote
*/
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0); return new WorkingNote(context, id, 0);
} }
/**
* 便
*
* @return truefalse
*/
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
// 检查便签是否值得保存
if (isWorthSaving()) { if (isWorthSaving()) {
// 如果便签不存在于数据库中,创建新便签
if (!existInDatabase()) { if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId); Log.e(TAG, "Create new note fail with id:" + mNoteId);
@ -196,11 +284,13 @@ public class WorkingNote {
} }
} }
// 同步便签数据到数据库
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
/** /**
* Update widget content if there exist any widget of this note * Update widget content if there exist any widget of this note
*/ */
// 如果便签有关联的小部件,更新小部件内容
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) { && mNoteSettingStatusListener != null) {
@ -212,10 +302,24 @@ public class WorkingNote {
} }
} }
/**
* 便
*
* @return truefalse
*/
public boolean existInDatabase() { public boolean existInDatabase() {
return mNoteId > 0; return mNoteId > 0;
} }
/**
* 便
*
* 1. 便
* 2. 便
* 3. 便
*
* @return truefalse
*/
private boolean isWorthSaving() { private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) { || (existInDatabase() && !mNote.isLocalModified())) {
@ -225,10 +329,21 @@ public class WorkingNote {
} }
} }
/**
* 便
*
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l; mNoteSettingStatusListener = l;
} }
/**
*
*
* @param date
* @param set
*/
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) { if (date != mAlertDate) {
mAlertDate = date; mAlertDate = date;
@ -239,17 +354,29 @@ public class WorkingNote {
} }
} }
/**
* 便/
*
* @param mark truefalse
*/
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
mIsDeleted = mark; mIsDeleted = mark;
// 如果便签有关联的小部件,通知小部件变更
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged(); mNoteSettingStatusListener.onWidgetChanged();
} }
} }
/**
* ID
*
* @param id ID
*/
public void setBgColorId(int id) { public void setBgColorId(int id) {
if (id != mBgColorId) { if (id != mBgColorId) {
mBgColorId = id; mBgColorId = id;
// 通知背景颜色变更
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged(); mNoteSettingStatusListener.onBackgroundColorChanged();
} }
@ -257,8 +384,14 @@ public class WorkingNote {
} }
} }
/**
* 便
*
* @param mode 便
*/
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
if (mMode != mode) { if (mMode != mode) {
// 通知便签模式变更
if (mNoteSettingStatusListener != null) { if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
} }
@ -267,6 +400,11 @@ public class WorkingNote {
} }
} }
/**
*
*
* @param type
*/
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
@ -274,6 +412,11 @@ public class WorkingNote {
} }
} }
/**
* ID
*
* @param id ID
*/
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
@ -281,6 +424,11 @@ public class WorkingNote {
} }
} }
/**
* 便
*
* @param text 便
*/
public void setWorkingText(String text) { public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) { if (!TextUtils.equals(mContent, text)) {
mContent = text; mContent = text;
@ -288,60 +436,130 @@ public class WorkingNote {
} }
} }
/**
* 便便
*
* @param phoneNumber
* @param callDate
*/
public void convertToCallNote(String phoneNumber, long callDate) { public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate)); mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber); mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER)); mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
} }
/**
* 便
*
* @return truefalse
*/
public boolean hasClockAlert() { public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false); return (mAlertDate > 0 ? true : false);
} }
/**
* 便
*
* @return 便
*/
public String getContent() { public String getContent() {
return mContent; return mContent;
} }
/**
*
*
* @return
*/
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
/**
*
*
* @return
*/
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
/**
* ID
*
* @return ID
*/
public int getBgColorResId() { public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId); return NoteBgResources.getNoteBgResource(mBgColorId);
} }
/**
* ID
*
* @return ID
*/
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
/**
* ID
*
* @return ID
*/
public int getTitleBgResId() { public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId); return NoteBgResources.getNoteTitleBgResource(mBgColorId);
} }
/**
* 便
*
* @return 便
*/
public int getCheckListMode() { public int getCheckListMode() {
return mMode; return mMode;
} }
/**
* 便ID
*
* @return 便ID
*/
public long getNoteId() { public long getNoteId() {
return mNoteId; return mNoteId;
} }
/**
* ID
*
* @return ID
*/
public long getFolderId() { public long getFolderId() {
return mFolderId; return mFolderId;
} }
/**
* ID
*
* @return ID
*/
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
/**
*
*
* @return
*/
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
/**
* 便
* 便
*/
public interface NoteSettingChangedListener { public interface NoteSettingChangedListener {
/** /**
* Called when the background color of current note has just changed * Called when the background color of current note has just changed

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : BackupUtils.java
* : 便便
* : 便便SD
*/
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
@ -35,12 +40,23 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
/**
* 便
*
* 便便
*
*/
public class BackupUtils { public class BackupUtils {
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils";
// Singleton stuff // 单例实例
private static BackupUtils sInstance; private static BackupUtils sInstance;
/**
* BackupUtils
*
* @param context
* @return BackupUtils
*/
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) { if (sInstance == null) {
sInstance = new BackupUtils(context); sInstance = new BackupUtils(context);
@ -49,43 +65,74 @@ 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; public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist // 备份文件不存在状态
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs // 数据已损坏状态(可能被其他程序修改)
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails // 系统错误状态(运行时异常导致备份或恢复失败)
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success // 操作成功状态
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
// 文本导出工具实例
private TextExport mTextExport; private TextExport mTextExport;
/**
*
*
* @param context
*/
private BackupUtils(Context context) { private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context);
} }
/**
*
*
* @return truefalse
*/
private static boolean externalStorageAvailable() { private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
/**
* 便
*
* @return STATE_*
*/
public int exportToText() { public int exportToText() {
return mTextExport.exportToText(); return mTextExport.exportToText();
} }
/**
*
*
* @return
*/
public String getExportedTextFileName() { public String getExportedTextFileName() {
return mTextExport.mFileName; return mTextExport.mFileName;
} }
/**
*
*
* @return
*/
public String getExportedTextFileDir() { public String getExportedTextFileDir() {
return mTextExport.mFileDirectory; return mTextExport.mFileDirectory;
} }
/**
*
*
* 便
*/
private static class TextExport { private static class TextExport {
// 便签查询投影:定义查询便签时需要获取的列
private static final String[] NOTE_PROJECTION = { private static final String[] NOTE_PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
@ -93,12 +140,16 @@ public class BackupUtils {
NoteColumns.TYPE NoteColumns.TYPE
}; };
// 便签ID列索引
private static final int NOTE_COLUMN_ID = 0; private static final int NOTE_COLUMN_ID = 0;
// 便签修改日期列索引
private static final int NOTE_COLUMN_MODIFIED_DATE = 1; private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
// 便签摘要列索引
private static final int NOTE_COLUMN_SNIPPET = 2; private static final int NOTE_COLUMN_SNIPPET = 2;
// 便签数据查询投影:定义查询便签数据时需要获取的列
private static final String[] DATA_PROJECTION = { private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT, DataColumns.CONTENT,
DataColumns.MIME_TYPE, DataColumns.MIME_TYPE,
@ -108,39 +159,65 @@ public class BackupUtils {
DataColumns.DATA4, DataColumns.DATA4,
}; };
// 便签内容列索引
private static final int DATA_COLUMN_CONTENT = 0; private static final int DATA_COLUMN_CONTENT = 0;
// 便签MIME类型列索引
private static final int DATA_COLUMN_MIME_TYPE = 1; private static final int DATA_COLUMN_MIME_TYPE = 1;
// 通话日期列索引
private static final int DATA_COLUMN_CALL_DATE = 2; private static final int DATA_COLUMN_CALL_DATE = 2;
// 电话号码列索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 文本格式化模板数组
private final String [] TEXT_FORMAT; private final String [] TEXT_FORMAT;
// 文件夹名称格式索引
private static final int FORMAT_FOLDER_NAME = 0; private static final int FORMAT_FOLDER_NAME = 0;
// 便签日期格式索引
private static final int FORMAT_NOTE_DATE = 1; private static final int FORMAT_NOTE_DATE = 1;
// 便签内容格式索引
private static final int FORMAT_NOTE_CONTENT = 2; private static final int FORMAT_NOTE_CONTENT = 2;
// 上下文环境
private Context mContext; private Context mContext;
// 导出文件名
private String mFileName; private String mFileName;
// 导出文件目录
private String mFileDirectory; private String mFileDirectory;
/**
*
*
* @param context
*/
public TextExport(Context context) { public TextExport(Context context) {
// 从资源文件加载文本格式化模板
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; mContext = context;
mFileName = ""; mFileName = "";
mFileDirectory = ""; mFileDirectory = "";
} }
/**
*
*
* @param id
* @return
*/
private String getFormat(int id) { private String getFormat(int id) {
return TEXT_FORMAT[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) { private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder // 查询属于此文件夹的便签
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId folderId
@ -149,11 +226,11 @@ public class BackupUtils {
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { do {
// Print note's last modified date // 输出便签的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note // 查询并导出此便签的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID); String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());
@ -163,9 +240,13 @@ public class BackupUtils {
} }
/** /**
* Export note identified by id to a print stream * ID便
*
* @param noteId 便ID
* @param ps
*/ */
private void exportNoteToText(String noteId, PrintStream ps) { private void exportNoteToText(String noteId, PrintStream ps) {
// 查询便签数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId noteId
@ -175,8 +256,9 @@ public class BackupUtils {
if (dataCursor.moveToFirst()) { if (dataCursor.moveToFirst()) {
do { do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
// 处理通话记录便签
if (DataConstants.CALL_NOTE.equals(mimeType)) { if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number // 输出电话号码
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
@ -185,16 +267,18 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber)); phoneNumber));
} }
// Print call date // 输出通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm), .format(mContext.getString(R.string.format_datetime_mdhm),
callDate))); callDate)));
// Print call attachment location // 输出通话附件位置
if (!TextUtils.isEmpty(location)) { if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location)); location));
} }
} else if (DataConstants.NOTE.equals(mimeType)) { }
// 处理普通文本便签
else if (DataConstants.NOTE.equals(mimeType)) {
String content = dataCursor.getString(DATA_COLUMN_CONTENT); String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) { if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
@ -205,7 +289,7 @@ public class BackupUtils {
} }
dataCursor.close(); dataCursor.close();
} }
// print a line separator between note // 在便签之间打印一个分隔行
try { try {
ps.write(new byte[] { ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -216,20 +300,24 @@ public class BackupUtils {
} }
/** /**
* Note will be exported as text which is user readable * 便
*
* @return STATE_*
*/ */
public int exportToText() { public int exportToText() {
// 检查外部存储是否可用
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted"); Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED; return STATE_SD_CARD_UNMOUONTED;
} }
// 获取输出流
PrintStream ps = getExportToTextPrintStream(); PrintStream ps = getExportToTextPrintStream();
if (ps == null) { if (ps == null) {
Log.e(TAG, "get print stream error"); Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR;
} }
// First export folder and its notes // 首先导出文件夹及其便签
Cursor folderCursor = mContext.getContentResolver().query( Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
@ -240,7 +328,7 @@ public class BackupUtils {
if (folderCursor != null) { if (folderCursor != null) {
if (folderCursor.moveToFirst()) { if (folderCursor.moveToFirst()) {
do { do {
// Print folder's name // 输出文件夹名称
String folderName = ""; String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name); folderName = mContext.getString(R.string.call_record_folder_name);
@ -283,7 +371,9 @@ public class BackupUtils {
} }
/** /**
* Get a print stream pointed to the file {@generateExportedTextFile} *
*
* @return null
*/ */
private PrintStream getExportToTextPrintStream() { private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path, File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
@ -310,7 +400,12 @@ public class BackupUtils {
} }
/** /**
* Generate the text file to store imported data * SD
*
* @param context
* @param filePathResId ID
* @param fileNameFormatResId ID
* @return null
*/ */
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : DataUtils.java
* : 便便
* : 便便便
*/
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.ContentProviderOperation; import android.content.ContentProviderOperation;
@ -34,10 +39,24 @@ import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
/**
* 便
*
* 便便便
*
*/
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
/**
* 便
*
* @param resolver
* @param ids 便ID
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查参数有效性
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null");
return true; return true;
@ -47,75 +66,113 @@ public class DataUtils {
return true; return true;
} }
// 创建批量操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) {
// 不允许删除根文件夹
if(id == Notes.ID_ROOT_FOLDER) { if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root"); Log.e(TAG, "Don't delete system folder root");
continue; continue;
} }
// 为每个便签ID创建删除操作
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build()); operationList.add(builder.build());
} }
try { try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
} }
return true; return true;
} catch (RemoteException e) { } 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) { } 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; 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) { public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
// 创建更新数据
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId); values.put(NoteColumns.PARENT_ID, desFolderId); // 设置新的父文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 保存原始父文件夹ID
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改
// 更新便签数据
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); 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, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
// 检查参数有效性
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null");
return true; return true;
} }
// 创建批量操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) {
// 为每个便签ID创建更新操作
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId); builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置新的父文件夹ID
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改
operationList.add(builder.build()); operationList.add(builder.build());
} }
try { try {
// 执行批量操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
} }
return true; return true;
} catch (RemoteException e) { } 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) { } 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; return false;
} }
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} *
*
* @param resolver
* @return
*/ */
public static int getUserFolderCount(ContentResolver resolver) { public static int getUserFolderCount(ContentResolver resolver) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, // 查询类型为文件夹且不在回收站中的记录数量
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" }, new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
@ -125,10 +182,13 @@ public class DataUtils {
if(cursor != null) { if(cursor != null) {
if(cursor.moveToFirst()) { if(cursor.moveToFirst()) {
try { try {
// 获取查询结果中的计数值
count = cursor.getInt(0); count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 索引越界异常处理
Log.e(TAG, "get folder count failed:" + e.toString()); Log.e(TAG, "get folder count failed:" + e.toString());
} finally { } finally {
// 确保关闭游标
cursor.close(); cursor.close();
} }
} }
@ -136,7 +196,16 @@ public class DataUtils {
return count; return count;
} }
/**
* ID便
*
* @param resolver
* @param noteId 便ID
* @param type 便
* @return 便truefalse
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 查询指定ID和类型的便签且不在回收站中
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
@ -145,6 +214,7 @@ public class DataUtils {
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
// 如果查询结果不为空,则便签存在且可见
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
@ -153,12 +223,21 @@ public class DataUtils {
return exist; return exist;
} }
/**
* ID便
*
* @param resolver
* @param noteId 便ID
* @return 便truefalse
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 查询指定ID的便签
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null); null, null, null, null);
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
// 如果查询结果不为空,则便签存在
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
@ -167,12 +246,21 @@ public class DataUtils {
return exist; return exist;
} }
/**
* ID
*
* @param resolver
* @param dataId ID
* @return truefalse
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 查询指定ID的数据
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null); null, null, null, null);
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
// 如果查询结果不为空,则数据存在
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {
exist = true; exist = true;
} }
@ -181,14 +269,24 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
*
* @param resolver
* @param name
* @return truefalse
*/
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询类型为文件夹、不在回收站中且名称匹配的记录
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?", " AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null); new String[] { name }, null);
boolean exist = false; boolean exist = false;
if(cursor != null) { if(cursor != null) {
// 如果查询结果不为空,则存在同名文件夹
if(cursor.getCount() > 0) { if(cursor.getCount() > 0) {
exist = true; exist = true;
} }
@ -197,7 +295,15 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
*
* @param resolver
* @param folderId ID
* @return null
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询指定文件夹中便签的小部件ID和类型
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?", NoteColumns.PARENT_ID + "=?",
@ -207,14 +313,17 @@ public class DataUtils {
HashSet<AppWidgetAttribute> set = null; HashSet<AppWidgetAttribute> set = null;
if (c != null) { if (c != null) {
if (c.moveToFirst()) { if (c.moveToFirst()) {
// 创建小部件属性集合
set = new HashSet<AppWidgetAttribute>(); set = new HashSet<AppWidgetAttribute>();
do { do {
try { try {
// 提取小部件ID和类型
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0); widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1); widget.widgetType = c.getInt(1);
set.add(widget); set.add(widget);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 索引越界异常处理
Log.e(TAG, e.toString()); Log.e(TAG, e.toString());
} }
} while (c.moveToNext()); } while (c.moveToNext());
@ -224,7 +333,15 @@ public class DataUtils {
return set; return set;
} }
/**
* 便ID
*
* @param resolver
* @param noteId 便ID
* @return
*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 查询指定便签ID和MIME类型的通话记录数据
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
@ -233,62 +350,95 @@ public class DataUtils {
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
// 返回电话号码
return cursor.getString(0); return cursor.getString(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
// 索引越界异常处理
Log.e(TAG, "Get call number fails " + e.toString()); Log.e(TAG, "Get call number fails " + e.toString());
} finally { } finally {
// 确保关闭游标
cursor.close(); cursor.close();
} }
} }
return ""; return "";
} }
/**
* 便ID
*
* @param resolver
* @param phoneNumber
* @param callDate
* @return 便ID0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 查询匹配电话号码和通话日期的便签ID
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)", + CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber},
null); null);
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
try { try {
// 返回便签ID
return cursor.getLong(0); return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString()); Log.e(TAG, "Get note id by phone number and call date fails: " + e.toString());
} finally {
cursor.close();
} }
} else {
cursor.close();
} }
cursor.close();
} }
return 0; return 0;
} }
/**
* 便ID便
*
* @param resolver
* @param noteId 便ID
* @return 便
*/
public static String getSnippetById(ContentResolver resolver, long noteId) { public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, // 查询指定便签ID的摘要
new String [] { NoteColumns.SNIPPET }, Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
NoteColumns.ID + "=?", new String[] { NoteColumns.SNIPPET },
new String [] { String.valueOf(noteId)}, null,
null,
null); null);
if (cursor != null) { if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
snippet = cursor.getString(0); try {
// 返回便签摘要
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get snippet fails: " + e.toString());
} finally {
cursor.close();
}
} else {
cursor.close();
} }
cursor.close();
return snippet;
} }
throw new IllegalArgumentException("Note is not found with id: " + noteId); return "";
} }
/**
* 便
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {
if (snippet != null) { if (snippet != null) {
snippet = snippet.trim(); // 替换换行符为空格
int index = snippet.indexOf('\n'); snippet = snippet.replace('\n', ' ');
if (index != -1) {
snippet = snippet.substring(0, index);
}
} }
return snippet; return snippet;
} }

@ -14,100 +14,301 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : GTaskStringUtils.java
* : Google Tasks
* : Google Tasks APIJSON便
*/
package net.micode.notes.tool; package net.micode.notes.tool;
/**
* Google Tasks
*
* Google Tasks
* - JSON
* -
* -
* -
* -
*
* Google Tasks APIJSON
*/
public class GTaskStringUtils { public class GTaskStringUtils {
/**
* JSON: ID
* ID
*/
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";
/**
* JSON:
*
*/
public final static String GTASK_JSON_ACTION_LIST = "action_list"; public final static String GTASK_JSON_ACTION_LIST = "action_list";
/**
* JSON:
*
*/
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; public final static String GTASK_JSON_ACTION_TYPE = "action_type";
/**
* :
*
*/
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
/**
* :
*
*/
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
/**
* :
*
*/
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
/**
* :
*
*/
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
/**
* JSON: ID
*
*/
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; public final static String GTASK_JSON_CREATOR_ID = "creator_id";
/**
* JSON:
*
*/
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
/**
* JSON:
*
*/
public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
/**
* JSON:
*
*/
public final static String GTASK_JSON_COMPLETED = "completed"; public final static String GTASK_JSON_COMPLETED = "completed";
/**
* JSON: ID
* ID
*/
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
/**
* JSON: ID
* ID
*/
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
/**
* JSON:
*
*/
public final static String GTASK_JSON_DELETED = "deleted"; public final static String GTASK_JSON_DELETED = "deleted";
/**
* JSON:
*
*/
public final static String GTASK_JSON_DEST_LIST = "dest_list"; public final static String GTASK_JSON_DEST_LIST = "dest_list";
/**
* JSON:
*
*/
public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
/**
* JSON:
*
*/
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
/**
* JSON:
*
*/
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
/**
* JSON:
*
*/
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
/**
* JSON:
*
*/
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; public final static String GTASK_JSON_GET_DELETED = "get_deleted";
/**
* JSON: ID
*
*/
public final static String GTASK_JSON_ID = "id"; public final static String GTASK_JSON_ID = "id";
/**
* JSON:
*
*/
public final static String GTASK_JSON_INDEX = "index"; public final static String GTASK_JSON_INDEX = "index";
/**
* JSON:
*
*/
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
/**
* JSON:
*
*/
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; 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"; public final static String GTASK_JSON_LIST_ID = "list_id";
/**
* JSON:
*
*/
public final static String GTASK_JSON_LISTS = "lists"; public final static String GTASK_JSON_LISTS = "lists";
/**
* JSON:
*
*/
public final static String GTASK_JSON_NAME = "name"; public final static String GTASK_JSON_NAME = "name";
/**
* JSON: ID
* ID
*/
public final static String GTASK_JSON_NEW_ID = "new_id"; public final static String GTASK_JSON_NEW_ID = "new_id";
/**
* JSON: 便
* 便
*/
public final static String GTASK_JSON_NOTES = "notes"; public final static String GTASK_JSON_NOTES = "notes";
/**
* JSON: ID
* ID
*/
public final static String GTASK_JSON_PARENT_ID = "parent_id"; public final static String GTASK_JSON_PARENT_ID = "parent_id";
/**
* JSON: ID
* ID
*/
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
/**
* JSON:
* API
*/
public final static String GTASK_JSON_RESULTS = "results"; public final static String GTASK_JSON_RESULTS = "results";
/**
* JSON:
*
*/
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; public final static String GTASK_JSON_SOURCE_LIST = "source_list";
/**
* JSON:
*
*/
public final static String GTASK_JSON_TASKS = "tasks"; public final static String GTASK_JSON_TASKS = "tasks";
/**
* JSON:
*
*/
public final static String GTASK_JSON_TYPE = "type"; public final static String GTASK_JSON_TYPE = "type";
/**
* : /
*
*/
public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
/**
* :
*
*/
public final static String GTASK_JSON_TYPE_TASK = "TASK"; public final static String GTASK_JSON_TYPE_TASK = "TASK";
/**
* JSON:
*
*/
public final static String GTASK_JSON_USER = "user"; public final static String GTASK_JSON_USER = "user";
/**
*
* MIUI便
*/
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
/**
*
* 便
*/
public final static String FOLDER_DEFAULT = "Default"; public final static String FOLDER_DEFAULT = "Default";
/**
*
* 便
*/
public final static String FOLDER_CALL_NOTE = "Call_Note"; public final static String FOLDER_CALL_NOTE = "Call_Note";
/**
*
*
*/
public final static String FOLDER_META = "METADATA"; public final static String FOLDER_META = "METADATA";
/**
* : Google Task ID
* 便Google Task ID
*/
public final static String META_HEAD_GTASK_ID = "meta_gid"; public final static String META_HEAD_GTASK_ID = "meta_gid";
/**
* : 便
* 便
*/
public final static String META_HEAD_NOTE = "meta_note"; public final static String META_HEAD_NOTE = "meta_note";
/**
* :
* 便
*/
public final static String META_HEAD_DATA = "meta_data"; public final static String META_HEAD_DATA = "meta_data";
/**
* 便
* 便
*/
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : ResourceParser.java
* : ID
* : 便访便UI使
*/
package net.micode.notes.tool; package net.micode.notes.tool;
import android.content.Context; import android.content.Context;
@ -22,24 +27,84 @@ import android.preference.PreferenceManager;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/**
*
*
* 使ID
* - 便
* - 便
* -
* -
*
* 使UI便访使
*/
public class ResourceParser { public class ResourceParser {
/**
* :
*/
public static final int YELLOW = 0; public static final int YELLOW = 0;
/**
* :
*/
public static final int BLUE = 1; public static final int BLUE = 1;
/**
* :
*/
public static final int WHITE = 2; public static final int WHITE = 2;
/**
* : 绿
*/
public static final int GREEN = 3; public static final int GREEN = 3;
/**
* :
*/
public static final int RED = 4; public static final int RED = 4;
/**
* :
*/
public static final int BG_DEFAULT_COLOR = YELLOW; public static final int BG_DEFAULT_COLOR = YELLOW;
/**
* :
*/
public static final int TEXT_SMALL = 0; public static final int TEXT_SMALL = 0;
/**
* :
*/
public static final int TEXT_MEDIUM = 1; public static final int TEXT_MEDIUM = 1;
/**
* :
*/
public static final int TEXT_LARGE = 2; public static final int TEXT_LARGE = 2;
/**
* :
*/
public static final int TEXT_SUPER = 3; public static final int TEXT_SUPER = 3;
/**
* :
*/
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM; public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
/**
* 便
*
* 便
*/
public static class NoteBgResources { public static class NoteBgResources {
/**
* 便
* ID
*/
private final static int [] BG_EDIT_RESOURCES = new int [] { private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow, R.drawable.edit_yellow,
R.drawable.edit_blue, R.drawable.edit_blue,
@ -48,6 +113,10 @@ public class ResourceParser {
R.drawable.edit_red R.drawable.edit_red
}; };
/**
* 便
* ID
*/
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] { private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow, R.drawable.edit_title_yellow,
R.drawable.edit_title_blue, R.drawable.edit_title_blue,
@ -56,25 +125,57 @@ public class ResourceParser {
R.drawable.edit_title_red R.drawable.edit_title_red
}; };
/**
* 便ID
*
* @param id
* @return ID
*/
public static int getNoteBgResource(int id) { public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id]; return BG_EDIT_RESOURCES[id];
} }
/**
* 便ID
*
* @param id
* @return ID
*/
public static int getNoteTitleBgResource(int id) { public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id]; return BG_EDIT_TITLE_RESOURCES[id];
} }
} }
/**
* ID
*
* 使
*
* @param context
* @return ID
*/
public static int getDefaultBgId(Context context) { public static int getDefaultBgId(Context context) {
// 检查用户是否设置了随机背景颜色
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) { NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 随机选择一种背景颜色
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length); return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else { } else {
// 使用默认背景颜色
return BG_DEFAULT_COLOR; return BG_DEFAULT_COLOR;
} }
} }
/**
* 便
*
* 便
*/
public static class NoteItemBgResources { public static class NoteItemBgResources {
/**
*
* ID
*/
private final static int [] BG_FIRST_RESOURCES = new int [] { private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up, R.drawable.list_yellow_up,
R.drawable.list_blue_up, R.drawable.list_blue_up,
@ -83,6 +184,10 @@ public class ResourceParser {
R.drawable.list_red_up R.drawable.list_red_up
}; };
/**
*
* ID
*/
private final static int [] BG_NORMAL_RESOURCES = new int [] { private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle, R.drawable.list_yellow_middle,
R.drawable.list_blue_middle, R.drawable.list_blue_middle,
@ -91,6 +196,10 @@ public class ResourceParser {
R.drawable.list_red_middle R.drawable.list_red_middle
}; };
/**
*
* ID
*/
private final static int [] BG_LAST_RESOURCES = new int [] { private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down, R.drawable.list_yellow_down,
R.drawable.list_blue_down, R.drawable.list_blue_down,
@ -99,6 +208,10 @@ public class ResourceParser {
R.drawable.list_red_down, R.drawable.list_red_down,
}; };
/**
*
* ID使
*/
private final static int [] BG_SINGLE_RESOURCES = new int [] { private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single, R.drawable.list_yellow_single,
R.drawable.list_blue_single, R.drawable.list_blue_single,
@ -107,28 +220,66 @@ public class ResourceParser {
R.drawable.list_red_single R.drawable.list_red_single
}; };
/**
* ID
*
* @param id
* @return ID
*/
public static int getNoteBgFirstRes(int id) { public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id]; return BG_FIRST_RESOURCES[id];
} }
/**
* ID
*
* @param id
* @return ID
*/
public static int getNoteBgLastRes(int id) { public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id]; return BG_LAST_RESOURCES[id];
} }
/**
* ID
*
* @param id
* @return ID
*/
public static int getNoteBgSingleRes(int id) { public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id]; return BG_SINGLE_RESOURCES[id];
} }
/**
* ID
*
* @param id
* @return ID
*/
public static int getNoteBgNormalRes(int id) { public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id]; return BG_NORMAL_RESOURCES[id];
} }
/**
* ID
*
* @return ID
*/
public static int getFolderBgRes() { public static int getFolderBgRes() {
return R.drawable.list_folder; return R.drawable.list_folder;
} }
} }
/**
*
*
*
*/
public static class WidgetBgResources { public static class WidgetBgResources {
/**
* 2x
* 2xID
*/
private final static int [] BG_2X_RESOURCES = new int [] { private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow, R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue, R.drawable.widget_2x_blue,
@ -137,10 +288,20 @@ public class ResourceParser {
R.drawable.widget_2x_red, R.drawable.widget_2x_red,
}; };
/**
* 2xID
*
* @param id
* @return 2xID
*/
public static int getWidget2xBgResource(int id) { public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id]; return BG_2X_RESOURCES[id];
} }
/**
* 4x
* 4xID
*/
private final static int [] BG_4X_RESOURCES = new int [] { private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow, R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue, R.drawable.widget_4x_blue,
@ -149,12 +310,27 @@ public class ResourceParser {
R.drawable.widget_4x_red R.drawable.widget_4x_red
}; };
/**
* 4xID
*
* @param id
* @return 4xID
*/
public static int getWidget4xBgResource(int id) { public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id]; return BG_4X_RESOURCES[id];
} }
} }
/**
*
*
*
*/
public static class TextAppearanceResources { public static class TextAppearanceResources {
/**
*
* ID
*/
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal, R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium, R.style.TextAppearanceMedium,
@ -162,11 +338,16 @@ public class ResourceParser {
R.style.TextAppearanceSuper R.style.TextAppearanceSuper
}; };
/**
* ID
*
* @param id
* @return ID
*/
public static int getTexAppearanceResource(int id) { public static int getTexAppearanceResource(int id) {
/** /**
* HACKME: Fix bug of store the resource id in shared preference. * Bug: ID
* The id may larger than the length of resources, in this case, * ID
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/ */
if (id >= TEXTAPPEARANCE_RESOURCES.length) { if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE; return BG_DEFAULT_FONT_SIZE;
@ -174,6 +355,11 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id]; return TEXTAPPEARANCE_RESOURCES[id];
} }
/**
*
*
* @return
*/
public static int getResourcesSize() { public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length; return TEXTAPPEARANCE_RESOURCES.length;
} }

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : AlarmAlertActivity.java
* : 便
* : 便
* :
* 1.
* 2.
* 3. 便
* 4. 便
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
@ -39,119 +49,204 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
/**
* 便
*
* 便
* OnClickListenerOnDismissListener
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
/** 当前提醒的便签ID */
private long mNoteId; private long mNoteId;
/** 便签内容摘要 */
private String mSnippet; private String mSnippet;
/** 便签摘要预览的最大长度 */
private static final int SNIPPET_PREW_MAX_LEN = 60; private static final int SNIPPET_PREW_MAX_LEN = 60;
/** 媒体播放器,用于播放闹钟声音 */
MediaPlayer mPlayer; MediaPlayer mPlayer;
/**
*
* 便
*
* @param savedInstanceState
*/
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// 请求无标题栏窗口
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE);
final Window win = getWindow(); final Window win = getWindow();
// 设置在锁屏状态下也能显示
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 如果屏幕未开启,添加相关窗口标志
if (!isScreenOn()) { if (!isScreenOn()) {
// 保持屏幕开启、点亮屏幕、允许锁屏时显示、设置窗口装饰插入
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
} }
// 获取启动此活动的意图
Intent intent = getIntent(); Intent intent = getIntent();
try { try {
// 从URI中提取便签ID
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 获取便签内容摘要
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 如果摘要过长,截取前面部分并添加省略号
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet; : mSnippet;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// 处理参数错误异常
e.printStackTrace(); e.printStackTrace();
return; return;
} }
// 初始化媒体播放器
mPlayer = new MediaPlayer(); mPlayer = new MediaPlayer();
// 检查便签是否存在且可见
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 显示提醒对话框
showActionDialog(); showActionDialog();
// 播放闹钟声音
playAlarmSound(); playAlarmSound();
} else { } else {
// 如果便签不存在或不可见,结束活动
finish(); finish();
} }
} }
/**
*
*
* @return truefalse
*/
private boolean isScreenOn() { private boolean isScreenOn() {
// 获取电源管理服务
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// 检查屏幕是否点亮
return pm.isScreenOn(); return pm.isScreenOn();
} }
/**
*
*
*/
private void playAlarmSound() { private void playAlarmSound() {
// 获取系统默认闹钟铃声URI
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取静音模式影响的音频流
int silentModeStreams = Settings.System.getInt(getContentResolver(), int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 根据系统设置选择合适的音频流类型
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
// 如果闹钟音频流受静音模式影响,使用静音模式流
mPlayer.setAudioStreamType(silentModeStreams); mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
// 否则使用标准闹钟音频流
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
} }
try { try {
// 设置数据源为闹钟铃声URI
mPlayer.setDataSource(this, url); mPlayer.setDataSource(this, url);
// 准备媒体播放器
mPlayer.prepare(); mPlayer.prepare();
// 设置循环播放
mPlayer.setLooping(true); mPlayer.setLooping(true);
// 开始播放
mPlayer.start(); mPlayer.start();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// TODO Auto-generated catch block // 处理参数错误异常
e.printStackTrace(); e.printStackTrace();
} catch (SecurityException e) { } catch (SecurityException e) {
// TODO Auto-generated catch block // 处理安全权限异常
e.printStackTrace(); e.printStackTrace();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// TODO Auto-generated catch block // 处理状态错误异常
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block // 处理IO异常
e.printStackTrace(); e.printStackTrace();
} }
} }
/**
*
* 便
*/
private void showActionDialog() { private void showActionDialog() {
// 创建提醒对话框构建器
AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog.Builder dialog = new AlertDialog.Builder(this);
// 设置对话框标题为应用名称
dialog.setTitle(R.string.app_name); dialog.setTitle(R.string.app_name);
// 设置对话框内容为便签摘要
dialog.setMessage(mSnippet); dialog.setMessage(mSnippet);
// 添加确定按钮
dialog.setPositiveButton(R.string.notealert_ok, this); dialog.setPositiveButton(R.string.notealert_ok, this);
// 如果屏幕已点亮,添加进入便签的按钮
if (isScreenOn()) { if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this); dialog.setNegativeButton(R.string.notealert_enter, this);
} }
// 显示对话框并设置关闭监听器
dialog.show().setOnDismissListener(this); dialog.show().setOnDismissListener(this);
} }
/**
*
*
* @param dialog
* @param which ID
*/
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
switch (which) { switch (which) {
case DialogInterface.BUTTON_NEGATIVE: case DialogInterface.BUTTON_NEGATIVE:
// 如果点击"进入"按钮,启动便签编辑活动
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId); intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent); startActivity(intent);
break; break;
default: default:
// 其他按钮不做特殊处理,对话框会自动关闭
break; break;
} }
} }
/**
*
*
* @param dialog
*/
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) {
// 停止闹钟声音
stopAlarmSound(); stopAlarmSound();
// 结束活动
finish(); finish();
} }
/**
*
*
*/
private void stopAlarmSound() { private void stopAlarmSound() {
if (mPlayer != null) { if (mPlayer != null) {
// 停止播放
mPlayer.stop(); mPlayer.stop();
// 释放资源
mPlayer.release(); mPlayer.release();
// 置空播放器引用
mPlayer = null; mPlayer = null;
} }
} }

@ -14,6 +14,15 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : AlarmInitReceiver.java
* : 便广
* : 便
* :
* 1. 广
* 2.
* 3.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.AlarmManager; import android.app.AlarmManager;
@ -27,20 +36,42 @@ import android.database.Cursor;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
* 便广
*
* 便
*
* 使便
*/
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
/**
*
*/
private static final String [] PROJECTION = new String [] { private static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE NoteColumns.ALERTED_DATE // 提醒时间
}; };
/** 便签ID列索引 */
private static final int COLUMN_ID = 0; private static final int COLUMN_ID = 0;
/** 提醒时间列索引 */
private static final int COLUMN_ALERTED_DATE = 1; private static final int COLUMN_ALERTED_DATE = 1;
/**
* 广
* 便
*
* @param context
* @param intent 广
*/
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 获取当前系统时间
long currentDate = System.currentTimeMillis(); long currentDate = System.currentTimeMillis();
// 查询所有未触发的提醒(提醒时间大于当前时间,且类型为便签)
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
@ -48,17 +79,29 @@ public class AlarmInitReceiver extends BroadcastReceiver {
null); null);
if (c != null) { if (c != null) {
// 如果有未触发的提醒
if (c.moveToFirst()) { if (c.moveToFirst()) {
do { do {
// 获取提醒时间
long alertDate = c.getLong(COLUMN_ALERTED_DATE); long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建用于触发AlarmReceiver的Intent
Intent sender = new Intent(context, AlarmReceiver.class); Intent sender = new Intent(context, AlarmReceiver.class);
// 设置Intent的数据为便签的URI
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建PendingIntent用于延迟触发
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取系统闹钟服务
AlarmManager alermManager = (AlarmManager) context AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE); .getSystemService(Context.ALARM_SERVICE);
// 设置闹钟,在提醒时间触发,并唤醒设备
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); } while (c.moveToNext());
} }
// 关闭游标,释放资源
c.close(); c.close();
} }
} }

@ -14,17 +14,41 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : AlarmReceiver.java
* : 便广
* : 广
* :
* 1. AlarmManager广
* 2. 广AlarmAlertActivity
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
/**
* 便广
*
* 便广
* AlarmAlertActivity
* 便
*/
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
*
* @param context
* @param intent 广便URI
*/
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 将意图的目标类设置为AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
// 添加新任务标志,确保活动在新的任务栈中启动
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动提醒活动
context.startActivity(intent); context.startActivity(intent);
} }
} }

@ -163,14 +163,33 @@ public class DateTimePicker extends FrameLayout {
int dayOfMonth, int hourOfDay, int minute); int dayOfMonth, int hourOfDay, int minute);
} }
/**
* 使
*
* @param context
*/
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
/**
* 使
* 1224
*
* @param context
* @param date
*/
public DateTimePicker(Context context, long date) { public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context)); this(context, date, DateFormat.is24HourFormat(context));
} }
/**
* 使
*
* @param context
* @param date
* @param is24HourView 使24
*/
public DateTimePicker(Context context, long date, boolean is24HourView) { public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); super(context);
mDate = Calendar.getInstance(); mDate = Calendar.getInstance();
@ -178,19 +197,24 @@ public class DateTimePicker extends FrameLayout {
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
inflate(context, R.layout.datetime_picker, this); inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date); mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour); mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute); mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100); mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化上午/下午选择器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
@ -198,19 +222,21 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setDisplayedValues(stringsForAmPm); mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state // 更新控件到初始状态
updateDateControl(); updateDateControl();
updateHourControl(); updateHourControl();
updateAmPmControl(); updateAmPmControl();
// 设置时间格式12小时制或24小时制
set24HourView(is24HourView); set24HourView(is24HourView);
// set to current time // 设置当前时间
setCurrentDate(date); setCurrentDate(date);
// 设置控件启用状态
setEnabled(isEnabled()); setEnabled(isEnabled());
// set the content descriptions // 完成初始化
mInitialising = false; mInitialising = false;
} }

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : DateTimePickerDialog.java
* :
* :
* :
* 1. AlertDialogDateTimePicker
* 2.
* 3.
* 4.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import java.util.Calendar; import java.util.Calendar;
@ -29,62 +39,134 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.text.format.DateUtils; import android.text.format.DateUtils;
/**
*
*
* AlertDialogDateTimePicker
*
*
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
/** 存储当前选择的日期时间 */
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
/** 是否使用24小时制显示 */
private boolean mIs24HourView; private boolean mIs24HourView;
/** 日期时间设置监听器 */
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
/** 日期时间选择器控件 */
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
/**
*
*
*/
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
/**
*
*
* @param dialog
* @param date
*/
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
/**
*
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); super(context);
// 创建日期时间选择器控件
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
// 将选择器设置为对话框的内容视图
setView(mDateTimePicker); setView(mDateTimePicker);
// 设置日期时间变更监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month, public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
// 更新日期对象
mDate.set(Calendar.YEAR, year); mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
// 更新对话框标题为当前选择的日期时间
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
}); });
// 设置初始日期时间
mDate.setTimeInMillis(date); mDate.setTimeInMillis(date);
// 将秒设置为0
mDate.set(Calendar.SECOND, 0); mDate.set(Calendar.SECOND, 0);
// 设置选择器的当前日期
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置确定按钮
setButton(context.getString(R.string.datetime_dialog_ok), this); setButton(context.getString(R.string.datetime_dialog_ok), this);
// 设置取消按钮(不需要监听器,点击会自动关闭对话框)
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置决定是否使用24小时制
set24HourView(DateFormat.is24HourFormat(this.getContext())); set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 更新对话框标题
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
/**
* 使24
*
* @param is24HourView true使24使12
*/
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
/**
*
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
/**
*
*
* @param date
*/
private void updateTitle(long date) { private void updateTitle(long date) {
// 设置日期时间格式化标志
int flag = int flag =
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR | // 显示年份
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_DATE | // 显示日期
DateUtils.FORMAT_SHOW_TIME; DateUtils.FORMAT_SHOW_TIME; // 显示时间
// 根据是否使用24小时制设置相应的格式
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 设置对话框标题为格式化的日期时间字符串
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
} }
/**
*
*
* @param arg0
* @param arg1 ID
*/
public void onClick(DialogInterface arg0, int arg1) { public void onClick(DialogInterface arg0, int arg1) {
// 如果设置了监听器,通知日期时间已设置
if (mOnDateTimeSetListener != null) { if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
} }
} }
} }

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : DropdownMenu.java
* :
* :
* :
* 1.
* 2.
* 3.
* 4.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -27,34 +37,77 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
/**
*
*
* PopupMenu
*
*
*/
public class DropdownMenu { public class DropdownMenu {
/** 触发菜单显示的按钮 */
private Button mButton; private Button mButton;
/** 弹出菜单对象 */
private PopupMenu mPopupMenu; private PopupMenu mPopupMenu;
/** 菜单对象,用于管理菜单项 */
private Menu mMenu; private Menu mMenu;
/**
*
*
* @param context
* @param button
* @param menuId ID
*/
public DropdownMenu(Context context, Button button, int menuId) { public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; mButton = button;
// 设置按钮的背景为下拉图标
mButton.setBackgroundResource(R.drawable.dropdown_icon); mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建弹出菜单,并与按钮关联
mPopupMenu = new PopupMenu(context, mButton); mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单对象
mMenu = mPopupMenu.getMenu(); mMenu = mPopupMenu.getMenu();
// 从资源文件中加载菜单项
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击监听器,点击时显示菜单
mButton.setOnClickListener(new OnClickListener() { mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
// 显示弹出菜单
mPopupMenu.show(); mPopupMenu.show();
} }
}); });
} }
/**
*
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) { if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); mPopupMenu.setOnMenuItemClickListener(listener);
} }
} }
/**
* ID
*
* @param id ID
* @return null
*/
public MenuItem findItem(int id) { public MenuItem findItem(int id) {
return mMenu.findItem(id); return mMenu.findItem(id);
} }
/**
*
*
* @param title
*/
public void setTitle(CharSequence title) { public void setTitle(CharSequence title) {
mButton.setText(title); mButton.setText(title);
} }

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : FoldersListAdapter.java
* :
* :
* :
* 1.
* 2.
* 3.
* 4. 便
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -28,53 +38,116 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
*
*
* CursorAdapterListView
*
*/
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
/**
*
*/
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, NoteColumns.ID, // 文件夹ID
NoteColumns.SNIPPET NoteColumns.SNIPPET // 文件夹名称
}; };
/** 文件夹ID列索引 */
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
/** 文件夹名称列索引 */
public static final int NAME_COLUMN = 1; public static final int NAME_COLUMN = 1;
/**
*
*
* @param context
* @param c
*/
public FoldersListAdapter(Context context, Cursor c) { public FoldersListAdapter(Context context, Cursor c) {
super(context, c); super(context, c);
// TODO Auto-generated constructor stub
} }
/**
*
* ListView
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建并返回一个新的文件夹列表项视图
return new FolderListItem(context); return new FolderListItem(context);
} }
/**
*
* ListView
*
* @param view
* @param context
* @param cursor
*/
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {
// 获取文件夹名称,对根文件夹做特殊处理
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 将文件夹名称绑定到视图
((FolderListItem) view).bind(folderName); ((FolderListItem) view).bind(folderName);
} }
} }
/**
*
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
// 获取指定位置的游标
Cursor cursor = (Cursor) getItem(position); Cursor cursor = (Cursor) getItem(position);
// 获取文件夹名称,对根文件夹做特殊处理
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
/**
*
*
*/
private class FolderListItem extends LinearLayout { private class FolderListItem extends LinearLayout {
/** 显示文件夹名称的文本视图 */
private TextView mName; private TextView mName;
/**
*
*
* @param context
*/
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);
// 从布局文件中加载视图
inflate(context, R.layout.folder_list_item, this); inflate(context, R.layout.folder_list_item, this);
// 获取文件夹名称文本视图
mName = (TextView) findViewById(R.id.tv_folder_name); mName = (TextView) findViewById(R.id.tv_folder_name);
} }
/**
*
*
* @param name
*/
public void bind(String name) { public void bind(String name) {
// 设置文件夹名称
mName.setText(name); mName.setText(name);
} }
} }
} }

@ -14,6 +14,19 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NoteEditActivity.java
* : 便
* : 便
* :
* 1. 便
* 2. 便
* 3.
* 4.
* 5.
* 6. 便
* 7. 便
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
@ -71,19 +84,44 @@ import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/**
* 便
*
* 便
*
* 便
*
*
* - 便
* - 便
* -
* -
* -
* - 便
* -
* - 便
*/
public class NoteEditActivity extends Activity implements OnClickListener, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
/**
* 便
* 访便
*/
private class HeadViewHolder { private class HeadViewHolder {
/** 显示便签修改时间的文本视图 */
public TextView tvModified; public TextView tvModified;
/** 显示提醒图标的图像视图 */
public ImageView ivAlertIcon; public ImageView ivAlertIcon;
/** 显示提醒日期的文本视图 */
public TextView tvAlertDate; public TextView tvAlertDate;
/** 设置背景颜色的按钮 */
public ImageView ibSetBgColor; public ImageView ibSetBgColor;
} }
/** 背景颜色选择器按钮ID与颜色值的映射 */
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
static { static {
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);
@ -93,6 +131,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);
} }
/** 背景颜色值与选择指示器ID的映射 */
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);
@ -102,6 +141,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
} }
/** 字体大小选择器按钮ID与字体大小值的映射 */
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
static { static {
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);
@ -110,6 +150,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);
} }
/** 字体大小值与选择指示器ID的映射 */
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>(); private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
static { static {
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
@ -118,59 +159,94 @@ public class NoteEditActivity extends Activity implements OnClickListener,
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
} }
/** 日志标签 */
private static final String TAG = "NoteEditActivity"; private static final String TAG = "NoteEditActivity";
/** 便签头部视图持有者 */
private HeadViewHolder mNoteHeaderHolder; private HeadViewHolder mNoteHeaderHolder;
/** 便签头部面板视图 */
private View mHeadViewPanel; private View mHeadViewPanel;
/** 便签背景颜色选择器视图 */
private View mNoteBgColorSelector; private View mNoteBgColorSelector;
/** 字体大小选择器视图 */
private View mFontSizeSelector; private View mFontSizeSelector;
/** 便签编辑器 */
private EditText mNoteEditor; private EditText mNoteEditor;
/** 便签编辑器面板 */
private View mNoteEditorPanel; private View mNoteEditorPanel;
/** 当前工作的便签对象 */
private WorkingNote mWorkingNote; private WorkingNote mWorkingNote;
/** 共享首选项对象 */
private SharedPreferences mSharedPrefs; private SharedPreferences mSharedPrefs;
/** 当前字体大小ID */
private int mFontSizeId; private int mFontSizeId;
/** 字体大小首选项键名 */
private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
/** 桌面快捷方式图标标题的最大长度 */
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;
/** 已勾选项的标记字符 */
public static final String TAG_CHECKED = String.valueOf('\u221A'); public static final String TAG_CHECKED = String.valueOf('\u221A');
/** 未勾选项的标记字符 */
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); public static final String TAG_UNCHECKED = String.valueOf('\u25A1');
/** 编辑文本列表容器 */
private LinearLayout mEditTextList; private LinearLayout mEditTextList;
/** 用户搜索查询字符串 */
private String mUserQuery; private String mUserQuery;
/** 用于搜索匹配的正则表达式模式 */
private Pattern mPattern; private Pattern mPattern;
/**
*
*
*
* @param savedInstanceState
*/
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
// 设置内容视图为便签编辑布局
this.setContentView(R.layout.note_edit); this.setContentView(R.layout.note_edit);
// 如果没有保存的状态且初始化活动状态失败,则结束活动
if (savedInstanceState == null && !initActivityState(getIntent())) { if (savedInstanceState == null && !initActivityState(getIntent())) {
finish(); finish();
return; return;
} }
// 初始化资源和视图
initResources(); initResources();
} }
/** /**
* Current activity may be killed when the memory is low. Once it is killed, for another time *
* user load this activity, we should restore the former state * 便
*
* @param savedInstanceState
*/ */
@Override @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState); super.onRestoreInstanceState(savedInstanceState);
// 如果有保存的便签ID尝试恢复编辑状态
if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {
// 创建查看便签的意图
Intent intent = new Intent(Intent.ACTION_VIEW); Intent intent = new Intent(Intent.ACTION_VIEW);
// 设置便签ID
intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID));
// 尝试初始化活动状态,如果失败则结束活动
if (!initActivityState(intent)) { if (!initActivityState(intent)) {
finish(); finish();
return; return;
@ -179,24 +255,36 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* 便便
*
* @param intent
* @return truefalse
*/
private boolean initActivityState(Intent intent) { private boolean initActivityState(Intent intent) {
/** /**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, * ACTION_VIEWID
* then jump to the NotesListActivity * 便
*/ */
mWorkingNote = null; mWorkingNote = null;
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
// 获取便签ID
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
// 初始化用户查询字符串为空
mUserQuery = ""; mUserQuery = "";
/** /**
* Starting from the searched result *
*/ */
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
// 从搜索数据中获取便签ID
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
// 获取用户搜索查询字符串
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
} }
// 检查便签是否存在且可见
if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
Intent jump = new Intent(this, NotesListActivity.class); Intent jump = new Intent(this, NotesListActivity.class);
startActivity(jump); startActivity(jump);

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NoteEditText.java
* : 便
* : 便
* :
* 1.
* 2.
* 3. URL
* 4.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -37,15 +47,33 @@ import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/**
* 便
*
* EditText便
* 便
* URL
*/
public class NoteEditText extends EditText { public class NoteEditText extends EditText {
/** 日志标签 */
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText";
/** 当前编辑框在列表中的索引位置 */
private int mIndex; private int mIndex;
/** 删除操作前的光标位置,用于判断是否需要合并上一个编辑框 */
private int mSelectionStartBeforeDelete; private int mSelectionStartBeforeDelete;
/** 电话号码链接前缀 */
private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_TEL = "tel:" ;
/** 网址链接前缀 */
private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_HTTP = "http:" ;
/** 邮件链接前缀 */
private static final String SCHEME_EMAIL = "mailto:" ; private static final String SCHEME_EMAIL = "mailto:" ;
/** 链接类型与对应菜单文本资源ID的映射 */
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static { static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
@ -54,56 +82,100 @@ public class NoteEditText extends EditText {
} }
/** /**
* Call by the {@link NoteEditActivity} to delete or add edit text *
* NoteEditActivity
*/ */
public interface OnTextViewChangeListener { 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); void onEditTextDelete(int index, String text);
/** /**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} *
* happen *
* @param index
* @param text
*/ */
void onEditTextEnter(int index, String 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); void onTextChange(int index, boolean hasText);
} }
/** 文本视图变化监听器 */
private OnTextViewChangeListener mOnTextViewChangeListener; private OnTextViewChangeListener mOnTextViewChangeListener;
/**
*
*
* @param context
*/
public NoteEditText(Context context) { public NoteEditText(Context context) {
super(context, null); super(context, null);
mIndex = 0; mIndex = 0;
} }
/**
*
*
* @param index
*/
public void setIndex(int index) { public void setIndex(int index) {
mIndex = index; mIndex = index;
} }
/**
*
*
* @param listener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
/**
*
*
* @param context
* @param attrs
*/
public NoteEditText(Context context, AttributeSet attrs) { public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle); super(context, attrs, android.R.attr.editTextStyle);
} }
/**
*
*
* @param context
* @param attrs
* @param defStyle
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
// TODO Auto-generated constructor stub // TODO Auto-generated constructor stub
} }
/**
*
* 使
*
* @param event
* @return
*/
@Override @Override
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
// 计算触摸点在文本中的精确位置,并设置光标
int x = (int) event.getX(); int x = (int) event.getX();
int y = (int) event.getY(); int y = (int) event.getY();
x -= getTotalPaddingLeft(); x -= getTotalPaddingLeft();
@ -121,15 +193,25 @@ public class NoteEditText extends EditText {
return super.onTouchEvent(event); return super.onTouchEvent(event);
} }
/**
*
*
*
* @param keyCode
* @param event
* @return
*/
@Override @Override
public boolean onKeyDown(int keyCode, KeyEvent event) { public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { switch (keyCode) {
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
// 如果设置了监听器回车键由Activity处理
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
return false; return false;
} }
break; break;
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
// 记录删除前的光标位置,用于判断是否需要与上一个编辑框合并
mSelectionStartBeforeDelete = getSelectionStart(); mSelectionStartBeforeDelete = getSelectionStart();
break; break;
default: default:
@ -138,11 +220,21 @@ public class NoteEditText extends EditText {
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event);
} }
/**
*
*
*
*
* @param keyCode
* @param event
* @return
*/
@Override @Override
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) { switch(keyCode) {
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
// 当光标在文本开头且不是第一个编辑框时,删除当前编辑框
if (0 == mSelectionStartBeforeDelete && mIndex != 0) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true; return true;
@ -153,9 +245,11 @@ public class NoteEditText extends EditText {
break; break;
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
// 获取光标位置,分割文本
int selectionStart = getSelectionStart(); int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString(); String text = getText().subSequence(selectionStart, length()).toString();
setText(getText().subSequence(0, selectionStart)); setText(getText().subSequence(0, selectionStart));
// 通知监听器创建新的编辑框
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else { } else {
Log.d(TAG, "OnTextViewChangeListener was not seted"); Log.d(TAG, "OnTextViewChangeListener was not seted");
@ -167,9 +261,18 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event); return super.onKeyUp(keyCode, event);
} }
/**
*
*
*
* @param focused
* @param direction
* @param previouslyFocusedRect
*/
@Override @Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
// 当失去焦点且文本为空时,通知监听器
if (!focused && TextUtils.isEmpty(getText())) { if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false); mOnTextViewChangeListener.onTextChange(mIndex, false);
} else { } else {
@ -179,8 +282,15 @@ public class NoteEditText extends EditText {
super.onFocusChanged(focused, direction, previouslyFocusedRect); super.onFocusChanged(focused, direction, previouslyFocusedRect);
} }
/**
*
* URL
*
* @param menu
*/
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onCreateContextMenu(ContextMenu menu) {
// 检查文本中是否包含URL链接
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {
int selStart = getSelectionStart(); int selStart = getSelectionStart();
int selEnd = getSelectionEnd(); int selEnd = getSelectionEnd();
@ -188,8 +298,10 @@ public class NoteEditText extends EditText {
int min = Math.min(selStart, selEnd); int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd); int max = Math.max(selStart, selEnd);
// 获取选中区域内的所有URL链接
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) { if (urls.length == 1) {
// 根据链接类型确定菜单文本
int defaultResId = 0; int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) { for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) { if(urls[0].getURL().indexOf(schema) >= 0) {
@ -202,10 +314,11 @@ public class NoteEditText extends EditText {
defaultResId = R.string.note_link_other; defaultResId = R.string.note_link_other;
} }
// 添加菜单项并设置点击监听器
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() { new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
// goto a new intent // 执行链接点击操作
urls[0].onClick(NoteEditText.this); urls[0].onClick(NoteEditText.this);
return true; return true;
} }

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NoteItemData.java
* : 便
* : 便便访
* :
* 1. 便
* 2. 便访
* 3. 便
* 4. 便
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -25,8 +35,15 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
/**
* 便
*
* 便便
* 访
* 便便
*/
public class NoteItemData { public class NoteItemData {
/** 数据库查询投影,定义需要获取的列 */
static final String [] PROJECTION = new String [] { static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -42,41 +59,79 @@ public class NoteItemData {
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
/** 投影中ID列的索引 */
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
/** 投影中提醒日期列的索引 */
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
/** 投影中背景颜色ID列的索引 */
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
/** 投影中创建日期列的索引 */
private static final int CREATED_DATE_COLUMN = 3; private static final int CREATED_DATE_COLUMN = 3;
/** 投影中是否有附件列的索引 */
private static final int HAS_ATTACHMENT_COLUMN = 4; private static final int HAS_ATTACHMENT_COLUMN = 4;
/** 投影中修改日期列的索引 */
private static final int MODIFIED_DATE_COLUMN = 5; private static final int MODIFIED_DATE_COLUMN = 5;
/** 投影中便签数量列的索引 */
private static final int NOTES_COUNT_COLUMN = 6; private static final int NOTES_COUNT_COLUMN = 6;
/** 投影中父ID列的索引 */
private static final int PARENT_ID_COLUMN = 7; private static final int PARENT_ID_COLUMN = 7;
/** 投影中摘要列的索引 */
private static final int SNIPPET_COLUMN = 8; private static final int SNIPPET_COLUMN = 8;
/** 投影中类型列的索引 */
private static final int TYPE_COLUMN = 9; private static final int TYPE_COLUMN = 9;
/** 投影中小部件ID列的索引 */
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
/** 投影中小部件类型列的索引 */
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
/** 便签ID */
private long mId; private long mId;
/** 提醒日期 */
private long mAlertDate; private long mAlertDate;
/** 背景颜色ID */
private int mBgColorId; private int mBgColorId;
/** 创建日期 */
private long mCreatedDate; private long mCreatedDate;
/** 是否有附件 */
private boolean mHasAttachment; private boolean mHasAttachment;
/** 修改日期 */
private long mModifiedDate; private long mModifiedDate;
/** 便签数量(对于文件夹) */
private int mNotesCount; private int mNotesCount;
/** 父ID所属文件夹ID */
private long mParentId; private long mParentId;
/** 便签摘要(显示内容) */
private String mSnippet; private String mSnippet;
/** 便签类型 */
private int mType; private int mType;
/** 小部件ID */
private int mWidgetId; private int mWidgetId;
/** 小部件类型 */
private int mWidgetType; private int mWidgetType;
/** 联系人姓名(通话记录便签) */
private String mName; private String mName;
/** 电话号码(通话记录便签) */
private String mPhoneNumber; private String mPhoneNumber;
/** 是否为列表中的最后一项 */
private boolean mIsLastItem; private boolean mIsLastItem;
/** 是否为列表中的第一项 */
private boolean mIsFirstItem; private boolean mIsFirstItem;
/** 是否为列表中的唯一一项 */
private boolean mIsOnlyOneItem; private boolean mIsOnlyOneItem;
/** 是否为文件夹后的单个便签 */
private boolean mIsOneNoteFollowingFolder; private boolean mIsOneNoteFollowingFolder;
/** 是否为文件夹后的多个便签中的一个 */
private boolean mIsMultiNotesFollowingFolder; private boolean mIsMultiNotesFollowingFolder;
/**
* 便
*
* @param context
* @param cursor 便
*/
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
// 从游标中提取基本属性
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
@ -86,16 +141,20 @@ public class NoteItemData {
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN);
// 清理便签摘要中的特殊标记
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, ""); NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN); mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
// 处理通话记录便签的特殊逻辑
mPhoneNumber = ""; mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
// 获取通话记录关联的电话号码
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) { if (!TextUtils.isEmpty(mPhoneNumber)) {
// 尝试获取联系人姓名,如果没有则使用电话号码作为名称
mName = Contact.getContact(context, mPhoneNumber); mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) { if (mName == null) {
mName = mPhoneNumber; mName = mPhoneNumber;
@ -106,27 +165,40 @@ public class NoteItemData {
if (mName == null) { if (mName == null) {
mName = ""; mName = "";
} }
// 检查便签在列表中的位置状态
checkPostion(cursor); checkPostion(cursor);
} }
/**
* 便
* 便
*
* @param cursor 便
*/
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
// 检查是否为最后一项、第一项或唯一一项
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false; mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false; mIsOneNoteFollowingFolder = false;
// 检查是否为文件夹后的便签
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition(); int position = cursor.getPosition();
if (cursor.moveToPrevious()) { if (cursor.moveToPrevious()) {
// 检查前一项是否为文件夹
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) { if (cursor.getCount() > (position + 1)) {
// 文件夹后有多个便签
mIsMultiNotesFollowingFolder = true; mIsMultiNotesFollowingFolder = true;
} else { } else {
// 文件夹后只有一个便签
mIsOneNoteFollowingFolder = true; mIsOneNoteFollowingFolder = true;
} }
} }
// 恢复游标位置
if (!cursor.moveToNext()) { if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back"); throw new IllegalStateException("cursor move to previous but can't move back");
} }
@ -134,90 +206,202 @@ public class NoteItemData {
} }
} }
/**
* 便
*
* @return 便truefalse
*/
public boolean isOneFollowingFolder() { public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder; return mIsOneNoteFollowingFolder;
} }
/**
* 便
*
* @return 便truefalse
*/
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;
} }
/**
*
*
* @return truefalse
*/
public boolean isLast() { public boolean isLast() {
return mIsLastItem; return mIsLastItem;
} }
/**
* 便
*
* @return
*/
public String getCallName() { public String getCallName() {
return mName; return mName;
} }
/**
*
*
* @return truefalse
*/
public boolean isFirst() { public boolean isFirst() {
return mIsFirstItem; return mIsFirstItem;
} }
/**
*
*
* @return truefalse
*/
public boolean isSingle() { public boolean isSingle() {
return mIsOnlyOneItem; return mIsOnlyOneItem;
} }
/**
* 便ID
*
* @return 便ID
*/
public long getId() { public long getId() {
return mId; return mId;
} }
/**
*
*
* @return
*/
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
/**
*
*
* @return
*/
public long getCreatedDate() { public long getCreatedDate() {
return mCreatedDate; return mCreatedDate;
} }
/**
*
*
* @return truefalse
*/
public boolean hasAttachment() { public boolean hasAttachment() {
return mHasAttachment; return mHasAttachment;
} }
/**
*
*
* @return
*/
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
/**
* ID
*
* @return ID
*/
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
/**
* IDID
*
* @return ID
*/
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
/**
* 便
*
* @return 便
*/
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; return mNotesCount;
} }
/**
* ID
* getParentId()
*
* @return ID
*/
public long getFolderId () { public long getFolderId () {
return mParentId; return mParentId;
} }
/**
* 便
*
* @return 便便
*/
public int getType() { public int getType() {
return mType; return mType;
} }
/**
*
*
* @return
*/
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
/**
* ID
*
* @return ID
*/
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
/**
* 便
*
* @return 便
*/
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
/**
*
*
* @return truefalse
*/
public boolean hasAlert() { public boolean hasAlert() {
return (mAlertDate > 0); return (mAlertDate > 0);
} }
/**
* 便
*
* @return 便truefalse
*/
public boolean isCallRecord() { public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber)); return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
} }
/**
* 便
*
* @param cursor 便
* @return 便
*/
public static int getNoteType(Cursor cursor) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }

@ -14,6 +14,18 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NotesListActivity.java
* : 便
* : 便便
* :
* 1. 便
* 2. 便
* 3. 便
* 4.
* 5. 便
* 6. Google
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.Activity; import android.app.Activity;
@ -78,63 +90,110 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashSet; import java.util.HashSet;
/**
* 便
*
* 便便
* 便
* 便
*/
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
/** 便签列表查询标记 */
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
/** 文件夹列表查询标记 */
private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int FOLDER_LIST_QUERY_TOKEN = 1;
/** 文件夹删除菜单项ID */
private static final int MENU_FOLDER_DELETE = 0; private static final int MENU_FOLDER_DELETE = 0;
/** 文件夹查看菜单项ID */
private static final int MENU_FOLDER_VIEW = 1; private static final int MENU_FOLDER_VIEW = 1;
/** 文件夹重命名菜单项ID */
private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final int MENU_FOLDER_CHANGE_NAME = 2;
/** 首次使用应用时添加介绍便签的首选项键 */
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
/**
*
*
*/
private enum ListEditState { private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER /** 便签列表状态 */
NOTE_LIST,
/** 子文件夹状态 */
SUB_FOLDER,
/** 通话记录文件夹状态 */
CALL_RECORD_FOLDER
}; };
/** 当前列表编辑状态 */
private ListEditState mState; private ListEditState mState;
/** 后台查询处理器 */
private BackgroundQueryHandler mBackgroundQueryHandler; private BackgroundQueryHandler mBackgroundQueryHandler;
/** 便签列表适配器 */
private NotesListAdapter mNotesListAdapter; private NotesListAdapter mNotesListAdapter;
/** 便签列表视图 */
private ListView mNotesListView; private ListView mNotesListView;
/** 添加新便签按钮 */
private Button mAddNewNote; private Button mAddNewNote;
/** 是否分发触摸事件的标志 */
private boolean mDispatch; private boolean mDispatch;
/** 触摸事件原始Y坐标 */
private int mOriginY; private int mOriginY;
/** 触摸事件分发Y坐标 */
private int mDispatchY; private int mDispatchY;
/** 标题栏文本视图 */
private TextView mTitleBar; private TextView mTitleBar;
/** 当前文件夹ID */
private long mCurrentFolderId; private long mCurrentFolderId;
/** 内容解析器 */
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
/** 多选模式回调 */
private ModeCallback mModeCallBack; private ModeCallback mModeCallBack;
/** 日志标签 */
private static final String TAG = "NotesListActivity"; private static final String TAG = "NotesListActivity";
/** 便签列表视图滚动速率 */
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
/** 当前焦点便签数据项 */
private NoteItemData mFocusNoteDataItem; private NoteItemData mFocusNoteDataItem;
/** 普通便签查询条件 */
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
/** 根文件夹查询条件 */
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)"; + NoteColumns.NOTES_COUNT + ">0)";
/** 打开便签请求码 */
private final static int REQUEST_CODE_OPEN_NODE = 102; private final static int REQUEST_CODE_OPEN_NODE = 102;
/** 新建便签请求码 */
private final static int REQUEST_CODE_NEW_NODE = 103; private final static int REQUEST_CODE_NEW_NODE = 103;
/**
*
*
* @param savedInstanceState
*/
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -142,27 +201,41 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
initResources(); initResources();
/** /**
* Insert an introduction when user firstly use this application * 使便
*/ */
setAppInfoFromRawRes(); setAppInfoFromRawRes();
} }
/**
*
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
// 便签编辑成功后刷新列表
mNotesListAdapter.changeCursor(null); mNotesListAdapter.changeCursor(null);
} else { } else {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data);
} }
} }
/**
*
* 使便
*/
private void setAppInfoFromRawRes() { private void setAppInfoFromRawRes() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
// 首次使用应用,需要添加介绍便签
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
InputStream in = null; InputStream in = null;
try { try {
// 读取介绍文件内容
in = getResources().openRawResource(R.raw.introduction); in = getResources().openRawResource(R.raw.introduction);
if (in != null) { if (in != null) {
InputStreamReader isr = new InputStreamReader(in); InputStreamReader isr = new InputStreamReader(in);
@ -190,11 +263,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
// 创建介绍便签并保存
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED); ResourceParser.RED);
note.setWorkingText(sb.toString()); note.setWorkingText(sb.toString());
if (note.saveNote()) { if (note.saveNote()) {
// 保存成功后,更新首选项标记,下次不再添加介绍
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else { } else {
Log.e(TAG, "Save introduction note error"); Log.e(TAG, "Save introduction note error");
@ -203,26 +278,42 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
* 便
*/
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
startAsyncNotesListQuery(); startAsyncNotesListQuery();
} }
/**
*
*
*/
private void initResources() { private void initResources() {
mContentResolver = this.getContentResolver(); mContentResolver = this.getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
// 初始化列表视图
mNotesListView = (ListView) findViewById(R.id.notes_list); mNotesListView = (ListView) findViewById(R.id.notes_list);
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false); null, false);
mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemClickListener(new OnListItemClickListener());
mNotesListView.setOnItemLongClickListener(this); mNotesListView.setOnItemLongClickListener(this);
// 设置列表适配器
mNotesListAdapter = new NotesListAdapter(this); mNotesListAdapter = new NotesListAdapter(this);
mNotesListView.setAdapter(mNotesListAdapter); mNotesListView.setAdapter(mNotesListAdapter);
// 初始化添加新便签按钮
mAddNewNote = (Button) findViewById(R.id.btn_new_note); mAddNewNote = (Button) findViewById(R.id.btn_new_note);
mAddNewNote.setOnClickListener(this); mAddNewNote.setOnClickListener(this);
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
// 初始化其他变量
mDispatch = false; mDispatch = false;
mDispatchY = 0; mDispatchY = 0;
mOriginY = 0; mOriginY = 0;
@ -231,17 +322,40 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mModeCallBack = new ModeCallback(); mModeCallBack = new ModeCallback();
} }
/**
*
*
* 便
* ActionMode
*/
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
/** 下拉菜单 */
private DropdownMenu mDropDownMenu; private DropdownMenu mDropDownMenu;
/** 操作模式 */
private ActionMode mActionMode; private ActionMode mActionMode;
/** 移动菜单项 */
private MenuItem mMoveMenu; private MenuItem mMoveMenu;
/**
*
*
*
* @param mode
* @param menu
* @return
*/
public boolean onCreateActionMode(ActionMode mode, Menu menu) { public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// 加载菜单资源
getMenuInflater().inflate(R.menu.note_list_options, menu); getMenuInflater().inflate(R.menu.note_list_options, menu);
menu.findItem(R.id.delete).setOnMenuItemClickListener(this); menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
mMoveMenu = menu.findItem(R.id.move); mMoveMenu = menu.findItem(R.id.move);
// 根据当前文件夹决定是否显示移动菜单
if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
|| DataUtils.getUserFolderCount(mContentResolver) == 0) { || DataUtils.getUserFolderCount(mContentResolver) == 0) {
// 通话记录文件夹或没有用户文件夹时不显示移动菜单
mMoveMenu.setVisible(false); mMoveMenu.setVisible(false);
} else { } else {
mMoveMenu.setVisible(true); mMoveMenu.setVisible(true);

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NotesListAdapter.java
* : 便
* : ListView
* :
* 1.
* 2.
* 3.
* 4. 访
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -30,19 +40,46 @@ import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
/**
* 便
*
* CursorAdapter便
*
* 便访
*/
public class NotesListAdapter extends CursorAdapter { public class NotesListAdapter extends CursorAdapter {
/** 日志标签 */
private static final String TAG = "NotesListAdapter"; private static final String TAG = "NotesListAdapter";
/** 上下文环境 */
private Context mContext; private Context mContext;
/** 选中项索引的映射表 */
private HashMap<Integer, Boolean> mSelectedIndex; private HashMap<Integer, Boolean> mSelectedIndex;
/** 便签数量(不包括文件夹) */
private int mNotesCount; private int mNotesCount;
/** 是否处于多选模式 */
private boolean mChoiceMode; private boolean mChoiceMode;
/**
*
* ID
*/
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
/** 小部件ID */
public int widgetId; public int widgetId;
/** 小部件类型 */
public int widgetType; public int widgetType;
}; };
/**
*
*
* @param context
*/
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); mSelectedIndex = new HashMap<Integer, Boolean>();
@ -50,38 +87,77 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0; mNotesCount = 0;
} }
/**
*
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); return new NotesListItem(context);
} }
/**
*
*
* @param view
* @param context
* @param cursor
*/
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
// 创建数据对象并绑定到视图
NoteItemData itemData = new NoteItemData(context, cursor); NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode, ((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition())); isSelectedItem(cursor.getPosition()));
} }
} }
/**
*
*
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked);
notifyDataSetChanged(); notifyDataSetChanged();
} }
/**
*
*
* @return truefalse
*/
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }
/**
*
*
* @param mode
*/
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
// 清空选中项
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
/**
* 便
*
* @param checked
*/
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { if (cursor.moveToPosition(i)) {
// 只选择便签,不选择文件夹
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked); setCheckedItem(i, checked);
} }
@ -89,6 +165,11 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
/**
* ID
*
* @return IDHashSet
*/
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
@ -105,6 +186,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
/**
*
*
* @return HashSet
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
@ -128,6 +214,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
/**
*
*
* @return
*/
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
if (null == values) { if (null == values) {
@ -143,11 +234,22 @@ public class NotesListAdapter extends CursorAdapter {
return count; return count;
} }
/**
* 便
*
* @return 便truefalse
*/
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount);
} }
/**
*
*
* @param position
* @return truefalse
*/
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
@ -155,23 +257,38 @@ public class NotesListAdapter extends CursorAdapter {
return mSelectedIndex.get(position); return mSelectedIndex.get(position);
} }
/**
*
* 便
*/
@Override @Override
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); super.onContentChanged();
calcNotesCount(); calcNotesCount();
} }
/**
*
* 便
*
* @param cursor
*/
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);
calcNotesCount(); calcNotesCount();
} }
/**
* 便
*
*/
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i); Cursor c = (Cursor) getItem(i);
if (c != null) { if (c != null) {
// 只计算便签,不计算文件夹
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++; mNotesCount++;
} }

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NotesListItem.java
* : 便
* : 便UI
* :
* 1. 便
* 2. 便
* 3.
* 4. 便
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.content.Context; import android.content.Context;
@ -29,18 +39,42 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
* 便
*
* LinearLayout便
*
*
*/
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
/** 提醒图标视图 */
private ImageView mAlert; private ImageView mAlert;
/** 标题文本视图 */
private TextView mTitle; private TextView mTitle;
/** 时间文本视图 */
private TextView mTime; private TextView mTime;
/** 通话联系人名称文本视图(用于通话记录便签) */
private TextView mCallName; private TextView mCallName;
/** 列表项关联的数据对象 */
private NoteItemData mItemData; private NoteItemData mItemData;
/** 多选模式下的复选框 */
private CheckBox mCheckBox; private CheckBox mCheckBox;
/**
*
*
* @param context
*/
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context);
// 加载列表项布局
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this);
// 初始化视图组件
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title); mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time); mTime = (TextView) findViewById(R.id.tv_time);
@ -48,7 +82,17 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); 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) { public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 处理多选模式下的复选框显示
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked); mCheckBox.setChecked(checked);
@ -57,7 +101,9 @@ public class NotesListItem extends LinearLayout {
} }
mItemData = data; mItemData = data;
// 根据不同类型的便签设置不同的显示效果
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
// 通话记录文件夹的显示
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
@ -65,6 +111,7 @@ public class NotesListItem extends LinearLayout {
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); + 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) { } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
// 通话记录便签的显示
mCallName.setVisibility(View.VISIBLE); mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName()); mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
@ -76,15 +123,18 @@ public class NotesListItem extends LinearLayout {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} }
} else { } else {
// 普通便签和文件夹的显示
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
// 文件夹显示
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count, + context.getString(R.string.format_folder_files_count,
data.getNotesCount())); data.getNotesCount()));
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE);
} else { } else {
// 普通便签显示
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);
@ -94,28 +144,46 @@ public class NotesListItem extends LinearLayout {
} }
} }
} }
// 设置修改时间
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 设置背景样式
setBackground(data); setBackground(data);
} }
/**
* 便
*
* @param data
*/
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
// 根据便签在列表中的位置选择不同的背景资源
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {
// 单独一个便签或文件夹后的单个便签
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) { } else if (data.isLast()) {
// 列表中最后一个便签
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) { } else if (data.isFirst() || data.isMultiFollowingFolder()) {
// 列表中第一个便签或文件夹后的多个便签中的第一个
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else { } else {
// 列表中间的便签
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
} }
} else { } else {
// 文件夹使用固定的背景样式
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }
/**
*
*
* @return
*/
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }

@ -14,6 +14,16 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NotesPreferenceActivity.java
* : 便
* : Google
* :
* 1. Google
* 2.
* 3.
* 4.
*/
package net.micode.notes.ui; package net.micode.notes.ui;
import android.accounts.Account; import android.accounts.Account;
@ -47,53 +57,81 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
/**
* 便
*
* PreferenceActivity便
* Google
*
*/
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
/** 首选项文件名 */
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";
/** 同步账户名称的首选项键 */
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; 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_LAST_SYNC_TIME = "pref_last_sync_time";
/** 背景颜色设置的首选项键 */
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; 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 PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
/** 账户筛选的权限键 */
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
/** 账户设置分类 */
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
/** Google任务同步广播接收器 */
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
/** 原始账户列表,用于检测新添加的账户 */
private Account[] mOriAccounts; private Account[] mOriAccounts;
/** 是否已添加新账户的标志 */
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
/**
*
*
* @param icicle
*/
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ /* 设置应用图标用于导航 */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
// 加载首选项资源
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
// 注册同步服务广播接收器
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
mOriAccounts = null; mOriAccounts = null;
// 添加设置页面头部视图
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
} }
/**
*
* UI
*/
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new // 如果用户添加了新账户,需要自动设置为同步账户
// account
if (mHasAddedAccount) { if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
@ -106,6 +144,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
if (!found) { if (!found) {
// 找到新添加的账户,设置为同步账户
setSyncAccount(accountNew.name); setSyncAccount(accountNew.name);
break; break;
} }
@ -113,9 +152,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
// 刷新UI显示
refreshUI(); refreshUI();
} }
/**
*
*/
@Override @Override
protected void onDestroy() { protected void onDestroy() {
if (mReceiver != null) { if (mReceiver != null) {
@ -124,6 +167,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
super.onDestroy(); super.onDestroy();
} }
/**
*
*
*/
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll(); mAccountCategory.removeAll();
@ -135,14 +182,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // 首次设置账户
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // 如果账户已设置,需要提示用户更改的风险
// user about the risk
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
} }
} else { } else {
// 同步进行中,不能更改账户
Toast.makeText(NotesPreferenceActivity.this, 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(); .show();
@ -154,12 +201,17 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
/**
*
*
*/
private void loadSyncButton() { private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state // 根据同步状态设置按钮文本和点击事件
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
// 同步进行中,显示取消同步按钮
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
@ -167,6 +219,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} else { } else {
// 未同步,显示立即同步按钮
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
@ -174,13 +227,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} }
// 只有设置了同步账户才启用同步按钮
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time // 设置上次同步时间显示
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
// 同步进行中,显示进度信息
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
} else { } else {
// 未同步,显示上次同步时间
long lastSyncTime = getLastSyncTime(this); long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) { if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
@ -193,14 +249,23 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
/**
* UI
*
*/
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
/**
*
* Google
*/
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 设置对话框标题和副标题
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
@ -210,6 +275,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null); dialogBuilder.setPositiveButton(null, null);
// 获取所有Google账户
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this); String defAccount = getSyncAccountName(this);
@ -217,6 +283,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mHasAddedAccount = false; mHasAddedAccount = false;
if (accounts.length > 0) { if (accounts.length > 0) {
// 显示账户列表
CharSequence[] items = new CharSequence[accounts.length]; CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; final CharSequence[] itemMapping = items;
int checkedItem = -1; int checkedItem = -1;
@ -230,6 +297,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
// 选择账户后设置为同步账户
setSyncAccount(itemMapping[which].toString()); setSyncAccount(itemMapping[which].toString());
dialog.dismiss(); dialog.dismiss();
refreshUI(); refreshUI();
@ -237,12 +305,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
} }
// 添加"添加账户"选项
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show(); final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() { addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
// 标记已添加账户,跳转到添加账户界面
mHasAddedAccount = true; mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
@ -254,9 +324,14 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
} }
/**
*
*
*/
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 设置对话框标题和警告信息
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
@ -265,6 +340,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
// 设置选项菜单
CharSequence[] menuItemArray = new CharSequence[] { CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
@ -273,8 +349,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (which == 0) { if (which == 0) {
// 更改账户
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else if (which == 1) { } else if (which == 1) {
// 移除账户
removeSyncAccount(); removeSyncAccount();
refreshUI(); refreshUI();
} }
@ -283,13 +361,24 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.show(); dialogBuilder.show();
} }
/**
* Google
*
* @return Google
*/
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
/**
*
*
* @param account
*/
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
// 保存账户名称到首选项
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
if (account != null) { if (account != null) {
@ -299,10 +388,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
editor.commit(); editor.commit();
// clean up last sync time // 清除上次同步时间
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// clean up local gtask related info // 清除本地Google任务相关信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -312,13 +401,19 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}).start(); }).start();
// 显示设置成功提示
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
} }
} }
/**
*
*
*/
private void removeSyncAccount() { private void removeSyncAccount() {
// 从首选项中移除账户名称和同步时间
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
@ -329,7 +424,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
editor.commit(); editor.commit();
// clean up local gtask related info // 清除本地Google任务相关信息
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -340,12 +435,24 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start(); }).start();
} }
/**
*
*
* @param context
* @return
*/
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
/**
*
*
* @param context
* @param time
*/
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
@ -354,18 +461,33 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit(); editor.commit();
} }
/**
*
*
* @param context
* @return 0
*/
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
/**
* Google广
* 广
*/
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
/**
* 广
* UI
*/
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI(); refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
// 同步进行中,更新进度显示
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
@ -374,9 +496,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
/**
*
*
* @param item
* @return
*/
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
// 返回主界面
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NoteWidgetProvider.java
* : 便
* : 便便
*/
package net.micode.notes.widget; package net.micode.notes.widget;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -32,24 +37,54 @@ import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity; import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
/**
* 便
*
* AppWidgetProvider便
* 便
* 2x4x
*/
public abstract class NoteWidgetProvider extends AppWidgetProvider { public abstract class NoteWidgetProvider extends AppWidgetProvider {
/**
* 便
* 便
*/
public static final String [] PROJECTION = new String [] { public static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID, // 便签ID
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.SNIPPET 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; */
public static final int COLUMN_ID = 0; // ID列索引
public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID列索引
public static final int COLUMN_SNIPPET = 2; // 内容摘要列索引
/**
*
*/
private static final String TAG = "NoteWidgetProvider"; private static final String TAG = "NoteWidgetProvider";
/**
*
*
*
*
* @param context
* @param appWidgetIds ID
*/
@Override @Override
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
// 创建更新数据
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
// 将小部件ID设置为无效值表示该便签不再与任何小部件关联
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// 遍历所有被删除的小部件ID
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
// 更新数据库清除小部件ID与便签的关联
context.getContentResolver().update(Notes.CONTENT_NOTE_URI, context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values, values,
NoteColumns.WIDGET_ID + "=?", NoteColumns.WIDGET_ID + "=?",
@ -57,7 +92,16 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
} }
} }
/**
* ID便
*
* @param context
* @param widgetId ID
* @return 便CursorCursor
*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) { private Cursor getNoteWidgetInfo(Context context, int widgetId) {
// 查询与指定小部件ID关联的便签数据
// 条件匹配小部件ID且不在回收站中
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
@ -65,68 +109,130 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
null); null);
} }
/**
*
*
*
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用私有更新方法隐私模式设为false
update(context, appWidgetManager, appWidgetIds, false); update(context, appWidgetManager, appWidgetIds, false);
} }
/**
*
*
* ID
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
* @param privacyMode 便
*/
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) { boolean privacyMode) {
// 遍历所有需要更新的小部件
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
// 检查小部件ID是否有效
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
// 设置默认背景ID和空内容
int bgId = ResourceParser.getDefaultBgId(context); int bgId = ResourceParser.getDefaultBgId(context);
String snippet = ""; String snippet = "";
// 创建打开便签编辑界面的Intent
Intent intent = new Intent(context, NoteEditActivity.class); Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
// 获取与小部件关联的便签信息
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) { if (c != null && c.moveToFirst()) {
// 检查是否有多个便签关联到同一个小部件ID异常情况
if (c.getCount() > 1) { if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close(); c.close();
return; return;
} }
// 提取便签内容和背景颜色
snippet = c.getString(COLUMN_SNIPPET); snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID); bgId = c.getInt(COLUMN_BG_COLOR_ID);
// 设置Intent参数用于打开现有便签
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
} else { } else {
// 没有关联便签,设置默认提示文本
snippet = context.getResources().getString(R.string.widget_havenot_content); snippet = context.getResources().getString(R.string.widget_havenot_content);
// 设置Intent参数用于创建新便签
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
} }
// 关闭游标
if (c != null) { if (c != null) {
c.close(); c.close();
} }
// 创建远程视图并设置背景
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
/** /**
* Generate the pending intent to start host for the widget * PendingIntent
*/ */
PendingIntent pendingIntent = null; PendingIntent pendingIntent = null;
if (privacyMode) { if (privacyMode) {
// 隐私模式下,显示提示文本,点击打开便签列表
rv.setTextViewText(R.id.widget_text, rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode)); context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent( pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else { } else {
// 正常模式下,显示便签内容,点击打开便签编辑界面
rv.setTextViewText(R.id.widget_text, snippet); rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent.FLAG_UPDATE_CURRENT);
} }
// 设置点击事件
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
// 更新小部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
} }
} }
} }
/**
* ID
*
* IDID
*
*
* @param bgId ID
* @return ID
*/
protected abstract int getBgResourceId(int bgId); protected abstract int getBgResourceId(int bgId);
/**
* ID
*
*
*
* @return ID
*/
protected abstract int getLayoutId(); protected abstract int getLayoutId();
/**
*
*
*
*
* @return
*/
protected abstract int getWidgetType(); protected abstract int getWidgetType();
} }

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NoteWidgetProvider_2x.java
* : 2x便
* : 2x便NoteWidgetProvider
*/
package net.micode.notes.widget; package net.micode.notes.widget;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -23,23 +28,61 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
/**
* 2x便
*
* NoteWidgetProvider2x便
* 2xAndroid2x2
*/
public class NoteWidgetProvider_2x extends NoteWidgetProvider { public class NoteWidgetProvider_2x extends NoteWidgetProvider {
/**
*
*
*
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的update方法更新小部件
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
/**
* ID
*
* 2x
*
* @return 2xID
*/
@Override @Override
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_2x; return R.layout.widget_2x;
} }
/**
* ID
*
* ID2x
*
* @param bgId ID
* @return 2xID
*/
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
// 使用ResourceParser工具类获取2x小部件的背景资源
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
} }
/**
*
*
* 2x
*
* @return 2x
*/
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X; return Notes.TYPE_WIDGET_2X;

@ -14,6 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
/**
* : NoteWidgetProvider_4x.java
* : 4x便
* : 4x便NoteWidgetProvider
*/
package net.micode.notes.widget; package net.micode.notes.widget;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
@ -23,22 +28,61 @@ import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
/**
* 4x便
*
* NoteWidgetProvider4x便
* 4xAndroid4x42x
* 便
*/
public class NoteWidgetProvider_4x extends NoteWidgetProvider { public class NoteWidgetProvider_4x extends NoteWidgetProvider {
/**
*
*
*
*
* @param context
* @param appWidgetManager
* @param appWidgetIds ID
*/
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// 调用父类的update方法更新小部件
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
} }
/**
* ID
*
* 4x
*
* @return 4xID
*/
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_4x; return R.layout.widget_4x;
} }
/**
* ID
*
* ID4x
*
* @param bgId ID
* @return 4xID
*/
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
// 使用ResourceParser工具类获取4x小部件的背景资源
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
} }
/**
*
*
* 4x
*
* @return 4x
*/
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; return Notes.TYPE_WIDGET_4X;

Loading…
Cancel
Save