Compare commits

...

15 Commits

Author SHA1 Message Date
JTXjtx ea9e01357a 第二次完善质量分析报告
1 week ago
JTXjtx 59a2ac89d1 完善小米便签质量分析报告
1 week ago
JTXjtx 949fad2d88 Merge branch 'master' of https://bdgit.educoder.net/p7tupf26b/git
3 weeks ago
JTXjtx a9276ef573 修改并完善了部分原来小米便签泛读报告的内容,增加代码标注部分
3 weeks ago
JTXjtx b55f5c4967 Merge branch 'master' of https://bdgit.educoder.net/p7tupf26b/git into jiangtianxiang_branch
3 weeks ago
JTXjtx 9039cfdca8 增加代码标注行数等信息,且将之前的泛读报告文档做了一些补充
3 weeks ago
p7tupf26b 064fe90f93 Merge pull request '将小米便签的报告重命名后合并' (#9) from jiangtianxiang_branch into master
3 weeks ago
JTXjtx 59343480ab Merge branch 'master' of https://bdgit.educoder.net/p7tupf26b/git into jiangtianxiang_branch
3 weeks ago
JTXjtx b4d68f5c9e 修改报告
3 weeks ago
JTXjtx f4067e0ee5 Merge branch 'jiangtianxiang_branch' of https://bdgit.educoder.net/p7tupf26b/git into jiangtianxiang_branch
3 weeks ago
JTXjtx 27b268c121 Merge branch 'jiangtianxiang_branch' of https://bdgit.educoder.net/p7tupf26b/git
3 weeks ago
JTXjtx 6047bb5df7 Merge branch 'jiangtianxiang_branch' of https://bdgit.educoder.net/p7tupf26b/git
3 weeks ago
JTXjtx acb6972819 增加对于小米便签开源代码的注释
3 weeks ago
JTXjtx 08ab1fc652 增加对于小米便签开源代码的注释
3 weeks ago
mbls3xqnp 8cd4ff2539 Merge pull request '添加部分注释' (#5) from develop into master
3 weeks ago

@ -0,0 +1,43 @@
package net.micode.notes;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
/**
*
* <p>
*
*
* </p>
*/
public class MainActivity extends AppCompatActivity {
/**
*
* <p>
*
* </p>
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 启用边到边显示模式
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
// 设置窗口边距监听器,自动适配系统栏
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
// 获取系统栏边距
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
// 设置视图内边距以适配系统栏
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
}

@ -25,10 +25,52 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
/**
*
* <p>
* 使
* AndroidContactsContract Provider
* </p>
* <p>
*
* <ul>
* <li></li>
* <li>使HashMap</li>
* <li></li>
* </ul>
* </p>
* <p>
* 使
* 使
* </p>
*
* @see ContactsContract
* @see PhoneNumberUtils
*/
public class Contact { public class Contact {
/**
*
* <p>
* 使HashMap
*
* </p>
* Key:
* Value:
*/
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
* <p>
* 使PHONE_NUMBERS_EQUAL
* Phone.CONTENT_ITEM_TYPE
* 使min_match='+'
* </p>
*/
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,15 +78,30 @@ public class Contact {
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/**
*
* <p>
*
*
*
* </p>
*
* @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);
} }
// 构建查询条件使用toCallerIDMinMatch进行号码最小匹配
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(
@ -54,6 +111,7 @@ 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);

@ -17,33 +17,103 @@
package net.micode.notes.data; package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
/**
*
* <p>
* 使
* <ul>
* <li>Content ProviderAuthorityURI</li>
* <li></li>
* <li>ID</li>
* <li>Intent Extra</li>
* <li>Widget</li>
* <li>NoteColumnsDataColumns</li>
* <li></li>
* </ul>
* </p>
* <p>
* Content Provider
* 访便使
* </p>
*/
public class Notes { public class Notes {
/**
* Content ProviderAuthority
*/
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;
/** /**
* Following IDs are system folders' identifiers * ID
* {@link Notes#ID_ROOT_FOLDER } is default folder * {@link Notes#ID_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER }
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@link Notes#ID_CALL_RECORD_FOLDER}
*/ */
public static final int ID_ROOT_FOLDER = 0; public static final int ID_ROOT_FOLDER = 0;
/**
* ID
*/
public static final int ID_TEMPARAY_FOLDER = -1; public static final int ID_TEMPARAY_FOLDER = -1;
/**
* ID
*/
public static final int ID_CALL_RECORD_FOLDER = -2; public static final int ID_CALL_RECORD_FOLDER = -2;
/**
* ID
*/
public static final int ID_TRASH_FOLER = -3; public static final int ID_TRASH_FOLER = -3;
/**
* Intent Extra
*/
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 ExtraID
*/
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 ExtraWidget 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 ExtraWidget
*/
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 ExtraID
*/
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 Extra
*/
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";
/**
* Widget
*/
public static final int TYPE_WIDGET_INVALIDE = -1; public static final int TYPE_WIDGET_INVALIDE = -1;
/**
* 2x2 Widget
*/
public static final int TYPE_WIDGET_2X = 0; public static final int TYPE_WIDGET_2X = 0;
/**
* 4x4 Widget
*/
public static final int TYPE_WIDGET_4X = 1; public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants { public static class DataConstants {

@ -27,21 +27,114 @@ import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
*
* <p>
* SQLiteOpenHelperSQLite
* notedata
* 使
* </p>
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li>4</li>
* <li>访</li>
* </ul>
* </p>
* <p>
*
* <ul>
* <li>V1: </li>
* <li>V2: </li>
* <li>V3: GTASK_ID</li>
* <li>V4: VERSION</li>
* </ul>
* </p>
*
* @see SQLiteOpenHelper
* @see Notes
*/
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";
/**
*
* <p>
* 4
* onUpgrade
* </p>
*/
private static final int DB_VERSION = 4; private static final int DB_VERSION = 4;
/**
*
*/
public interface TABLE { public interface TABLE {
/**
*
* <p>
* IDID
* Widget
* IDIDGTASK ID
* </p>
*/
public static final String NOTE = "note"; public static final String NOTE = "note";
/**
*
* <p>
* MIME
* MIME5
* </p>
*/
public static final String DATA = "data"; public static final String DATA = "data";
} }
/**
*
*/
private static final String TAG = "NotesDatabaseHelper"; private static final String TAG = "NotesDatabaseHelper";
/**
*
* <p>
* 使
*
* </p>
*/
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
/**
* SQL
* <p>
* note
* <ul>
* <li>ID: </li>
* <li>PARENT_ID: ID0</li>
* <li>ALERTED_DATE: 0</li>
* <li>BG_COLOR_ID: ID0</li>
* <li>CREATED_DATE: </li>
* <li>HAS_ATTACHMENT: 0</li>
* <li>MODIFIED_DATE: </li>
* <li>NOTES_COUNT: 0</li>
* <li>SNIPPET: </li>
* <li>TYPE: 0=1=2=0</li>
* <li>WIDGET_ID: Widget ID0</li>
* <li>WIDGET_TYPE: Widget-1</li>
* <li>SYNC_ID: ID0</li>
* <li>LOCAL_MODIFIED: 0</li>
* <li>ORIGIN_PARENT_ID: ID0</li>
* <li>GTASK_ID: Google Tasks ID</li>
* <li>VERSION: 0</li>
* </ul>
* </p>
*/
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 +156,21 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")"; ")";
/**
* SQL
* <p>
* data
* <ul>
* <li>ID: </li>
* <li>MIME_TYPE: MIME</li>
* <li>NOTE_ID: ID0</li>
* <li>CREATED_DATE: </li>
* <li>MODIFIED_DATE: </li>
* <li>CONTENT: </li>
* <li>DATA1-5: </li>
* </ul>
* </p>
*/
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,6 +186,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")"; ")";
/**
* SQL
* <p>
* dataNOTE_IDID
* </p>
*/
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 + ");";
@ -206,10 +320,23 @@ 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);
} }
/**
*
* <p>
* noteSQL
* </p>
*
* @param db SQLiteDatabase
*/
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
@ -217,7 +344,17 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created");
} }
/**
*
* <p>
* note
*
* </p>
*
* @param db SQLiteDatabase
*/
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 +363,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 +373,27 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
} }
/**
*
* <p>
* note
* <ul>
* <li>ID_CALL_RECORD_FOLDER</li>
* <li>ID_ROOT_FOLDER</li>
* <li>ID_TEMPARAY_FOLDER</li>
* <li>ID_TRASH_FOLER</li>
* </ul>
* </p>
*
* @param db SQLiteDatabase
*/
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 +401,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 +410,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,12 +419,21 @@ 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);
} }
/**
*
* <p>
* dataSQL
* </p>
*
* @param db SQLiteDatabase
*/
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
@ -277,16 +441,36 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created");
} }
/**
*
* <p>
* data
*
* </p>
*
* @param db SQLiteDatabase
*/
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);
} }
/**
*
* <p>
* 使线
* </p>
*
* @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,45 +478,78 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance; return mInstance;
} }
/**
*
* <p>
* notedata
* </p>
*
* @param db SQLiteDatabase
*/
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db);
createDataTable(db); createDataTable(db);
} }
/**
*
* <p>
*
*
* </p>
*
* @param db SQLiteDatabase
* @param oldVersion
* @param newVersion
* @throws IllegalStateException
*/
@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;
// 从V1升级到V2包括V2到V3
if (oldVersion == 1) { if (oldVersion == 1) {
upgradeToV2(db); upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3 skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++; oldVersion++;
} }
// 从V2升级到V3
if (oldVersion == 2 && !skipV2) { if (oldVersion == 2 && !skipV2) {
upgradeToV3(db); upgradeToV3(db);
reCreateTriggers = true; reCreateTriggers = true;
oldVersion++; oldVersion++;
} }
// 从V3升级到V4
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");
} }
} }
/**
* V2
* <p>
* notedata
* </p>
*
* @param db SQLiteDatabase
*/
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);
@ -340,21 +557,40 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db); createDataTable(db);
} }
/**
* V3
* <p>
* GTASK_IDnote
* </p>
*
* @param db SQLiteDatabase
*/
private void upgradeToV3(SQLiteDatabase db) { private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers // 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 // add a column for gtask id
// 添加GTASK_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 // 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);
} }
/**
* V4
* <p>
* VERSIONnote
* </p>
*
* @param db SQLiteDatabase
*/
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");

@ -35,21 +35,97 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* Content Provider
* <p>
* ContentProviderCRUD
* notedata访URI
*
* </p>
* <p>
*
* <ul>
* <li>URIURI</li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* <p>
* URI
* <ul>
* <li>content://micode_notes/note - 查询所有笔记</li>
* <li>content://micode_notes/note/# - 查询指定ID的笔记</li>
* <li>content://micode_notes/data - 查询所有数据</li>
* <li>content://micode_notes/data/# - 查询指定ID的数据</li>
* <li>content://micode_notes/search - 搜索笔记</li>
* <li>content://micode_notes/search_suggest_query - 搜索建议</li>
* </ul>
* </p>
*
* @see ContentProvider
* @see NotesDatabaseHelper
* @see Notes
*/
public class NotesProvider extends ContentProvider { public class NotesProvider extends ContentProvider {
/**
* URI
* <p>
* URI
* URI
* </p>
*/
private static final UriMatcher mMatcher; private static final UriMatcher mMatcher;
/**
*
* <p>
* SQLiteDatabase
* </p>
*/
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
* <p>
* UriMatcherURI
* </p>
*/
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE); mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
@ -62,8 +138,15 @@ public class NotesProvider extends ContentProvider {
} }
/** /**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, *
* we will trim '\n' and white space in order to show more information. * <p>
* IDIntent
* 使TRIMREPLACE便
* </p>
* <p>
* x'0A'SQLite'\n'
*
* </p>
*/ */
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,18 +156,49 @@ 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
* <p>
* noteSNIPPET
* PARENT_IDID_TRASH_FOLER
* TYPETYPE_NOTE
* </p>
*/
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;
/**
* Content Provider
* <p>
*
* </p>
*
* @return true
*/
@Override @Override
public boolean onCreate() { public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
/**
*
* <p>
* URI
* 使LIKE
* </p>
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor
* @throws IllegalArgumentException URI
*/
@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) {
@ -93,25 +207,30 @@ public class NotesProvider extends ContentProvider {
String id = null; String id = null;
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的笔记
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的数据
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");
@ -119,18 +238,22 @@ public class NotesProvider extends ContentProvider {
String searchString = null; String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) { if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
// 从URI路径中获取搜索关键词
if (uri.getPathSegments().size() > 1) { if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1); searchString = uri.getPathSegments().get(1);
} }
} else { } else {
// 从查询参数中获取搜索关键词
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 });
@ -141,21 +264,36 @@ 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;
} }
/**
*
* <p>
* URI
* URI
* </p>
*
* @param uri URI
* @param values
* @return URIID
* @throws IllegalArgumentException 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;
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 {
@ -167,12 +305,14 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note 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 // 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,6 +321,20 @@ public class NotesProvider extends ContentProvider {
return ContentUris.withAppendedId(uri, insertedId); return ContentUris.withAppendedId(uri, insertedId);
} }
/**
*
* <p>
* URI
* ID0
* URI
* </p>
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
* @throws IllegalArgumentException URI
*/
@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;
@ -189,14 +343,17 @@ public class NotesProvider extends ContentProvider {
boolean deleteData = false; boolean deleteData = false;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE: case URI_NOTE:
// 删除笔记(排除系统文件夹)
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 "; selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs); count = db.delete(TABLE.NOTE, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
// 删除指定ID的笔记
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
/** /**
* ID that smaller than 0 is system folder which is not allowed to * ID that smaller than 0 is system folder which is not allowed to
* trash * trash
* ID0
*/ */
long noteId = Long.valueOf(id); long noteId = Long.valueOf(id);
if (noteId <= 0) { if (noteId <= 0) {
@ -206,10 +363,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的数据
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,8 +377,10 @@ 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) {
// 删除数据时通知笔记URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
@ -227,6 +388,21 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
/**
*
* <p>
* URI
*
* URI
* </p>
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
* @throws IllegalArgumentException URI
*/
@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;
@ -235,20 +411,24 @@ public class NotesProvider extends ContentProvider {
boolean updateData = false; boolean updateData = false;
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的笔记递增版本号
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的数据
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,8 +438,10 @@ 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) {
// 更新数据时通知笔记URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
@ -267,10 +449,30 @@ public class NotesProvider extends ContentProvider {
return count; return count;
} }
/**
*
* <p>
* IDSQL WHERE
* </p>
*
* @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 + ')' : "");
} }
/**
*
* <p>
* VERSION使1
*
* </p>
*
* @param id ID0使selection
* @param selection
* @param selectionArgs
*/
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
@ -279,6 +481,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,6 +490,7 @@ 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);
} }
@ -296,10 +500,18 @@ public class NotesProvider extends ContentProvider {
mHelper.getWritableDatabase().execSQL(sql.toString()); mHelper.getWritableDatabase().execSQL(sql.toString());
} }
/**
* MIME
* <p>
* URIMIME
* </p>
*
* @param uri URI
* @return MIME
*/
@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;
} }
} }

@ -25,36 +25,86 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Google Tasks
* <p>
* Task Google Tasks
* Google Tasks
* JSON
* </p>
*/
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 Tasks ID
*/
private String mRelatedGid = null; private String mRelatedGid = null;
/**
*
* <p>
* Google Tasks ID JSON
* JSON notes
* </p>
*
* @param gid Google Tasks ID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
// 将关联的 GID 添加到元信息中
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");
} }
// 将元信息转换为字符串并设置为任务备注
setNotes(metaInfo.toString()); setNotes(metaInfo.toString());
// 设置为元数据专用名称
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
/**
* Google Tasks ID
*
* @return Google Tasks ID null
*/
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
/**
*
* <p>
* notes notes
* </p>
*
* @return notes null true false
*/
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }
/**
* JSON
* <p>
* JSON Google Tasks ID
* </p>
*
* @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 {
// 从 notes 字段中解析元信息 JSON
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());
// 提取关联的 GID
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 +113,45 @@ public class MetaData extends Task {
} }
} }
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
* @throws IllegalAccessError
*/
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called // 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
* <p>
* JSON
* </p>
*
* @return
* @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");
} }
/**
*
* <p>
*
* </p>
*
* @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");

@ -20,33 +20,86 @@ import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Google Tasks
* <p>
* TaskTaskListMetaData
* Google ID
* JSON
* </p>
*/
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 Tasks ID
*/
private String mGid; private String mGid;
/**
*
*/
private String mName; private String mName;
/**
*
*/
private long mLastModified; private long mLastModified;
/**
* true
*/
private boolean mDeleted; private boolean mDeleted;
/**
*
* <p>
* GID null 0 false
* </p>
*/
public Node() { public Node() {
mGid = null; mGid = null;
mName = ""; mName = "";
@ -54,46 +107,137 @@ public abstract class Node {
mDeleted = false; mDeleted = false;
} }
/**
* JSON
* <p>
* ID JSON
* </p>
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
* <p>
* ID JSON
* </p>
*
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
* <p>
* JSON
* </p>
*
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent();
/**
*
* <p>
*
* </p>
*
* @param c
* @return SYNC_ACTION_*
*/
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
/**
* Google Tasks ID
*
* @param gid Google Tasks 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 true
*/
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted;
} }
/**
* Google Tasks ID
*
* @return Google Tasks ID null
*/
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 true
*/
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }

@ -35,24 +35,39 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* SQLite
* <p>
*
* MIME
* JSON JSON Google Tasks
* </p>
*/
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;
/** 扩展数据 1 字段在投影数组中的索引 */
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
/** 扩展数据 3 字段在投影数组中的索引 */
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;
@ -71,6 +86,15 @@ public class SqlData {
private ContentValues mDiffDataValues; private ContentValues mDiffDataValues;
/**
*
* <p>
*
* commit
* </p>
*
* @param context ContentResolver
*/
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
@ -82,6 +106,16 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
*
* <p>
*
* commit
* </p>
*
* @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 +123,14 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
*
* <p>
*
* </p>
*
* @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,6 +139,16 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
} }
/**
* JSON
* <p>
* JSON
*
* </p>
*
* @param js JSON
* @throws JSONException JSON
*/
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
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) {
@ -130,6 +182,15 @@ public class SqlData {
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3;
} }
/**
* JSON
* <p>
* JSON
* </p>
*
* @return JSON null
* @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,6 +205,19 @@ public class SqlData {
return js; return js;
} }
/**
*
* <p>
*
* - ID
* -
* </p>
*
* @param noteId ID
* @param validateVersion true
* @param version
* @throws ActionFailureException
*/
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { if (mIsCreate) {
@ -166,6 +240,7 @@ public class SqlData {
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
@ -183,6 +258,11 @@ public class SqlData {
mIsCreate = false; mIsCreate = false;
} }
/**
* ID
*
* @return ID
*/
public long getId() { public long getId() {
return mDataId; return mDataId;
} }

@ -38,11 +38,21 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/**
* SQLite
* <p>
*
* Google Tasks JSON JSON
*
* </p>
*/
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,38 +62,55 @@ 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;
/** Widget ID 字段在投影数组中的索引 */
public static final int WIDGET_ID_COLUMN = 10; public static final int WIDGET_ID_COLUMN = 10;
/** Widget 类型字段在投影数组中的索引 */
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 Tasks 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;
@ -122,6 +149,15 @@ public class SqlNote {
private ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
/**
*
* <p>
*
* commit
* </p>
*
* @param context ContentResolver
*/
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -143,6 +179,16 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
} }
/**
*
* <p>
*
* commit
* </p>
*
* @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 +200,16 @@ public class SqlNote {
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
/**
* ID
* <p>
* ID
* commit
* </p>
*
* @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();
@ -166,6 +222,14 @@ public class SqlNote {
} }
/**
* ID
* <p>
* ID loadFromCursor(Cursor)
* </p>
*
* @param id ID
*/
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;
try { try {
@ -185,6 +249,14 @@ public class SqlNote {
} }
} }
/**
*
* <p>
*
* </p>
*
* @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,6 +272,13 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
/**
*
* <p>
* Data SqlData
*
* </p>
*/
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
@ -226,6 +305,17 @@ public class SqlNote {
} }
} }
/**
* JSON
* <p>
* JSON
*
*
* </p>
*
* @param js JSON
* @return true false
*/
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);
@ -359,6 +449,15 @@ public class SqlNote {
return true; return true;
} }
/**
* JSON
* <p>
* JSON
* JSON
* </p>
*
* @return JSON null
*/
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -407,39 +506,102 @@ public class SqlNote {
return null; return null;
} }
/**
* ID
* <p>
* ID
* </p>
*
* @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 Tasks ID
* <p>
* Google Tasks ID
* </p>
*
* @param gid Google Tasks ID
*/
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
/**
* ID
* <p>
*
* </p>
*
* @param syncId
*/
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
/**
*
* <p>
* 0
* </p>
*/
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
/**
* ID
*
* @return ID INVALID_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 true false
*/
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
/**
*
* <p>
*
* - ID
* -
* -
* </p>
*
* @param validateVersion true
* @throws ActionFailureException
* @throws IllegalStateException ID
*/
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)) {
@ -476,6 +638,7 @@ public class SqlNote {
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[] {
@ -494,7 +657,7 @@ public class SqlNote {
} }
} }
// refresh local info // 从数据库重新加载最新数据,确保内存状态与数据库一致
loadFromCursor(mId); loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();

@ -32,19 +32,51 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Google Tasks
* <p>
* Node Google Tasks
*
* JSON
* </p>
*/
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();
/**
* true
*/
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;
/**
*
* <p>
* null
* </p>
*/
public Task() { public Task() {
super(); super();
mCompleted = false; mCompleted = false;
@ -54,6 +86,16 @@ public class Task extends Node {
mMetaInfo = null; mMetaInfo = null;
} }
/**
* JSON
* <p>
* JSON ID
* </p>
*
* @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 +145,16 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
* <p>
* JSON
* </p>
*
* @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 +187,15 @@ public class Task extends Node {
return js; return js;
} }
/**
* JSON
* <p>
* JSON ID
* </p>
*
* @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 +236,15 @@ public class Task extends Node {
} }
} }
/**
* JSON
* <p>
* JSON
*
* </p>
*
* @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)) {
@ -190,6 +260,7 @@ public class Task extends Node {
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,6 +275,15 @@ public class Task extends Node {
} }
} }
/**
* JSON
* <p>
* JSON
* JSON
* </p>
*
* @return JSON null
*/
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
String name = getName(); String name = getName();
try { try {
@ -229,6 +309,7 @@ public class Task extends Node {
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 +328,15 @@ public class Task extends Node {
} }
} }
/**
*
* <p>
* JSON
*
* </p>
*
* @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,6 +348,16 @@ public class Task extends Node {
} }
} }
/**
*
* <p>
*
*
* </p>
*
* @param c
* @return SYNC_ACTION_*
*/
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
JSONObject noteInfo = null; JSONObject noteInfo = null;
@ -311,39 +411,87 @@ public class Task extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
/**
*
* <p>
*
* </p>
*
* @return true false
*/
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 true
*/
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 true
*/
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;
} }

@ -30,19 +30,52 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
/**
* Google Tasks
* <p>
* Node Google Tasks
*
* JSON
* </p>
*/
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;
/**
*
* <p>
* 1
* </p>
*/
public TaskList() { public TaskList() {
super(); super();
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>();
mIndex = 1; mIndex = 1;
} }
/**
* JSON
* <p>
* JSON
* </p>
*
* @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();
@ -74,6 +107,16 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
* <p>
* JSON
* </p>
*
* @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();
@ -103,6 +146,15 @@ public class TaskList extends Node {
return js; return js;
} }
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
@ -129,6 +181,15 @@ public class TaskList extends Node {
} }
} }
/**
* JSON
* <p>
* JSON
*
* </p>
*
* @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");
@ -138,9 +199,11 @@ public class TaskList extends Node {
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);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { } else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 系统文件夹,根据 ID 设置对应的名称
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER) if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER) else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
@ -157,16 +220,27 @@ public class TaskList extends Node {
} }
} }
/**
* JSON
* <p>
* JSON
*
* </p>
*
* @return JSON null
*/
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(),
folderName.length()); folderName.length());
folder.put(NoteColumns.SNIPPET, folderName); folder.put(NoteColumns.SNIPPET, folderName);
// 根据文件夹名称判断类型
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT) if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE)) || folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -183,6 +257,16 @@ public class TaskList extends Node {
} }
} }
/**
*
* <p>
*
*
* </p>
*
* @param c
* @return SYNC_ACTION_*
*/
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) {
@ -216,10 +300,24 @@ 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();
} }
/**
*
* <p>
*
* </p>
*
* @param task
* @return true false
*/
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)) {
@ -234,6 +332,16 @@ public class TaskList extends Node {
return ret; return ret;
} }
/**
*
* <p>
*
* </p>
*
* @param task
* @param index 0
* @return true false
*/
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");
@ -260,6 +368,16 @@ public class TaskList extends Node {
return true; return true;
} }
/**
*
* <p>
*
*
* </p>
*
* @param task
* @return true false
*/
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);
@ -281,6 +399,16 @@ public class TaskList extends Node {
return ret; return ret;
} }
/**
*
* <p>
*
* </p>
*
* @param task
* @param index 0 1
* @return true false
*/
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 +427,12 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
} }
/**
* GID
*
* @param gid Google Tasks ID
* @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 +443,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 0 1
* @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 +467,12 @@ public class TaskList extends Node {
return mChildren.get(index); return mChildren.get(index);
} }
/**
* GID
*
* @param gid Google Tasks ID
* @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 +481,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;
} }

@ -16,17 +16,39 @@
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
*
* <p>
* Google Tasks
*
* RuntimeException
* </p>
*/
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
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);
} }

@ -16,17 +16,39 @@
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
/**
*
* <p>
* Google Tasks
* 访 Google Tasks
* Exception
* </p>
*/
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
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);
} }

@ -29,88 +29,187 @@ import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/**
* Google Tasks
* <p>
* AsyncTask Google Tasks
*
* </p>
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
/** 同步通知的唯一标识符 */
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
/**
*
* <p>
*
* </p>
*/
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;
/**
*
* <p>
*
* </p>
*
* @param context
* @param listener
*/
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
// 获取系统通知服务
mNotifiManager = (NotificationManager) mContext mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE); .getSystemService(Context.NOTIFICATION_SERVICE);
// 获取 GTaskManager 单例
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
/**
*
* <p>
* GTaskManager cancelSync()
* </p>
*/
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
/**
*
* <p>
* AsyncTask publishProgress() UI 线
* </p>
*
* @param message
*/
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
} }
/**
*
* <p>
*
*
* </p>
*
* @param tickerId ID
* @param content
*/
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent; PendingIntent pendingIntent;
// 根据同步结果选择跳转目标
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
// 同步失败或取消,跳转到设置页面
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
} else { } else {
// 同步成功,跳转到笔记列表
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
} }
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, // 构建通知
pendingIntent); Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(content)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification=builder.getNotification();
// 显示通知
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
/**
*
* <p>
* 线 Google Tasks
* </p>
*
* @param unused 使
* @return GTaskManager.STATE_SUCCESSSTATE_NETWORK_ERRORSTATE_INTERNAL_ERRORSTATE_SYNC_IN_PROGRESS STATE_SYNC_CANCELLED
*/
@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
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
// 执行同步并返回结果
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
/**
*
* <p>
* UI 线广
* </p>
*
* @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]);
// 如果上下文是 GTaskSyncService发送广播
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
} }
} }
/**
*
* <p>
*
*
* </p>
*
* @param result
*/
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
// 根据同步结果显示相应通知
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
// 同步成功
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));
// 更新最后同步时间
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) { } else if (result == GTaskManager.STATE_NETWORK_ERROR) {
// 网络错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network)); showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) { } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
// 内部错误
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal)); showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) { } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
// 同步已取消
showNotification(R.string.ticker_cancel, mContext showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled)); .getString(R.string.error_sync_cancelled));
} }
// 调用完成监听器
if (mOnCompleteListener != null) { if (mOnCompleteListener != null) {
new Thread(new Runnable() { new Thread(new Runnable() {

@ -61,15 +61,27 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
/**
* Google Tasks
* <p>
* Google Tasks API Google Tasks
*
* 使 HTTP Google Tasks API Cookie
* </p>
*/
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;
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
@ -90,6 +102,12 @@ public class GTaskClient {
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
/**
*
* <p>
*
* </p>
*/
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -102,6 +120,14 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
/**
* GTaskClient
* <p>
* 使线
* </p>
*
* @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,6 +135,17 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
/**
* Google Tasks
* <p>
*
* Cookie 5
* Gmail/Googlemail
* </p>
*
* @param activity Activity
* @return true false
*/
public boolean login(Activity activity) { public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes // we suppose that the cookie would expire after 5 minutes
// then we need to re-login // then we need to re-login
@ -164,6 +201,26 @@ public class GTaskClient {
return true; return true;
} }
/**
*
*
* @return Google
*/
private Account getSyncAccount() {
return mAccount;
}
/**
* Google
* <p>
* Google
* invalidateToken true使
* </p>
*
* @param activity 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);
@ -207,6 +264,16 @@ public class GTaskClient {
return authToken; return authToken;
} }
/**
* Google Tasks
* <p>
* 使 Google Tasks使
* </p>
*
* @param activity Activity
* @param authToken
* @return true false
*/
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 // maybe the auth token is out of date, now let's invalidate the
@ -225,6 +292,15 @@ public class GTaskClient {
return true; return true;
} }
/**
* 使 Google Tasks
* <p>
* Google Tasks GET Cookie
* </p>
*
* @param authToken
* @return true false
*/
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
@ -280,10 +356,26 @@ public class GTaskClient {
return true; return true;
} }
/**
* ID
* <p>
* ID
* </p>
*
* @return ID
*/
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++;
} }
/**
* HTTP POST
* <p>
* application/x-www-form-urlencoded
* </p>
*
* @return HttpPost
*/
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,6 +383,16 @@ public class GTaskClient {
return httpPost; return httpPost;
} }
/**
* HTTP
* <p>
* HTTP gzip deflate
* </p>
*
* @param entity HTTP
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
@ -323,6 +425,17 @@ public class GTaskClient {
} }
} }
/**
* POST Google Tasks
* <p>
* JSON POST JSON
* </p>
*
* @param js JSON
* @return JSON
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -360,6 +473,16 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
* Google Tasks ID
* </p>
*
* @param task
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -386,6 +509,16 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
* Google Tasks ID
* </p>
*
* @param tasklist
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -412,6 +545,16 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
* Google Tasks
*
* </p>
*
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
@ -433,6 +576,15 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
* 10
* </p>
*
* @param node null
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // too many update items may result in an error
@ -447,6 +599,18 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
*
* </p>
*
* @param task
* @param preParent
* @param curParent
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
@ -486,6 +650,16 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
* Google Tasks
* </p>
*
* @param node
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -509,6 +683,16 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
* Google Tasks
* </p>
*
* @return JSON
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -547,6 +731,17 @@ public class GTaskClient {
} }
} }
/**
*
* <p>
* Google Tasks
* </p>
*
* @param listGid Google ID
* @return JSON
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -575,10 +770,21 @@ public class GTaskClient {
} }
} }
/**
*
*
* @return Google
*/
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount;
} }
/**
*
* <p>
*
* </p>
*/
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }

@ -48,17 +48,30 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
/**
* Google Tasks
* <p>
* Google Tasks
*
*
* </p>
*/
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;
@ -87,6 +100,12 @@ public class GTaskManager {
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
/**
*
* <p>
*
* </p>
*/
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false;
mCancelled = false; mCancelled = false;
@ -99,6 +118,14 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>();
} }
/**
* GTaskManager
* <p>
* 使线
* </p>
*
* @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,11 +133,30 @@ public class GTaskManager {
return mInstance; return mInstance;
} }
/**
* Activity
* <p>
* Google
* </p>
*
* @param activity 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;
} }
/**
*
* <p>
* Google Tasks
* Google Tasks
* </p>
*
* @param context
* @param asyncTask
* @return STATE_SUCCESSSTATE_NETWORK_ERRORSTATE_INTERNAL_ERRORSTATE_SYNC_IN_PROGRESS STATE_SYNC_CANCELLED
*/
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");
@ -790,10 +836,21 @@ public class GTaskManager {
} }
} }
/**
*
*
* @return Google
*/
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return mActivity == null ? null : GTaskClient.getInstance().getSyncAccount().name;
} }
/**
*
* <p>
*
* </p>
*/
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} }

@ -23,54 +23,110 @@ import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
/**
* Google Tasks
* <p>
* Google Tasks
* 广
* </p>
*/
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";
/** 启动同步操作的 Action 值 */
public final static int ACTION_START_SYNC = 0; public final static int ACTION_START_SYNC = 0;
/** 取消同步操作的 Action 值 */
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_CANCEL_SYNC = 1;
/** 无效的 Action 值 */
public final static int ACTION_INVALID = 2; public final static int ACTION_INVALID = 2;
/** 同步服务广播名称 */
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 = "";
/**
*
* <p>
* GTaskASyncTask
* 广
* </p>
*/
private void startSync() { private void startSync() {
// 检查是否已有同步任务在运行
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() { public void onComplete() {
// 清空同步任务引用
mSyncTask = null; mSyncTask = null;
// 发送同步完成广播
sendBroadcast(""); sendBroadcast("");
// 停止服务
stopSelf(); stopSelf();
} }
}); });
// 发送同步开始广播
sendBroadcast(""); sendBroadcast("");
// 执行异步同步任务
mSyncTask.execute(); mSyncTask.execute();
} }
} }
/**
*
* <p>
* cancelSync()
* </p>
*/
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) {
// 取消异步同步任务
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
/**
*
* <p>
* null
* </p>
*/
@Override @Override
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
/**
*
* <p>
* Intent Action
* ACTION_START_SYNC ACTION_CANCEL_SYNC
* </p>
*
* @param intent Intent Action
* @param flags
* @param startId ID
* @return START_STICKY
*/
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
// 检查 Intent 是否包含 Action 参数
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) { if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
// 根据 Action 类型执行相应操作
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) { switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC: case ACTION_START_SYNC:
startSync(); startSync();
@ -86,42 +142,99 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
/**
*
* <p>
*
* </p>
*/
@Override @Override
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) {
// 取消同步任务以释放内存
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
/**
*
* <p>
* null
* </p>
*
* @param intent Intent
* @return null
*/
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
/**
* 广
* <p>
* 广
* </p>
*
* @param msg
*/
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
// 更新同步进度消息
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
// 添加是否正在同步的标志
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
// 添加进度消息
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
// 发送广播
sendBroadcast(intent); sendBroadcast(intent);
} }
/**
*
* <p>
* Activity GTaskManager
* </p>
*
* @param activity Activity Google
*/
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
// 设置 Activity 上下文用于账户认证
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
// 启动同步服务
activity.startService(intent); activity.startService(intent);
} }
/**
*
* <p>
*
* </p>
*
* @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 true false
*/
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
/**
*
*
* @return
*/
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }

@ -34,15 +34,36 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList; import java.util.ArrayList;
/**
*
* <p>
*
*
* </p>
*/
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
* <p>
* ID
* ID
* </p>
*
* @param context
* @param folderId ID
* @return ID 0
*/ */
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);
@ -54,6 +75,7 @@ public class Note {
long noteId = 0; long noteId = 0;
try { try {
// 从 URI 中提取笔记 ID
noteId = Long.valueOf(uri.getPathSegments().get(1)); noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
@ -65,41 +87,114 @@ public class Note {
return noteId; return noteId;
} }
/**
*
* <p>
*
* </p>
*/
public Note() { public Note() {
mNoteDiffValues = new ContentValues(); mNoteDiffValues = new ContentValues();
mNoteData = new NoteData(); mNoteData = new NoteData();
} }
/**
*
* <p>
*
* </p>
*
* @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());
} }
/**
*
* <p>
*
* </p>
*
* @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
* <p>
* ID
* </p>
*
* @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
* <p>
* ID
* </p>
*
* @param id ID
*/
public void setCallDataId(long id) { public void setCallDataId(long id) {
mNoteData.setCallDataId(id); mNoteData.setCallDataId(id);
} }
/**
*
* <p>
*
* </p>
*
* @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);
} }
/**
*
* <p>
*
* </p>
*
* @return true false
*/
public boolean isLocalModified() { public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
} }
/**
*
* <p>
*
*
* </p>
*
* @param context
* @param noteId ID
* @return true false
*/
public boolean syncNote(Context context, long noteId) { public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -110,15 +205,14 @@ public class Note {
} }
/** /**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and * {@link NoteColumns#LOCAL_MODIFIED}
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the * {@link NoteColumns#MODIFIED_DATE}使
* 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) {
Log.e(TAG, "Update note error, should not happen"); Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through // 不返回,继续执行
} }
mNoteDiffValues.clear(); mNoteDiffValues.clear();
@ -130,17 +224,35 @@ public class Note {
return true; return true;
} }
/**
*
* <p>
*
*
* </p>
*/
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";
/**
*
* <p>
* ContentValues
* </p>
*/
public NoteData() { public NoteData() {
mTextDataValues = new ContentValues(); mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues(); mCallDataValues = new ContentValues();
@ -148,10 +260,26 @@ public class Note {
mCallDataId = 0; mCallDataId = 0;
} }
/**
*
* <p>
*
* </p>
*
* @return true false
*/
boolean isLocalModified() { boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
} }
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID 0
*/
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 +287,14 @@ public class Note {
mTextDataId = id; mTextDataId = id;
} }
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID 0
*/
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,21 +302,50 @@ public class Note {
mCallDataId = id; mCallDataId = id;
} }
/**
*
* <p>
*
* </p>
*
* @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());
} }
/**
*
* <p>
*
* </p>
*
* @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
* <p>
*
*
* </p>
*
* @param context
* @param noteId ID
* @return URI null
*/
Uri pushIntoContentResolver(Context context, long noteId) { Uri pushIntoContentResolver(Context context, long noteId) {
/** /**
* Check for safety *
*/ */
if (noteId <= 0) { if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -189,9 +354,11 @@ public class Note {
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 +370,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 +379,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 +395,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 +404,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(

@ -32,36 +32,57 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources; import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
*
* <p>
*
*
* </p>
*/
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;
/** Widget ID */
private int mWidgetId; private int mWidgetId;
/** Widget 类型 */
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 +93,7 @@ public class WorkingNote {
DataColumns.DATA4, DataColumns.DATA4,
}; };
/** 数据查询投影 - 笔记元数据 */
public static final String[] NOTE_PROJECTION = new String[] { public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE, NoteColumns.ALERTED_DATE,
@ -81,26 +103,45 @@ 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;
/** 笔记 Widget ID 列索引 */
private static final int NOTE_WIDGET_ID_COLUMN = 3; private static final int NOTE_WIDGET_ID_COLUMN = 3;
/** 笔记 Widget 类型列索引 */
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;
/**
*
* <p>
*
* </p>
*
* @param context
* @param folderId ID
*/
// New note construct // New note construct
private WorkingNote(Context context, long folderId) { private WorkingNote(Context context, long folderId) {
mContext = context; mContext = context;
@ -114,6 +155,16 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
} }
/**
*
* <p>
*
* </p>
*
* @param context
* @param noteId ID
* @param folderId ID
*/
// Existing note construct // Existing note construct
private WorkingNote(Context context, long noteId, long folderId) { private WorkingNote(Context context, long noteId, long folderId) {
mContext = context; mContext = context;
@ -125,6 +176,12 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
* Widget
* </p>
=======
* *
* *
* ID * ID
@ -132,6 +189,7 @@ public class WorkingNote {
* *
* *
* @throws IllegalArgumentException ID * @throws IllegalArgumentException ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
private void loadNote() { private void loadNote() {
// 构建查询URI通过笔记ID定位特定的笔记记录 // 构建查询URI通过笔记ID定位特定的笔记记录
@ -163,8 +221,15 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
*
* </p>
=======
* loadNote()loadNoteData() * loadNote()loadNoteData()
* ID * ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
private void loadNoteData() { private void loadNoteData() {
// 通过ContentResolver查询数据库获取指定笔记ID的数据 // 通过ContentResolver查询数据库获取指定笔记ID的数据
@ -188,16 +253,25 @@ public class WorkingNote {
// 如果是普通文本笔记类型 // 如果是普通文本笔记类型
if (DataConstants.NOTE.equals(type)) { if (DataConstants.NOTE.equals(type)) {
<<<<<<< HEAD
// 加载文本笔记数据
=======
// 获取笔记的文本内容 // 获取笔记的文本内容
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
mContent = cursor.getString(DATA_CONTENT_COLUMN); mContent = cursor.getString(DATA_CONTENT_COLUMN);
// 获取笔记的显示模式(普通模式或清单模式) // 获取笔记的显示模式(普通模式或清单模式)
mMode = cursor.getInt(DATA_MODE_COLUMN); mMode = cursor.getInt(DATA_MODE_COLUMN);
// 设置文本数据的ID用于后续更新操作 // 设置文本数据的ID用于后续更新操作
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
<<<<<<< HEAD
} else if (DataConstants.CALL_NOTE.equals(type)) {
// 加载通话记录数据
=======
} }
// 如果是通话记录笔记类型 // 如果是通话记录笔记类型
else if (DataConstants.CALL_NOTE.equals(type)) { else if (DataConstants.CALL_NOTE.equals(type)) {
// 设置通话记录数据的ID // 设置通话记录数据的ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} }
// 如果是未知类型,记录调试信息 // 如果是未知类型,记录调试信息
@ -217,6 +291,19 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
*
* </p>
*
* @param context
* @param folderId ID
* @param widgetId Widget ID
* @param widgetType Widget
* @param defaultBgColorId ID
* @return WorkingNote
=======
* *
* *
* *
@ -228,6 +315,7 @@ public class WorkingNote {
* @param widgetType * @param widgetType
* @param defaultBgColorId ID * @param defaultBgColorId ID
* @return WorkingNote * @return WorkingNote
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
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) {
@ -244,6 +332,16 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
* ID
* </p>
*
* @param context
* @param id ID
* @return WorkingNote
=======
* ID * ID
* *
* *
@ -254,6 +352,7 @@ public class WorkingNote {
* @param id IDID * @param id IDID
* @return WorkingNote * @return WorkingNote
* @throws IllegalArgumentException ID * @throws IllegalArgumentException ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public static WorkingNote load(Context context, long id) { public static WorkingNote load(Context context, long id) {
// 创建一个新的WorkingNote实例传入笔记ID和文件夹ID(0表示不指定) // 创建一个新的WorkingNote实例传入笔记ID和文件夹ID(0表示不指定)
@ -262,32 +361,56 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
*
*
* Widget Widget
* </p>
*
* @return true false
=======
* *
* *
* ID * ID
* 使synchronized线 * 使synchronized线
* *
* @return truefalse * @return truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public synchronized boolean saveNote() { public synchronized boolean saveNote() {
// 检查笔记是否值得保存(非空内容或已修改) // 检查笔记是否值得保存(非空内容或已修改)
if (isWorthSaving()) { if (isWorthSaving()) {
// 如果笔记在数据库中不存在新笔记则需要先获取一个新的笔记ID // 如果笔记在数据库中不存在新笔记则需要先获取一个新的笔记ID
if (!existInDatabase()) { if (!existInDatabase()) {
<<<<<<< HEAD
// 创建新笔记
=======
// 调用Note.getNewNoteId()方法获取一个新的笔记ID // 调用Note.getNewNoteId()方法获取一个新的笔记ID
// 如果获取失败返回0记录错误日志并返回false // 如果获取失败返回0记录错误日志并返回false
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
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);
return false; return false;
} }
} }
<<<<<<< HEAD
// 同步笔记数据
mNote.syncNote(mContext, mNoteId);
/**
* Widget Widget
*/
=======
// 将笔记数据同步到数据库 // 将笔记数据同步到数据库
// 这会更新笔记的基本信息和内容数据 // 这会更新笔记的基本信息和内容数据
mNote.syncNote(mContext, mNoteId); mNote.syncNote(mContext, mNoteId);
// 如果笔记关联了桌面小部件,则更新小部件显示内容 // 如果笔记关联了桌面小部件,则更新小部件显示内容
// 检查条件小部件ID有效、小部件类型有效、状态监听器不为空 // 检查条件小部件ID有效、小部件类型有效、状态监听器不为空
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
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) {
@ -303,9 +426,15 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
*
* @return ID 0 true false
=======
* *
* *
* @return truefalse * @return truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public boolean existInDatabase() { public boolean existInDatabase() {
// 通过检查笔记ID是否大于0来判断笔记是否已保存到数据库 // 通过检查笔记ID是否大于0来判断笔记是否已保存到数据库
@ -314,9 +443,18 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
*
* </p>
*
* @return true false
=======
* *
* *
* @return truefalse * @return truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
private boolean isWorthSaving() { private boolean isWorthSaving() {
// 检查笔记是否已被删除、是否为空内容(新笔记)、是否已修改(已存在笔记) // 检查笔记是否已被删除、是否为空内容(新笔记)、是否已修改(已存在笔记)
@ -329,6 +467,11 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
*
* @param l
=======
* *
* *
* *
@ -340,6 +483,7 @@ public class WorkingNote {
* *
* @param l NoteSettingChangedListener * @param l NoteSettingChangedListener
* null * null
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
// 将传入的监听器对象保存到成员变量中 // 将传入的监听器对象保存到成员变量中
@ -348,6 +492,15 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
*
* </p>
*
* @param date
* @param set
=======
* *
* *
* *
@ -356,6 +509,7 @@ public class WorkingNote {
* *
* @param date 0 * @param date 0
* @param set truefalse * @param set truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public void setAlertDate(long date, boolean set) { public void setAlertDate(long date, boolean set) {
// 检查新的提醒日期是否与当前日期不同 // 检查新的提醒日期是否与当前日期不同
@ -376,6 +530,14 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
* Widget
* </p>
*
* @param mark
=======
* *
* *
* *
@ -386,6 +548,7 @@ public class WorkingNote {
* *
* *
* @param mark truefalse * @param mark truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public void markDeleted(boolean mark) { public void markDeleted(boolean mark) {
// 设置笔记的删除标记状态 // 设置笔记的删除标记状态
@ -403,6 +566,14 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
* ID
* <p>
*
* </p>
*
* @param id ID
=======
* ID * ID
* *
* setAlertDate * setAlertDate
@ -414,6 +585,7 @@ public class WorkingNote {
* *
* *
* @param id ID * @param id ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public void setBgColorId(int id) { public void setBgColorId(int id) {
// 检查新的背景颜色ID是否与当前ID不同 // 检查新的背景颜色ID是否与当前ID不同
@ -434,6 +606,14 @@ public class WorkingNote {
} }
/** /**
<<<<<<< HEAD
*
* <p>
*
* </p>
*
* @param mode
=======
* *
* *
* *
@ -445,6 +625,7 @@ public class WorkingNote {
* *
* *
* @param mode * @param mode
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
public void setCheckListMode(int mode) { public void setCheckListMode(int mode) {
// 检查新的模式是否与当前模式不同 // 检查新的模式是否与当前模式不同
@ -464,6 +645,11 @@ public class WorkingNote {
} }
} }
/**
* Widget
*
* @param type Widget
*/
public void setWidgetType(int type) { public void setWidgetType(int type) {
if (type != mWidgetType) { if (type != mWidgetType) {
mWidgetType = type; mWidgetType = type;
@ -471,6 +657,11 @@ public class WorkingNote {
} }
} }
/**
* Widget ID
*
* @param id Widget ID
*/
public void setWidgetId(int id) { public void setWidgetId(int id) {
if (id != mWidgetId) { if (id != mWidgetId) {
mWidgetId = id; mWidgetId = id;
@ -478,6 +669,14 @@ public class WorkingNote {
} }
} }
/**
*
* <p>
*
* </p>
*
* @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;
@ -485,61 +684,140 @@ public class WorkingNote {
} }
} }
/**
*
* <p>
*
* </p>
*
* @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 true false
*/
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;
} }
/**
* Widget ID
*
* @return Widget ID
*/
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
/**
* Widget
*
* @return Widget
*/
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
/** /**
<<<<<<< HEAD
*
* <p>
* UI
* </p>
*/
public interface NoteSettingChangedListener {
/**
*
=======
* *
* *
* UI * UI
@ -550,27 +828,45 @@ public class WorkingNote {
* *
* *
* UI * UI
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
void onBackgroundColorChanged(); void onBackgroundColorChanged();
/** /**
<<<<<<< HEAD
*
*
* @param date
* @param set
=======
* *
* *
* @param date 0 * @param date 0
* @param set truefalse * @param set truefalse
* *
* 使AlarmManagerPendingIntent * 使AlarmManagerPendingIntent
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
void onClockAlertChanged(long date, boolean set); void onClockAlertChanged(long date, boolean set);
/** /**
<<<<<<< HEAD
* Widget
=======
* *
* *
* 广 * 广
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
void onWidgetChanged(); void onWidgetChanged();
/** /**
<<<<<<< HEAD
*
*
* @param oldMode
* @param newMode
=======
* *
* *
* @param oldMode * @param oldMode
@ -578,6 +874,7 @@ public class WorkingNote {
* *
* UI * UI
* *
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/ */
void onCheckListModeChanged(int oldMode, int newMode); void onCheckListModeChanged(int oldMode, int newMode);
} }

@ -36,11 +36,27 @@ import java.io.IOException;
import java.io.PrintStream; import java.io.PrintStream;
/**
*
* <p>
*
* SD
* 使
* </p>
*/
public class BackupUtils { public class BackupUtils {
/** 日志标签 */
private static final String TAG = "BackupUtils"; private static final String TAG = "BackupUtils";
// Singleton stuff // Singleton stuff
/** 单例实例 */
private static BackupUtils sInstance; private static BackupUtils sInstance;
/**
*
*
* @param context
* @return
*/
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,84 @@ public class BackupUtils {
} }
/** /**
* Following states are signs to represents backup or restore *
* status * <p>
*
* </p>
*/ */
// Currently, the sdcard is not mounted // 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 // 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 // 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 // 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 // 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 true false
*/
private static boolean externalStorageAvailable() { private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
} }
/**
*
*
* @return STATE_SD_CARD_UNMOUONTEDSTATE_SYSTEM_ERROR STATE_SUCCESS
*/
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;
} }
/**
*
* <p>
*
*
* </p>
*/
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 +150,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,23 +169,39 @@ 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;
@ -132,12 +209,24 @@ public class BackupUtils {
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 *
* <p>
*
* </p>
*
* @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 // Query notes belong to this folder
@ -163,7 +252,13 @@ public class BackupUtils {
} }
/** /**
* Export note identified by id to a print stream *
* <p>
* MIME
* </p>
*
* @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,
@ -216,7 +311,13 @@ public class BackupUtils {
} }
/** /**
* Note will be exported as text which is user readable *
* <p>
*
*
* </p>
*
* @return STATE_SD_CARD_UNMOUONTEDSTATE_SYSTEM_ERROR STATE_SUCCESS
*/ */
public int exportToText() { public int exportToText() {
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
@ -283,7 +384,12 @@ public class BackupUtils {
} }
/** /**
* Get a print stream pointed to the file {@generateExportedTextFile} *
* <p>
* SD PrintStream
* </p>
*
* @return PrintStream 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 +416,15 @@ public class BackupUtils {
} }
/** /**
* Generate the text file to store imported data * SD
* <p>
*
* </p>
*
* @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();
@ -325,9 +439,11 @@ public class BackupUtils {
try { try {
if (!filedir.exists()) { if (!filedir.exists()) {
// 创建目录
filedir.mkdir(); filedir.mkdir();
} }
if (!file.exists()) { if (!file.exists()) {
// 创建文件
file.createNewFile(); file.createNewFile();
} }
return file; return file;

@ -35,8 +35,28 @@ import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
/**
*
* <p>
*
*
* </p>
*/
public class DataUtils { public class DataUtils {
/** 日志标签 */
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
/**
*
* <p>
* ID
*
* </p>
*
* @param resolver ContentResolver
* @param ids ID
* @return true false
*/
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");
@ -50,6 +70,7 @@ public class DataUtils {
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;
} }
@ -72,6 +93,17 @@ public class DataUtils {
return false; return false;
} }
/**
*
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @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);
@ -80,6 +112,17 @@ public class DataUtils {
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
} }
/**
*
* <p>
*
* </p>
*
* @param resolver ContentResolver
* @param ids ID
* @param folderId ID
* @return true false
*/
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) {
@ -112,7 +155,14 @@ public class DataUtils {
} }
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} *
* <p>
*
*
* </p>
*
* @param resolver ContentResolver
* @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,
@ -136,6 +186,17 @@ public class DataUtils {
return count; return count;
} }
/**
*
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param noteId ID
* @param type
* @return true false
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null,
@ -153,6 +214,16 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param noteId ID
* @return true false
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null); null, null, null, null);
@ -167,6 +238,16 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param dataId ID
* @return true false
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null); null, null, null, null);
@ -181,6 +262,16 @@ public class DataUtils {
return exist; return exist;
} }
/**
*
* <p>
*
* </p>
*
* @param resolver ContentResolver
* @param name
* @return true false
*/
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 +
@ -197,6 +288,16 @@ public class DataUtils {
return exist; return exist;
} }
/**
* Widget
* <p>
* Widget
* </p>
*
* @param resolver ContentResolver
* @param folderId ID
* @return Widget null
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
@ -224,6 +325,16 @@ public class DataUtils {
return set; return set;
} }
/**
* ID
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param noteId ID
* @return
*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER }, new String [] { CallNote.PHONE_NUMBER },
@ -243,6 +354,17 @@ public class DataUtils {
return ""; return "";
} }
/**
* ID
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param phoneNumber
* @param callDate
* @return ID 0
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID }, new String [] { CallNote.NOTE_ID },
@ -264,6 +386,17 @@ public class DataUtils {
return 0; return 0;
} }
/**
* ID
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param noteId ID
* @return
* @throws IllegalArgumentException
*/
public static String getSnippetById(ContentResolver resolver, long noteId) { public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET }, new String [] { NoteColumns.SNIPPET },
@ -282,9 +415,20 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId); throw new IllegalArgumentException("Note is not found with id: " + noteId);
} }
/**
*
* <p>
*
* </p>
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {
if (snippet != null) { if (snippet != null) {
// 去除首尾空格
snippet = snippet.trim(); snippet = snippet.trim();
// 截取到第一个换行符之前的内容
int index = snippet.indexOf('\n'); int index = snippet.indexOf('\n');
if (index != -1) { if (index != -1) {
snippet = snippet.substring(0, index); snippet = snippet.substring(0, index);

@ -16,98 +16,150 @@
package net.micode.notes.tool; package net.micode.notes.tool;
/**
* Google Tasks
* <p>
* Google Tasks JSON
*
* </p>
*/
public class GTaskStringUtils { public class GTaskStringUtils {
/** 操作 ID */
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";
/** 操作列表 */
public final static String GTASK_JSON_ACTION_LIST = "action_list"; public final static String GTASK_JSON_ACTION_LIST = "action_list";
/** 操作类型 */
public final static String GTASK_JSON_ACTION_TYPE = "action_type"; public final static String GTASK_JSON_ACTION_TYPE = "action_type";
/** 创建操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
/** 获取所有操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
/** 移动操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
/** 更新操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
/** 创建者 ID */
public final static String GTASK_JSON_CREATOR_ID = "creator_id"; public final static String GTASK_JSON_CREATOR_ID = "creator_id";
/** 子实体 */
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
/** 客户端版本 */
public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
/** 完成状态 */
public final static String GTASK_JSON_COMPLETED = "completed"; public final static String GTASK_JSON_COMPLETED = "completed";
/** 当前列表 ID */
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
/** 默认列表 ID */
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
/** 删除标记 */
public final static String GTASK_JSON_DELETED = "deleted"; public final static String GTASK_JSON_DELETED = "deleted";
/** 目标列表 */
public final static String GTASK_JSON_DEST_LIST = "dest_list"; public final static String GTASK_JSON_DEST_LIST = "dest_list";
/** 目标父节点 */
public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
/** 目标父节点类型 */
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
/** 实体增量 */
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
/** 实体类型 */
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
/** 获取已删除标记 */
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; public final static String GTASK_JSON_GET_DELETED = "get_deleted";
/** ID */
public final static String GTASK_JSON_ID = "id"; public final static String GTASK_JSON_ID = "id";
/** 索引 */
public final static String GTASK_JSON_INDEX = "index"; public final static String GTASK_JSON_INDEX = "index";
/** 最后修改时间 */
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
/** 最新同步点 */
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
/** 列表 ID */
public final static String GTASK_JSON_LIST_ID = "list_id"; public final static String GTASK_JSON_LIST_ID = "list_id";
/** 列表集合 */
public final static String GTASK_JSON_LISTS = "lists"; public final static String GTASK_JSON_LISTS = "lists";
/** 名称 */
public final static String GTASK_JSON_NAME = "name"; public final static String GTASK_JSON_NAME = "name";
/** 新 ID */
public final static String GTASK_JSON_NEW_ID = "new_id"; public final static String GTASK_JSON_NEW_ID = "new_id";
/** 笔记集合 */
public final static String GTASK_JSON_NOTES = "notes"; public final static String GTASK_JSON_NOTES = "notes";
/** 父节点 ID */
public final static String GTASK_JSON_PARENT_ID = "parent_id"; public final static String GTASK_JSON_PARENT_ID = "parent_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";
/** 结果集合 */
public final static String GTASK_JSON_RESULTS = "results"; public final static String GTASK_JSON_RESULTS = "results";
/** 源列表 */
public final static String GTASK_JSON_SOURCE_LIST = "source_list"; public final static String GTASK_JSON_SOURCE_LIST = "source_list";
/** 任务集合 */
public final static String GTASK_JSON_TASKS = "tasks"; public final static String GTASK_JSON_TASKS = "tasks";
/** 类型 */
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";
/** 用户信息 */
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";
/** 元数据 GTask 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";
} }

@ -22,24 +22,57 @@ import android.preference.PreferenceManager;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
/**
*
* <p>
* Widget
*
* </p>
*/
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;
/**
*
* <p>
*
*
* </p>
*/
public static class NoteBgResources { public static class NoteBgResources {
/** 编辑区域背景资源数组 */
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 +81,7 @@ public class ResourceParser {
R.drawable.edit_red R.drawable.edit_red
}; };
/** 标题栏背景资源数组 */
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 +90,56 @@ public class ResourceParser {
R.drawable.edit_title_red R.drawable.edit_title_red
}; };
/**
* ID
*
* @param id ID0-4
* @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 ID0-4
* @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
* <p>
*
* ID
* </p>
*
* @param context
* @return ID0-4
*/
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;
} }
} }
/**
*
* <p>
*
*
* </p>
*/
public static class NoteItemBgResources { public static class NoteItemBgResources {
/** 首项背景资源数组 */
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 +148,7 @@ public class ResourceParser {
R.drawable.list_red_up R.drawable.list_red_up
}; };
/** 中间项背景资源数组 */
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 +157,7 @@ public class ResourceParser {
R.drawable.list_red_middle R.drawable.list_red_middle
}; };
/** 末项背景资源数组 */
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 +166,7 @@ public class ResourceParser {
R.drawable.list_red_down, R.drawable.list_red_down,
}; };
/** 单项背景资源数组 */
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 +175,65 @@ public class ResourceParser {
R.drawable.list_red_single R.drawable.list_red_single
}; };
/**
* ID
*
* @param id ID0-4
* @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 ID0-4
* @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 ID0-4
* @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 ID0-4
* @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;
} }
} }
/**
* Widget
* <p>
* Widget
* 2x2 4x4 Widget
* </p>
*/
public static class WidgetBgResources { public static class WidgetBgResources {
/** 2x2 Widget 背景资源数组 */
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 +242,17 @@ public class ResourceParser {
R.drawable.widget_2x_red, R.drawable.widget_2x_red,
}; };
/**
* 2x2 Widget ID
*
* @param id ID0-4
* @return 2x2 Widget ID
*/
public static int getWidget2xBgResource(int id) { public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id]; return BG_2X_RESOURCES[id];
} }
/** 4x4 Widget 背景资源数组 */
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 +261,26 @@ public class ResourceParser {
R.drawable.widget_4x_red R.drawable.widget_4x_red
}; };
/**
* 4x4 Widget ID
*
* @param id ID0-4
* @return 4x4 Widget ID
*/
public static int getWidget4xBgResource(int id) { public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id]; return BG_4X_RESOURCES[id];
} }
} }
/**
*
* <p>
*
*
* </p>
*/
public static class TextAppearanceResources { public static class TextAppearanceResources {
/** 文本外观样式资源数组 */
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 +288,20 @@ public class ResourceParser {
R.style.TextAppearanceSuper R.style.TextAppearanceSuper
}; };
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID0-3
* @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. * HACKME: SharedPreferences ID bug
* The id may larger than the length of resources, in this case, * ID
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} * {@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 +309,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;
} }

@ -39,33 +39,70 @@ import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
/**
*
*
*
* AlarmReceiver
*
*
* 1.
* 2.
* 3.
* 4.
*
* @see NoteEditActivity
* @see net.micode.notes.tool.DataUtils
*/
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();
// 添加FLAG_SHOW_WHEN_LOCKED标志使活动可以在锁屏界面上显示
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 intent = getIntent(); Intent intent = getIntent();
try { try {
// 从Intent中解析出笔记ID
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 通过笔记ID获取笔记内容摘要
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;
@ -74,84 +111,149 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
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 {
// 设置音频源
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
e.printStackTrace(); e.printStackTrace();
} }
} }
/**
*
*
* AlertDialog
* "查看笔记"
*/
private void showActionDialog() { private void showActionDialog() {
// 创建AlertDialog构建器
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 null
* @param which ID DialogInterface.BUTTON_POSITIVE
* DialogInterface.BUTTON_NEGATIVE
*/
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 intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
// 设置动作为查看
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
// 传递笔记ID
intent.putExtra(Intent.EXTRA_UID, mNoteId); intent.putExtra(Intent.EXTRA_UID, mNoteId);
// 启动笔记编辑活动
startActivity(intent); startActivity(intent);
break; break;
// 默认情况(点击"确定"按钮)
default: default:
break; break;
} }
} }
/**
*
*
*
*
*
* @param dialog null
*/
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;
} }
} }

@ -16,49 +16,90 @@
package net.micode.notes.ui; package net.micode.notes.ui;
import android.app.AlarmManager; import android.app.AlarmManager; // 系统闹钟管理器,用于设置和管理系统级闹钟
import android.app.PendingIntent; import android.app.PendingIntent; // 延迟意图,用于在指定时间触发操作
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver; // 广播接收器基类,用于接收系统广播
import android.content.ContentUris; import android.content.ContentUris; // 用于处理内容URI的工具类
import android.content.Context; import android.content.Context; // 应用上下文,提供访问应用环境和资源的接口
import android.content.Intent; import android.content.Intent; // 意图,用于组件间通信
import android.database.Cursor; import android.database.Cursor; // 数据库游标,用于遍历查询结果
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes; // 笔记数据相关类
import net.micode.notes.data.Notes.NoteColumns; // 笔记表列定义
/**
*
*
* BroadcastReceiver
*
*
*
* 1. BOOT_COMPLETED广
* 2.
*/
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
/**
*
* ID
*/
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 // 提醒日期
}; };
private static final int COLUMN_ID = 0; // 列索引常量,用于从查询结果中获取对应列的数据
private static final int COLUMN_ALERTED_DATE = 1; private static final int COLUMN_ID = 0; // ID列在结果集中的索引
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();
// 查询所有提醒时间晚于当前时间的笔记
// 查询条件:提醒日期 > 当前时间 AND 笔记类型 = 普通笔记
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, // 查询条件
new String[] { String.valueOf(currentDate) }, new String[] { String.valueOf(currentDate) }, // 查询参数
null); 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);
// 将笔记ID作为URI数据附加到Intent中这样AlarmReceiver就能知道是哪个笔记的闹钟触发了
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它封装了上述Intent可以在指定时间触发
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);
// 设置闹钟
// 使用RTC_WAKEUP模式即使设备处于睡眠状态也会唤醒设备并触发广播
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); } while (c.moveToNext()); // 移动到下一条记录
} }
// 关闭游标,释放资源
c.close(); c.close();
} }
} }

@ -16,15 +16,48 @@
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; // 意图,用于组件间通信
/**
*
*
* BroadcastReceiverAlarmManager
* AlarmManager广广
* (AlarmAlertActivity)
*
*
* 1. AlarmInitReceiver
* 2. 广
* 3. AlarmReceiver广AlarmAlertActivity
*/
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
*
* 广
* IntentAlarmAlertActivityFLAG_ACTIVITY_NEW_TASK
* 使UIActivity
*
* @param context Activity
* @param intent 广IntentID
*/
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 将Intent的目标组件设置为AlarmAlertActivity
// 这样当启动Activity时就会显示闹钟提醒界面
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
// 添加FLAG_ACTIVITY_NEW_TASK标志
// 这是必需的因为从非Activity上下文(如BroadcastReceiver)启动Activity时
// 必须指定这个标志,表示启动一个新的任务栈
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动AlarmAlertActivity显示闹钟提醒
// 原始Intent中包含了触发闹钟的笔记ID等信息AlarmAlertActivity会使用这些信息
// 来显示相应的笔记内容和提醒信息
context.startActivity(intent); context.startActivity(intent);
} }
} }

@ -28,6 +28,28 @@ import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.NumberPicker; import android.widget.NumberPicker;
/**
*
* <p>
* FrameLayout
* 使NumberPicker/
* 2412
* </p>
* <p>
*
* <ul>
* <li>37</li>
* <li>240-23121-12</li>
* <li>0-59</li>
* <li>/12</li>
* <li></li>
* <li>/</li>
* </ul>
* </p>
*
* @see NumberPicker
* @see OnDateTimeChangedListener
*/
public class DateTimePicker extends FrameLayout { public class DateTimePicker extends FrameLayout {
private static final boolean DEFAULT_ENABLE_STATE = true; private static final boolean DEFAULT_ENABLE_STATE = true;
@ -64,36 +86,55 @@ public class DateTimePicker extends FrameLayout {
private OnDateTimeChangedListener mOnDateTimeChangedListener; private OnDateTimeChangedListener mOnDateTimeChangedListener;
/**
*
* <p>
*
* </p>
*/
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 根据选择器的变化调整日期
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl(); updateDateControl();
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
/**
*
* <p>
* 230023
* 12/
* </p>
*/
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false; boolean isDateChanged = false;
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
// 处理12小时制下的跨日情况
if (!mIs24HourView) { if (!mIs24HourView) {
// 从下午11点变为12点日期加1天
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true; isDateChanged = true;
// 从12点变为下午11点日期减1天
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { } else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1); cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true; isDateChanged = true;
} }
// 切换上午/下午
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm; mIsAm = !mIsAm;
updateAmPmControl(); updateAmPmControl();
} }
} else { } else {
// 处理24小时制下的跨日情况
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
@ -104,9 +145,11 @@ public class DateTimePicker extends FrameLayout {
isDateChanged = true; isDateChanged = true;
} }
} }
// 计算新的小时数
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour); mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged(); onDateTimeChanged();
// 如果日期发生变化,更新年月日
if (isDateChanged) { if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR)); setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH)); setCurrentMonth(cal.get(Calendar.MONTH));
@ -115,21 +158,31 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
/**
*
* <p>
* 590059
* </p>
*/
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue(); int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue(); int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0; int offset = 0;
// 从最大值变为最小值小时加1
if (oldVal == maxValue && newVal == minValue) { if (oldVal == maxValue && newVal == minValue) {
offset += 1; offset += 1;
// 从最小值变为最大值小时减1
} else if (oldVal == minValue && newVal == maxValue) { } else if (oldVal == minValue && newVal == maxValue) {
offset -= 1; offset -= 1;
} }
// 如果跨小时,更新小时和日期
if (offset != 0) { if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset); mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour()); mHourSpinner.setValue(getCurrentHour());
updateDateControl(); updateDateControl();
// 更新上午/下午状态
int newHour = getCurrentHourOfDay(); int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) { if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false; mIsAm = false;
@ -144,10 +197,17 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
/**
* /
* <p>
* //
* </p>
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm; mIsAm = !mIsAm;
// 切换上午/下午,调整小时数
if (mIsAm) { if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else { } else {
@ -158,39 +218,88 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
/**
*
* <p>
*
* </p>
*/
public interface OnDateTimeChangedListener { public interface OnDateTimeChangedListener {
/**
*
*
* @param view
* @param year
* @param month 0-11
* @param dayOfMonth 1-31
* @param hourOfDay 0-23
* @param minute 0-59
*/
void onDateTimeChanged(DateTimePicker view, int year, int month, void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute); int dayOfMonth, int hourOfDay, int minute);
} }
/**
*
*
* 使
* 使24
*
* @param context
*/
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
/**
*
*
* 使
* 使24
*
* @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));
} }
/**
*
*
* 使
* NumberPicker
*
* @param context
* @param date
* @param is24HourView 使24true24false12
*/
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();
mInitialising = true; mInitialising = true;
// 判断当前是否为下午
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,22 +307,31 @@ 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();
// 设置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;
} }
/**
*
*
* NumberPicker
*
* @param enabled truefalse
*/
@Override @Override
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) { if (mIsEnabled == enabled) {
@ -227,24 +345,29 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled; mIsEnabled = enabled;
} }
/**
*
*
* @return truefalse
*/
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return mIsEnabled; return mIsEnabled;
} }
/** /**
* Get the current date in millis *
* *
* @return the current date in millis * @return
*/ */
public long getCurrentDateInTimeMillis() { public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis(); return mDate.getTimeInMillis();
} }
/** /**
* Set the current date *
* *
* @param date The current date in millis * @param date
*/ */
public void setCurrentDate(long date) { public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
@ -254,13 +377,13 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Set the current date *
* *
* @param year The current year * @param year
* @param month The current month * @param month 0-11
* @param dayOfMonth The current dayOfMonth * @param dayOfMonth 1-31
* @param hourOfDay The current hourOfDay * @param hourOfDay 0-23
* @param minute The current minute * @param minute 0-59
*/ */
public void setCurrentDate(int year, int month, public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
@ -272,18 +395,18 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get current year *
* *
* @return The current year * @return
*/ */
public int getCurrentYear() { public int getCurrentYear() {
return mDate.get(Calendar.YEAR); return mDate.get(Calendar.YEAR);
} }
/** /**
* Set current year *
* *
* @param year The current year * @param year
*/ */
public void setCurrentYear(int year) { public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) { if (!mInitialising && year == getCurrentYear()) {
@ -295,18 +418,18 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get current month in the year *
* *
* @return The current month in the year * @return 0-11
*/ */
public int getCurrentMonth() { public int getCurrentMonth() {
return mDate.get(Calendar.MONTH); return mDate.get(Calendar.MONTH);
} }
/** /**
* Set current month in the year *
* *
* @param month The month in the year * @param month 0-11
*/ */
public void setCurrentMonth(int month) { public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) { if (!mInitialising && month == getCurrentMonth()) {
@ -318,18 +441,18 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get current day of the month *
* *
* @return The day of the month * @return 1-31
*/ */
public int getCurrentDay() { public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH); return mDate.get(Calendar.DAY_OF_MONTH);
} }
/** /**
* Set current day of the month *
* *
* @param dayOfMonth The day of the month * @param dayOfMonth 1-31
*/ */
public void setCurrentDay(int dayOfMonth) { public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) { if (!mInitialising && dayOfMonth == getCurrentDay()) {
@ -341,13 +464,21 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get current hour in 24 hour mode, in the range (0~23) * 24
* @return The current hour in 24 hour mode *
* @return 0-23
*/ */
public int getCurrentHourOfDay() { public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY); return mDate.get(Calendar.HOUR_OF_DAY);
} }
/**
*
*
* 240-23121-12
*
* @return
*/
private int getCurrentHour() { private int getCurrentHour() {
if (mIs24HourView){ if (mIs24HourView){
return getCurrentHourOfDay(); return getCurrentHourOfDay();
@ -362,9 +493,9 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Set current hour in 24 hour mode, in the range (0~23) * 24
* *
* @param hourOfDay * @param hourOfDay 0-23
*/ */
public void setCurrentHour(int hourOfDay) { public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
@ -372,6 +503,7 @@ public class DateTimePicker extends FrameLayout {
} }
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) { if (!mIs24HourView) {
// 处理12小时制下的上午/下午状态
if (hourOfDay >= HOURS_IN_HALF_DAY) { if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false; mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) { if (hourOfDay > HOURS_IN_HALF_DAY) {
@ -390,16 +522,18 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Get currentMinute *
* *
* @return The Current Minute * @return 0-59
*/ */
public int getCurrentMinute() { public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE); return mDate.get(Calendar.MINUTE);
} }
/** /**
* Set current minute *
*
* @param minute 0-59
*/ */
public void setCurrentMinute(int minute) { public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) { if (!mInitialising && minute == getCurrentMinute()) {
@ -411,22 +545,25 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* @return true if this is in 24 hour view else false. * 24
*
* @return true24false12
*/ */
public boolean is24HourView () { public boolean is24HourView () {
return mIs24HourView; return mIs24HourView;
} }
/** /**
* Set whether in 24 hour or AM/PM mode. *
* *
* @param is24HourView True for 24 hour mode. False for AM/PM mode. * @param is24HourView true使24false使12
*/ */
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) { if (mIs24HourView == is24HourView) {
return; return;
} }
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
// 根据显示模式显示或隐藏上午/下午选择器
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay(); int hour = getCurrentHourOfDay();
updateHourControl(); updateHourControl();
@ -434,30 +571,53 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl(); updateAmPmControl();
} }
/**
*
*
* 37
* "MM.dd EEEE".
*/
private void updateDateControl() { private void updateDateControl() {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
// 设置为当前日期的前4天
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null); mDateSpinner.setDisplayedValues(null);
// 生成7天的日期显示值
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
} }
mDateSpinner.setDisplayedValues(mDateDisplayValues); mDateSpinner.setDisplayedValues(mDateDisplayValues);
// 设置当前选中项为中间项
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate(); mDateSpinner.invalidate();
} }
/**
* /
*
* //
* 24/12
*/
private void updateAmPmControl() { private void updateAmPmControl() {
if (mIs24HourView) { if (mIs24HourView) {
// 24小时制下隐藏上午/下午选择器
mAmPmSpinner.setVisibility(View.GONE); mAmPmSpinner.setVisibility(View.GONE);
} else { } else {
// 12小时制下显示上午/下午选择器
int index = mIsAm ? Calendar.AM : Calendar.PM; int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index); mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE); mAmPmSpinner.setVisibility(View.VISIBLE);
} }
} }
/**
*
*
*
* 240-23121-12
*/
private void updateHourControl() { private void updateHourControl() {
if (mIs24HourView) { if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
@ -469,13 +629,19 @@ public class DateTimePicker extends FrameLayout {
} }
/** /**
* Set the callback that indicates the 'Set' button has been pressed. *
* @param callback the callback, if null will do nothing *
* @param callback null
*/ */
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback; mOnDateTimeChangedListener = callback;
} }
/**
*
*
*
*/
private void onDateTimeChanged() { private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) { if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),

@ -29,6 +29,25 @@ 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;
/**
*
* <p>
* AlertDialog
* 使DateTimePicker2412
* </p>
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li>2412</li>
* </ul>
* </p>
*
* @see DateTimePicker
* @see OnDateTimeSetListener
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
@ -36,52 +55,122 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
/**
*
* <p>
*
* </p>
*/
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
/**
*
*
* @param dialog
* @param date
*/
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
/**
*
*
* DateTimePicker
* 使24
*
* @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) {
// 更新内部Calendar对象
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);
// 将秒数清零
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
* <p>
* 使24
* true使24false使12
* </p>
*
* @param is24HourView true使24false使12
*/
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
/**
*
* <p>
* OnDateTimeSet
*
* </p>
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
/**
*
*
*
* mIs24HourView使24
*
* @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));
} }
/**
*
*
* OnDateTimeSet
*
* @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());
} }

@ -27,17 +27,49 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
/**
*
* <p>
* PopupMenuButton
*
* </p>
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
public class DropdownMenu { public class DropdownMenu {
// 下拉按钮
private Button mButton; private Button mButton;
// 弹出菜单
private PopupMenu mPopupMenu; private PopupMenu mPopupMenu;
// 菜单对象
private Menu mMenu; private Menu mMenu;
/**
*
*
* PopupMenu
*
* @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();
@ -45,16 +77,32 @@ public class DropdownMenu {
}); });
} }
/**
*
*
* @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);
} }

@ -28,50 +28,123 @@ 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;
/**
*
* <p>
* CursorAdapterListView
*
* </p>
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*
* @see NotesListActivity
*/
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
// 数据库查询投影,指定需要从笔记表中获取的列
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
// 列索引常量,用于从查询结果中获取对应列的数据
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1; public static final int NAME_COLUMN = 1;
/**
*
*
*
*
* @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
} }
/**
*
*
* FolderListItem
*
* @param context
* @param cursor
* @param parent
* @return FolderListItem
*/
@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);
} }
/**
*
*
*
*
* @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 0
* @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);
} }
/**
*
* <p>
* LinearLayout
* </p>
*/
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);
} }

@ -74,6 +74,12 @@ import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener, public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener { NoteSettingChangedListener, OnTextViewChangeListener {
/**
*
* <p>
* UI
* </p>
*/
private class HeadViewHolder { private class HeadViewHolder {
public TextView tvModified; public TextView tvModified;
@ -162,8 +168,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
/** /**
* 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 * <p>
*
* ID
* </p>
* @param savedInstanceState Bundle
*/ */
@Override @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) { protected void onRestoreInstanceState(Bundle savedInstanceState) {
@ -179,6 +189,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* <p>
* Intent
* <ul>
* <li>ACTION_VIEW: </li>
* <li>ACTION_INSERT_OR_EDIT: </li>
* </ul>
* </p>
* @param intent 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, * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
@ -268,6 +290,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
initNoteScreen(); initNoteScreen();
} }
/**
*
* <p>
*
* <ul>
* <li></li>
* <li>/</li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
private void initNoteScreen() { private void initNoteScreen() {
mNoteEditor.setTextAppearance(this, TextAppearanceResources mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId)); .getTexAppearanceResource(mFontSizeId));
@ -295,6 +329,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
showAlertHeader(); showAlertHeader();
} }
/**
*
* <p>
*
*
* </p>
*/
private void showAlertHeader() { private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) { if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
@ -318,6 +359,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
initActivityState(intent); initActivityState(intent);
} }
/**
*
* <p>
* ID便
* ID
* </p>
* @param outState Bundle
*/
@Override @Override
protected void onSaveInstanceState(Bundle outState) { protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); super.onSaveInstanceState(outState);
@ -333,6 +382,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
} }
/**
*
* <p>
*
*
* </p>
* @param ev
* @return truefalse
*/
@Override @Override
public boolean dispatchTouchEvent(MotionEvent ev) { public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
@ -349,6 +407,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return super.dispatchTouchEvent(ev); return super.dispatchTouchEvent(ev);
} }
/**
*
* <p>
*
* </p>
* @param view
* @param ev
* @return truefalse
*/
private boolean inRangeOfView(View view, MotionEvent ev) { private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2]; int []location = new int[2];
view.getLocationOnScreen(location); view.getLocationOnScreen(location);
@ -363,6 +430,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
/**
*
* <p>
* UI
* SharedPreferences
* </p>
*/
private void initResources() { private void initResources() {
mHeadViewPanel = findViewById(R.id.note_title); mHeadViewPanel = findViewById(R.id.note_title);
mNoteHeaderHolder = new HeadViewHolder(); mNoteHeaderHolder = new HeadViewHolder();
@ -397,6 +471,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
} }
/**
*
* <p>
*
* </p>
*/
@Override @Override
protected void onPause() { protected void onPause() {
super.onPause(); super.onPause();
@ -406,6 +486,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
clearSettingState(); clearSettingState();
} }
/**
*
* <p>
* 广2x4x
* </p>
*/
private void updateWidget() { private void updateWidget() {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
@ -425,6 +511,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
/**
*
* <p>
* UI
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* @param v
*/
public void onClick(View v) { public void onClick(View v) {
int id = v.getId(); int id = v.getId();
if (id == R.id.btn_set_bg_color) { if (id == R.id.btn_set_bg_color) {
@ -452,6 +550,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* <p>
*
* 退
* </p>
*/
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if(clearSettingState()) { if(clearSettingState()) {
@ -462,6 +567,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
super.onBackPressed(); super.onBackPressed();
} }
/**
*
* <p>
*
* </p>
* @return truefalse
*/
private boolean clearSettingState() { private boolean clearSettingState() {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE); mNoteBgColorSelector.setVisibility(View.GONE);
@ -473,6 +585,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return false; return false;
} }
/**
*
* <p>
* UI
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
public void onBackgroundColorChanged() { public void onBackgroundColorChanged() {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE); View.VISIBLE);
@ -480,6 +603,19 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
} }
/**
*
* <p>
*
* <ul>
* <li>使</li>
* <li></li>
* <li>/</li>
* </ul>
* </p>
* @param menu
* @return true
*/
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
if (isFinishing()) { if (isFinishing()) {
@ -505,6 +641,24 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li>/</li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* @param item
* @return true
*/
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
@ -553,6 +707,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true; return true;
} }
/**
*
* <p>
*
*
* </p>
*/
private void setReminder() { private void setReminder() {
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
d.setOnDateTimeSetListener(new OnDateTimeSetListener() { d.setOnDateTimeSetListener(new OnDateTimeSetListener() {
@ -564,8 +725,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
/** /**
* Share note to apps that support {@link Intent#ACTION_SEND} action *
* and {@text/plain} type * <p>
* 使ACTION_SEND Intent
* </p>
* @param context
* @param info
*/ */
private void sendTo(Context context, String info) { private void sendTo(Context context, String info) {
Intent intent = new Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
@ -574,6 +739,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
context.startActivity(intent); context.startActivity(intent);
} }
/**
*
* <p>
* NoteEditActivity
*
* </p>
*/
private void createNewNote() { private void createNewNote() {
// Firstly, save current editing notes // Firstly, save current editing notes
saveNote(); saveNote();
@ -586,6 +758,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
startActivity(intent); startActivity(intent);
} }
/**
*
* <p>
*
*
* </p>
*/
private void deleteCurrentNote() { private void deleteCurrentNote() {
if (mWorkingNote.existInDatabase()) { if (mWorkingNote.existInDatabase()) {
HashSet<Long> ids = new HashSet<Long>(); HashSet<Long> ids = new HashSet<Long>();
@ -608,10 +787,27 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote.markDeleted(true); mWorkingNote.markDeleted(true);
} }
/**
*
* <p>
*
* </p>
* @return truefalse
*/
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
/**
*
* <p>
*
*
* 使AlarmManager
* </p>
* @param date
* @param set truefalse
*/
public void onClockAlertChanged(long date, boolean set) { public void onClockAlertChanged(long date, boolean set) {
/** /**
* User could set clock to an unsaved note, so before setting the * User could set clock to an unsaved note, so before setting the
@ -642,10 +838,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* <p>
*
* </p>
*/
public void onWidgetChanged() { public void onWidgetChanged() {
updateWidget(); updateWidget();
} }
/**
*
* <p>
*
*
* </p>
* @param index
* @param text
*/
public void onEditTextDelete(int index, String text) { public void onEditTextDelete(int index, String text) {
int childCount = mEditTextList.getChildCount(); int childCount = mEditTextList.getChildCount();
if (childCount == 1) { if (childCount == 1) {
@ -672,6 +883,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.setSelection(length); edit.setSelection(length);
} }
/**
*
* <p>
*
*
* </p>
* @param index
* @param text
*/
public void onEditTextEnter(int index, String text) { public void onEditTextEnter(int index, String text) {
/** /**
* Should not happen, check for debug * Should not happen, check for debug
@ -691,6 +911,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* <p>
*
*
* </p>
* @param text
*/
private void switchToListMode(String text) { private void switchToListMode(String text) {
mEditTextList.removeAllViews(); mEditTextList.removeAllViews();
String[] items = text.split("\n"); String[] items = text.split("\n");
@ -708,6 +936,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList.setVisibility(View.VISIBLE); mEditTextList.setVisibility(View.VISIBLE);
} }
/**
*
* <p>
*
* 使
* </p>
* @param fullText
* @param userQuery
* @return Spannable
*/
private Spannable getHighlightQueryResult(String fullText, String userQuery) { private Spannable getHighlightQueryResult(String fullText, String userQuery) {
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
if (!TextUtils.isEmpty(userQuery)) { if (!TextUtils.isEmpty(userQuery)) {
@ -725,6 +963,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return spannable; return spannable;
} }
/**
*
* <p>
*
*
* </p>
* @param item
* @param index
* @return
*/
private View getListItem(String item, int index) { private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
@ -756,6 +1004,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return view; return view;
} }
/**
*
* <p>
*
*
* </p>
* @param index
* @param hasText
*/
public void onTextChange(int index, boolean hasText) { public void onTextChange(int index, boolean hasText) {
if (index >= mEditTextList.getChildCount()) { if (index >= mEditTextList.getChildCount()) {
Log.e(TAG, "Wrong index, should not happen"); Log.e(TAG, "Wrong index, should not happen");
@ -768,6 +1025,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* <p>
*
*
*
* </p>
* @param oldMode
* @param newMode
*/
public void onCheckListModeChanged(int oldMode, int newMode) { public void onCheckListModeChanged(int oldMode, int newMode) {
if (newMode == TextNote.MODE_CHECK_LIST) { if (newMode == TextNote.MODE_CHECK_LIST) {
switchToListMode(mNoteEditor.getText().toString()); switchToListMode(mNoteEditor.getText().toString());
@ -782,6 +1049,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* <p>
* WorkingNote
*
* </p>
* @return truefalse
*/
private boolean getWorkingText() { private boolean getWorkingText() {
boolean hasChecked = false; boolean hasChecked = false;
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
@ -805,6 +1080,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return hasChecked; return hasChecked;
} }
/**
*
* <p>
*
* RESULT_OK/
* </p>
* @return truefalse
*/
private boolean saveNote() { private boolean saveNote() {
getWorkingText(); getWorkingText();
boolean saved = mWorkingNote.saveNote(); boolean saved = mWorkingNote.saveNote();
@ -821,6 +1104,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return saved; return saved;
} }
/**
*
* <p>
*
*
* 使10
* </p>
*/
private void sendToDesktop() { private void sendToDesktop() {
/** /**
* Before send message to home, we should make sure that current * Before send message to home, we should make sure that current
@ -856,6 +1147,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
} }
} }
/**
*
* <p>
*
* 10
* </p>
* @param content
* @return
*/
private String makeShortcutIconTitle(String content) { private String makeShortcutIconTitle(String content) {
content = content.replace(TAG_CHECKED, ""); content = content.replace(TAG_CHECKED, "");
content = content.replace(TAG_UNCHECKED, ""); content = content.replace(TAG_UNCHECKED, "");
@ -863,10 +1163,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
SHORTCUT_ICON_TITLE_MAX_LEN) : content; SHORTCUT_ICON_TITLE_MAX_LEN) : content;
} }
/**
* Toast
* <p>
* Toast
* </p>
* @param resId ID
*/
private void showToast(int resId) { private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT); showToast(resId, Toast.LENGTH_SHORT);
} }
/**
* Toast
* <p>
* Toast
* </p>
* @param resId ID
* @param duration Toast.LENGTH_SHORTToast.LENGTH_LONG
*/
private void showToast(int resId, int duration) { private void showToast(int resId, int duration) {
Toast.makeText(this, resId, duration).show(); Toast.makeText(this, resId, duration).show();
} }

@ -37,15 +37,40 @@ import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
/**
*
* <p>
* EditText
* NoteEditActivity
* </p>
* <p>
*
* <ul>
* <li>EditText</li>
* <li>URL</li>
* <li></li>
* <li></li>
* </ul>
* </p>
*
* @see NoteEditActivity
*/
public class NoteEditText extends EditText { public class NoteEditText extends EditText {
// 日志标签
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText";
// 当前EditText的索引
private int mIndex; private int mIndex;
// 删除前的光标位置
private int mSelectionStartBeforeDelete; private int mSelectionStartBeforeDelete;
// 电话号码URI方案
private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_TEL = "tel:" ;
// HTTP URI方案
private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_HTTP = "http:" ;
// 邮件URI方案
private static final String SCHEME_EMAIL = "mailto:" ; private static final String SCHEME_EMAIL = "mailto:" ;
// URI方案与上下文菜单资源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,66 +79,119 @@ public class NoteEditText extends EditText {
} }
/** /**
* Call by the {@link NoteEditActivity} to delete or add edit text *
* <p>
* NoteEditActivityEditText
* </p>
*
* @see NoteEditActivity
*/ */
public interface OnTextViewChangeListener { public interface OnTextViewChangeListener {
/** /**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens *
* and the text is null *
* @param index EditText
* @param text EditText
*/ */
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 EditText
* @param text EditText
*/ */
void onEditTextEnter(int index, String text); void onEditTextEnter(int index, String text);
/** /**
* Hide or show item option when text change *
*
* @param index EditText
* @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;
} }
/**
* EditText
*
* @param index EditText
*/
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 XML
*/
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 XML
* @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
} }
/**
*
*
*
*
* @param event
* @return truefalse
*/
@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();
y -= getTotalPaddingTop(); y -= getTotalPaddingTop();
// 加上滚动偏移量
x += getScrollX(); x += getScrollX();
y += getScrollY(); y += getScrollY();
Layout layout = getLayout(); Layout layout = getLayout();
// 获取触摸点所在的行号
int line = layout.getLineForVertical(y); int line = layout.getLineForVertical(y);
// 获取触摸点在行中的字符偏移量
int off = layout.getOffsetForHorizontal(line, x); int off = layout.getOffsetForHorizontal(line, x);
// 设置文本选择光标位置
Selection.setSelection(getText(), off); Selection.setSelection(getText(), off);
break; break;
} }
@ -121,15 +199,26 @@ public class NoteEditText extends EditText {
return super.onTouchEvent(event); return super.onTouchEvent(event);
} }
/**
*
*
*
*
* @param keyCode
* @param event
* @return truefalse
*/
@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:
// 如果设置了监听器返回false让onKeyUp处理
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 +227,22 @@ public class NoteEditText extends EditText {
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event);
} }
/**
*
*
*
*
* @param keyCode
* @param event
* @return truefalse
*/
@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) {
// 如果光标在开头且不是第一个EditText删除当前EditText
if (0 == mSelectionStartBeforeDelete && mIndex != 0) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true; return true;
@ -152,10 +252,14 @@ 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));
// 通知监听器创建新的EditText
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,10 +271,20 @@ 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 {
mOnTextViewChangeListener.onTextChange(mIndex, true); mOnTextViewChangeListener.onTextChange(mIndex, true);
@ -179,18 +293,28 @@ 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) {
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {
int selStart = getSelectionStart(); int selStart = getSelectionStart();
int selEnd = getSelectionEnd(); int selEnd = getSelectionEnd();
// 获取选区的起始和结束位置
int min = Math.min(selStart, selEnd); int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd); int max = Math.max(selStart, selEnd);
// 获取选区内的所有URLSpan
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;
// 根据URL类型确定菜单项文本
for(String schema: sSchemaActionResMap.keySet()) { for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) { if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema); defaultResId = sSchemaActionResMap.get(schema);
@ -202,10 +326,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;
} }

@ -25,8 +25,27 @@ 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;
/**
*
* <p>
*
* 便访
* </p>
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*
* @see NotesListItem
* @see NotesListAdapter
*/
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,6 +61,7 @@ public class NoteItemData {
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_TYPE,
}; };
// 列索引常量,用于从查询结果中获取对应列的数据
private static final int ID_COLUMN = 0; private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1; private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int BG_COLOR_ID_COLUMN = 2;
@ -55,27 +75,55 @@ public class NoteItemData {
private static final int WIDGET_ID_COLUMN = 10; private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11; private static final int WIDGET_TYPE_COLUMN = 11;
// 笔记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
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 PROJECTION
*/
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);
@ -86,6 +134,7 @@ 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);
@ -93,10 +142,12 @@ public class NoteItemData {
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,9 +157,17 @@ 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;
@ -116,17 +175,21 @@ public class NoteItemData {
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 +197,203 @@ 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 0
*/
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;
} }
/**
* ID
*
* @return ID
*/
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
/**
*
*
* @return
*/
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; return mNotesCount;
} }
/**
* ID
*
* @return IDgetParentId
*/
public long getFolderId () { public long getFolderId () {
return mParentId; return mParentId;
} }
/**
*
*
* @return Notes.TYPE_NOTENotes.TYPE_FOLDERNotes.TYPE_SYSTEM
*/
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));
} }
/**
*
*
* NoteItemData
*
* @param cursor TYPE_COLUMN
* @return
*/
public static int getNoteType(Cursor cursor) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }

@ -78,63 +78,119 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashSet; import java.util.HashSet;
/**
*
*
*
*
*
*
* 1.
* 2.
* 3.
* 4. Google Tasks
* 5.
* 6.
*
* @see NoteEditActivity
* @see NotesListAdapter
* @see GTaskSyncService
*/
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;
// 普通选择条件指定父文件夹ID
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);
@ -147,6 +203,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
setAppInfoFromRawRes(); setAppInfoFromRawRes();
} }
/**
*
*
*
*
* @param requestCode
* @param resultCode RESULT_OK
* @param data Intent
*/
@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
@ -157,6 +222,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
*
* 使res/raw/introduction
*/
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)) {
@ -203,12 +273,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
*
*
*/
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
startAsyncNotesListQuery(); startAsyncNotesListQuery();
} }
/**
*
*
* UI
*/
private void initResources() { private void initResources() {
mContentResolver = this.getContentResolver(); mContentResolver = this.getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
@ -231,11 +311,23 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mModeCallBack = new ModeCallback(); mModeCallBack = new ModeCallback();
} }
/**
*
*
* ListView.MultiChoiceModeListener
*/
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 ActionMode
* @param menu
* @return true
*/
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);
@ -259,7 +351,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
(Button) customView.findViewById(R.id.selection_menu), (Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown); R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) { /**
*
*
* @param item
* @return true
*/
public boolean onMenuItemClick(MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu(); updateMenu();
return true; return true;
@ -269,6 +367,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
/**
*
*
*
*/
private void updateMenu() { private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount(); int selectedCount = mNotesListAdapter.getSelectedCount();
// Update dropdown menu // Update dropdown menu
@ -286,26 +389,60 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
*
* @param mode ActionMode
* @param menu
* @return false
*/
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
/**
*
*
* @param mode ActionMode
* @param item
* @return false
*/
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub // TODO Auto-generated method stub
return false; return false;
} }
/**
*
*
* 退
*
* @param mode ActionMode
*/
public void onDestroyActionMode(ActionMode mode) { public void onDestroyActionMode(ActionMode mode) {
mNotesListAdapter.setChoiceMode(false); mNotesListAdapter.setChoiceMode(false);
mNotesListView.setLongClickable(true); mNotesListView.setLongClickable(true);
mAddNewNote.setVisibility(View.VISIBLE); mAddNewNote.setVisibility(View.VISIBLE);
} }
/**
*
*
* ActionMode
*/
public void finishActionMode() { public void finishActionMode() {
mActionMode.finish(); mActionMode.finish();
} }
/**
*
*
* @param mode ActionMode
* @param position
* @param id ID
* @param checked
*/
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) { boolean checked) {
mNotesListAdapter.setCheckedItem(position, checked); mNotesListAdapter.setCheckedItem(position, checked);
@ -408,6 +545,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}; };
/**
*
* <p>
* ID
* 使使
* </p>
*/
private void startAsyncNotesListQuery() { private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION; : NORMAL_SELECTION;
@ -417,11 +561,35 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
} }
/**
*
* <p>
* AsyncQueryHandler线
* UI线
* </p>
*/
private final class BackgroundQueryHandler extends AsyncQueryHandler { private final class BackgroundQueryHandler extends AsyncQueryHandler {
/**
*
* @param contentResolver
*/
public BackgroundQueryHandler(ContentResolver contentResolver) { public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver); super(contentResolver);
} }
/**
*
* <p>
*
* <ul>
* <li>FOLDER_NOTE_LIST_QUERY_TOKEN: </li>
* <li>FOLDER_LIST_QUERY_TOKEN: </li>
* </ul>
* </p>
* @param token
* @param cookie Cookie
* @param cursor
*/
@Override @Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) { protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) { switch (token) {
@ -441,6 +609,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
* <p>
*
*
* </p>
* @param cursor
*/
private void showFolderListMenu(Cursor cursor) { private void showFolderListMenu(Cursor cursor) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder); builder.setTitle(R.string.menu_title_select_folder);
@ -462,6 +638,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.show(); builder.show();
} }
/**
*
* <p>
* NoteEditActivityID
* </p>
*/
private void createNewNote() { private void createNewNote() {
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
@ -469,6 +651,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
} }
/**
*
* <p>
* 线
*
*
* </p>
*/
private void batchDelete() { private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
@ -506,6 +696,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute(); }.execute();
} }
/**
*
* <p>
*
*
*
* </p>
* @param folderId ID
*/
private void deleteFolder(long folderId) { private void deleteFolder(long folderId) {
if (folderId == Notes.ID_ROOT_FOLDER) { if (folderId == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Wrong folder id, should not happen " + folderId); Log.e(TAG, "Wrong folder id, should not happen " + folderId);
@ -533,6 +732,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
* <p>
* NoteEditActivity
* </p>
* @param data
*/
private void openNode(NoteItemData data) { private void openNode(NoteItemData data) {
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
@ -540,6 +746,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
} }
/**
*
* <p>
*
*
* </p>
* @param data
*/
private void openFolder(NoteItemData data) { private void openFolder(NoteItemData data) {
mCurrentFolderId = data.getId(); mCurrentFolderId = data.getId();
startAsyncNotesListQuery(); startAsyncNotesListQuery();
@ -567,6 +781,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
* <p>
*
* </p>
*/
private void showSoftInput() { private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) { if (inputMethodManager != null) {
@ -574,11 +794,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
* <p>
*
* </p>
* @param view
*/
private void hideSoftInput(View view) { private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
} }
/**
*
* <p>
*
* create
* </p>
* @param create truefalse
*/
private void showCreateOrModifyFolderDialog(final boolean create) { private void showCreateOrModifyFolderDialog(final boolean create) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this); final AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
@ -664,6 +899,16 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
} }
/**
*
* <p>
*
* <ul>
* <li></li>
* <li>退Activity</li>
* </ul>
* </p>
*/
@Override @Override
public void onBackPressed() { public void onBackPressed() {
switch (mState) { switch (mState) {
@ -688,6 +933,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
/**
*
* <p>
* 广使
* </p>
* @param appWidgetId ID
* @param appWidgetType 2x4x
*/
private void updateWidget(int appWidgetId, int appWidgetType) { private void updateWidget(int appWidgetId, int appWidgetType) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) { if (appWidgetType == Notes.TYPE_WIDGET_2X) {
@ -707,6 +960,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
} }
/**
*
* <p>
*
* </p>
*/
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
@ -760,6 +1019,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* @param menu
* @return true
*/
@Override @Override
public boolean onPrepareOptionsMenu(Menu menu) { public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear(); menu.clear();
@ -778,6 +1050,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* @param item
* @return true
*/
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
@ -818,12 +1106,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true; return true;
} }
/**
*
* <p>
*
* </p>
* @return true
*/
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false); startSearch(null, false, null /* appData */, false);
return true; return true;
} }
/**
*
* <p>
* 线SD
*
* </p>
*/
private void exportNoteToText() { private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() { new AsyncTask<Void, Void, Integer>() {
@ -866,19 +1168,51 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute(); }.execute();
} }
/**
*
* <p>
*
* </p>
* @return truefalse
*/
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
} }
/**
* Activity
* <p>
* NotesPreferenceActivity
* </p>
*/
private void startPreferenceActivity() { private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this; Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class); Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1); from.startActivityIfNeeded(intent, -1);
} }
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li>/</li>
* </ul>
* </p>
*/
private class OnListItemClickListener implements OnItemClickListener { private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { /**
*
*
* @param parent
* @param view
* @param position
* @param id ID
*/
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
NoteItemData item = ((NotesListItem) view).getItemData(); NoteItemData item = ((NotesListItem) view).getItemData();
if (mNotesListAdapter.isInChoiceMode()) { if (mNotesListAdapter.isInChoiceMode()) {
@ -917,6 +1251,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
/**
*
* <p>
*
*
* </p>
*/
private void startQueryDestinationFolders() { private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection: selection = (mState == ListEditState.NOTE_LIST) ? selection:
@ -935,6 +1276,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
NoteColumns.MODIFIED_DATE + " DESC"); NoteColumns.MODIFIED_DATE + " DESC");
} }
/**
*
*
* @param parent
* @param view
* @param position
* @param id ID
* @return true
*/
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData(); mFocusNoteDataItem = ((NotesListItem) view).getItemData();

@ -31,18 +31,51 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
/**
*
*
* CursorAdapterListView
*
*
*
* 1. NotesListItem
* 2.
* 3. ID
* 4.
*
* @see NotesListItem
* @see NoteItemData
*/
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;
// 记录选中状态的Mapkey为位置value为是否选中
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;
}; };
/**
*
*
* Map
*
* @param context null
*/
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); mSelectedIndex = new HashMap<Integer, Boolean>();
@ -50,11 +83,28 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0; mNotesCount = 0;
} }
/**
*
*
* @param context
* @param cursor
* @param parent
* @return NotesListItem
*/
@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) {
@ -64,20 +114,41 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
/**
*
*
* @param position 0
* @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 truefalse退
*/
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); mSelectedIndex.clear();
mChoiceMode = mode; mChoiceMode = mode;
} }
/**
*
*
* @param checked truefalse
*/
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
@ -89,6 +160,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 +181,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
/**
*
*
* @return HashSetnull
*/
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 +209,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
/**
*
*
* @return 0
*/
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
if (null == values) { if (null == values) {
@ -143,11 +229,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 0
* @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,12 +252,22 @@ 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);

@ -30,6 +30,14 @@ import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources; import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
*
* <p>
* LinearLayout
*
*
* </p>
*/
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert; private ImageView mAlert;
private TextView mTitle; private TextView mTitle;
@ -38,6 +46,10 @@ public class NotesListItem extends LinearLayout {
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);
@ -48,6 +60,13 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
} }
/**
*
* @param context 访
* @param data NoteItemData
* @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);
@ -99,6 +118,10 @@ public class NotesListItem extends LinearLayout {
setBackground(data); setBackground(data);
} }
/**
*
* @param data NoteItemData
*/
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
@ -116,6 +139,10 @@ public class NotesListItem extends LinearLayout {
} }
} }
/**
*
* @return NoteItemData
*/
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData;
} }

@ -48,27 +48,85 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
/**
* Activity
* <p>
* Activity
* <ul>
* <li>Google Tasks</li>
* <li></li>
* <li></li>
* </ul>
* </p>
* <p>
* PreferenceActivity使SharedPreferences
* GTaskReceiver广
* </p>
*/
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
/**
* SharedPreferences
*/
public static final String PREFERENCE_NAME = "notes_preferences"; public static final String PREFERENCE_NAME = "notes_preferences";
/**
* SharedPreferences
*/
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
/**
* SharedPreferences
*/
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
/**
* SharedPreferences
*/
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";
/**
* Preference
*/
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
/**
* Intent
*/
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
/**
* PreferenceCategory
*/
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
/**
* 广
*/
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
/**
*
*/
private Account[] mOriAccounts; private Account[] mOriAccounts;
/**
*
*/
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
/**
* Activity
* <p>
*
* <ul>
* <li>ActionBar</li>
* <li>preferences.xml</li>
* <li>广</li>
* <li></li>
* </ul>
* </p>
* @param icicle
*/
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
@ -88,6 +146,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
} }
/**
* Activity
* <p>
* Google
* UI
* </p>
*/
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
@ -116,6 +181,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
refreshUI(); refreshUI();
} }
/**
* Activity
* <p>
* 广
* </p>
*/
@Override @Override
protected void onDestroy() { protected void onDestroy() {
if (mReceiver != null) { if (mReceiver != null) {
@ -124,6 +195,18 @@ public class NotesPreferenceActivity extends PreferenceActivity {
super.onDestroy(); super.onDestroy();
} }
/**
*
* <p>
* Preference
* Preference
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll(); mAccountCategory.removeAll();
@ -154,6 +237,17 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
/**
*
* <p>
*
* <ul>
* <li>"取消同步"</li>
* <li>"立即同步"</li>
* </ul>
*
* </p>
*/
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);
@ -193,11 +287,24 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
/**
* UI
* <p>
*
* </p>
*/
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
/**
*
* <p>
* Google
* "添加账户"
* </p>
*/
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@ -254,6 +361,17 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
} }
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@ -283,11 +401,29 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.show(); dialogBuilder.show();
} }
/**
* Google
* <p>
* AccountManager"com.google"
* </p>
* @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");
} }
/**
*
* <p>
* SharedPreferences
* <ul>
* <li></li>
* <li>GTASK_IDSYNC_ID</li>
* </ul>
* </p>
* @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);
@ -318,6 +454,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
/**
*
* <p>
* SharedPreferences
* GTASK_IDSYNC_ID
* </p>
*/
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();
@ -340,12 +483,28 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start(); }).start();
} }
/**
*
* <p>
* SharedPreferences
* </p>
* @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, "");
} }
/**
*
* <p>
* SharedPreferences
* </p>
* @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,14 +513,36 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit(); editor.commit();
} }
/**
*
* <p>
* SharedPreferences
* </p>
* @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);
} }
/**
* 广
* <p>
* GTaskSyncService广UI
* </p>
*/
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
/**
* 广
* <p>
* 广UI
* </p>
* @param context
* @param intent 广Intent
*/
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI(); refreshUI();
@ -374,6 +555,15 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
/**
*
* <p>
* ActionBar
*
* </p>
* @param item
* @return truefalse
*/
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:

Loading…
Cancel
Save