Compare commits

..

17 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
mbls3xqnp ffd73e60a9 Merge pull request '添加部分注释' (#4) from baoerjun_branch into develop
3 weeks ago
p7tupf26b 09fa62c08f Merge pull request '将小米便签的报告重命名后合并' (#2) from jiangtianxiang_branch into develop
2 months 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;
/**
*
* <p>
* 使
* AndroidContactsContract Provider
* </p>
* <p>
*
* <ul>
* <li></li>
* <li>使HashMap</li>
* <li></li>
* </ul>
* </p>
* <p>
* 使
* 使
* </p>
*
* @see ContactsContract
* @see PhoneNumberUtils
*/
public class Contact {
/**
*
* <p>
* 使HashMap
*
* </p>
* Key:
* Value:
*/
private static HashMap<String, String> sContactCache;
/**
*
*/
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
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
@ -36,15 +78,30 @@ public class Contact {
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
*
* <p>
*
*
*
* </p>
*
* @param context 访ContentResolver
* @param phoneNumber
* @return null
*/
public static String getContact(Context context, String phoneNumber) {
// 初始化缓存
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 检查缓存中是否已存在
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
// 构建查询条件使用toCallerIDMinMatch进行号码最小匹配
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query(
@ -54,6 +111,7 @@ public class Contact {
new String[] { phoneNumber },
null);
// 处理查询结果
if (cursor != null && cursor.moveToFirst()) {
try {
String name = cursor.getString(0);

@ -17,33 +17,103 @@
package net.micode.notes.data;
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 {
/**
* Content ProviderAuthority
*/
public static final String AUTHORITY = "micode_notes";
/**
*
*/
public static final String TAG = "Notes";
/**
*
*/
public static final int TYPE_NOTE = 0;
/**
*
*/
public static final int TYPE_FOLDER = 1;
/**
*
*/
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
* ID
* {@link Notes#ID_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER }
* {@link Notes#ID_CALL_RECORD_FOLDER}
*/
public static final int ID_ROOT_FOLDER = 0;
/**
* ID
*/
public static final int ID_TEMPARAY_FOLDER = -1;
/**
* ID
*/
public static final int ID_CALL_RECORD_FOLDER = -2;
/**
* ID
*/
public static final int ID_TRASH_FOLER = -3;
/**
* Intent Extra
*/
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";
/**
* Intent ExtraWidget 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";
/**
* Intent ExtraID
*/
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";
/**
* Widget
*/
public static final int TYPE_WIDGET_INVALIDE = -1;
/**
* 2x2 Widget
*/
public static final int TYPE_WIDGET_2X = 0;
/**
* 4x4 Widget
*/
public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants {

@ -27,21 +27,114 @@ import net.micode.notes.data.Notes.DataConstants;
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 {
/**
*
*/
private static final String DB_NAME = "note.db";
/**
*
* <p>
* 4
* onUpgrade
* </p>
*/
private static final int DB_VERSION = 4;
/**
*
*/
public interface TABLE {
/**
*
* <p>
* IDID
* Widget
* IDIDGTASK ID
* </p>
*/
public static final String NOTE = "note";
/**
*
* <p>
* MIME
* MIME5
* </p>
*/
public static final String DATA = "data";
}
/**
*
*/
private static final String TAG = "NotesDatabaseHelper";
/**
*
* <p>
* 使
*
* </p>
*/
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 =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
@ -63,6 +156,21 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
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 =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
@ -78,6 +186,12 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";
/**
* SQL
* <p>
* dataNOTE_IDID
* </p>
*/
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
@ -206,10 +320,23 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";
/**
*
*
* @param context
*/
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
*
* <p>
* noteSQL
* </p>
*
* @param db SQLiteDatabase
*/
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
@ -217,7 +344,17 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created");
}
/**
*
* <p>
* note
*
* </p>
*
* @param db SQLiteDatabase
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
// 删除所有已存在的触发器
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
@ -226,6 +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_move_notes_on_trash");
// 重新创建所有触发器
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
@ -235,12 +373,27 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
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) {
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*/
// 创建通话记录文件夹
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
@ -248,6 +401,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* root folder which is default folder
*/
// 创建根文件夹(默认文件夹)
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -256,6 +410,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* temporary folder which is used for moving note
*/
// 创建临时文件夹(用于移动笔记)
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
@ -264,12 +419,21 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
/**
* create trash folder
*/
// 创建回收站文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
*
* <p>
* dataSQL
* </p>
*
* @param db SQLiteDatabase
*/
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
@ -277,16 +441,36 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created");
}
/**
*
* <p>
* data
*
* </p>
*
* @param db SQLiteDatabase
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) {
// 删除所有已存在的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
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_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}
/**
*
* <p>
* 使线
* </p>
*
* @param context
* @return NotesDatabaseHelper
*/
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
@ -294,45 +478,78 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance;
}
/**
*
* <p>
* notedata
* </p>
*
* @param db SQLiteDatabase
*/
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}
/**
*
* <p>
*
*
* </p>
*
* @param db SQLiteDatabase
* @param oldVersion
* @param newVersion
* @throws IllegalStateException
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
boolean reCreateTriggers = false;
boolean skipV2 = false;
// 从V1升级到V2包括V2到V3
if (oldVersion == 1) {
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++;
}
// 从V2升级到V3
if (oldVersion == 2 && !skipV2) {
upgradeToV3(db);
reCreateTriggers = true;
oldVersion++;
}
// 从V3升级到V4
if (oldVersion == 3) {
upgradeToV4(db);
oldVersion++;
}
// 如果需要,重新创建触发器
if (reCreateTriggers) {
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
// 检查升级是否成功
if (oldVersion != newVersion) {
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
}
}
/**
* V2
* <p>
* notedata
* </p>
*
* @param db SQLiteDatabase
*/
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
@ -340,21 +557,40 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
createDataTable(db);
}
/**
* V3
* <p>
* GTASK_IDnote
* </p>
*
* @param db SQLiteDatabase
*/
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
// 删除未使用的触发器
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
// 添加GTASK_ID列
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
// 添加回收站系统文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}
/**
* V4
* <p>
* VERSIONnote
* </p>
*
* @param db SQLiteDatabase
*/
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");

@ -35,21 +35,97 @@ import net.micode.notes.data.Notes.NoteColumns;
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 {
/**
* URI
* <p>
* URI
* URI
* </p>
*/
private static final UriMatcher mMatcher;
/**
*
* <p>
* SQLiteDatabase
* </p>
*/
private NotesDatabaseHelper mHelper;
/**
*
*/
private static final String TAG = "NotesProvider";
/**
* URI
*/
private static final int URI_NOTE = 1;
/**
* URI
*/
private static final int URI_NOTE_ITEM = 2;
/**
* URI
*/
private static final int URI_DATA = 3;
/**
* URI
*/
private static final int URI_DATA_ITEM = 4;
/**
* URI
*/
private static final int URI_SEARCH = 5;
/**
* URI
*/
private static final int URI_SEARCH_SUGGEST = 6;
/**
* URI
* <p>
* UriMatcherURI
* </p>
*/
static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
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 + ","
+ 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 + ","
+ "'" + 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
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
/**
* Content Provider
* <p>
*
* </p>
*
* @return true
*/
@Override
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
/**
*
* <p>
* URI
* 使LIKE
* </p>
*
* @param uri URI
* @param projection
* @param selection
* @param selectionArgs
* @param sortOrder
* @return Cursor
* @throws IllegalArgumentException URI
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
@ -93,25 +207,30 @@ public class NotesProvider extends ContentProvider {
String id = null;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 查询所有笔记
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
// 查询指定ID的笔记
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
// 查询所有数据
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
// 查询指定ID的数据
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH:
case URI_SEARCH_SUGGEST:
// 搜索笔记或搜索建议
if (sortOrder != null || projection != null) {
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
@ -119,18 +238,22 @@ public class NotesProvider extends ContentProvider {
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
// 从URI路径中获取搜索关键词
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {
// 从查询参数中获取搜索关键词
searchString = uri.getQueryParameter("pattern");
}
// 搜索关键词为空时返回null
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
// 使用模糊匹配搜索笔记摘要
searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
@ -141,21 +264,36 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 设置通知URI当数据变更时通知观察者
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
/**
*
* <p>
* URI
* URI
* </p>
*
* @param uri URI
* @param values
* @return URIID
* @throws IllegalArgumentException URI
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 插入笔记
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
case URI_DATA:
// 插入数据
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
@ -167,12 +305,14 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
// 通知笔记URI的观察者
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
// 通知数据URI的观察者
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
@ -181,6 +321,20 @@ public class NotesProvider extends ContentProvider {
return ContentUris.withAppendedId(uri, insertedId);
}
/**
*
* <p>
* URI
* ID0
* URI
* </p>
*
* @param uri URI
* @param selection
* @param selectionArgs
* @return
* @throws IllegalArgumentException URI
*/
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int count = 0;
@ -189,14 +343,17 @@ public class NotesProvider extends ContentProvider {
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 删除笔记(排除系统文件夹)
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
// 删除指定ID的笔记
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
* ID0
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
@ -206,10 +363,12 @@ public class NotesProvider extends ContentProvider {
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 删除数据
count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true;
break;
case URI_DATA_ITEM:
// 删除指定ID的数据
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
@ -218,8 +377,10 @@ public class NotesProvider extends ContentProvider {
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 删除成功后通知观察者
if (count > 0) {
if (deleteData) {
// 删除数据时通知笔记URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
@ -227,6 +388,21 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
*
* <p>
* URI
*
* URI
* </p>
*
* @param uri URI
* @param values
* @param selection
* @param selectionArgs
* @return
* @throws IllegalArgumentException URI
*/
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
@ -235,20 +411,24 @@ public class NotesProvider extends ContentProvider {
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 更新笔记(递增版本号)
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
// 更新指定ID的笔记递增版本号
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 更新数据
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
// 更新指定ID的数据
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
@ -258,8 +438,10 @@ public class NotesProvider extends ContentProvider {
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 更新成功后通知观察者
if (count > 0) {
if (updateData) {
// 更新数据时通知笔记URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
@ -267,10 +449,30 @@ public class NotesProvider extends ContentProvider {
return count;
}
/**
*
* <p>
* IDSQL WHERE
* </p>
*
* @param selection
* @return
*/
private String parseSelection(String 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) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
@ -279,6 +481,7 @@ public class NotesProvider extends ContentProvider {
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
// 构建WHERE子句
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
@ -287,6 +490,7 @@ public class NotesProvider extends ContentProvider {
}
if (!TextUtils.isEmpty(selection)) {
String selectString = id > 0 ? parseSelection(selection) : selection;
// 替换查询条件中的占位符
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
@ -296,10 +500,18 @@ public class NotesProvider extends ContentProvider {
mHelper.getWritableDatabase().execSQL(sql.toString());
}
/**
* MIME
* <p>
* URIMIME
* </p>
*
* @param uri URI
* @return MIME
*/
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}

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

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

@ -35,24 +35,39 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* SQLite
* <p>
*
* MIME
* JSON JSON Google Tasks
* </p>
*/
public class SqlData {
private static final String TAG = SqlData.class.getSimpleName();
/** 无效 ID 标识符 */
private static final int INVALID_ID = -99999;
/** 数据表查询投影字段数组 */
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
/** ID 字段在投影数组中的索引 */
public static final int DATA_ID_COLUMN = 0;
/** MIME 类型字段在投影数组中的索引 */
public static final int DATA_MIME_TYPE_COLUMN = 1;
/** 内容字段在投影数组中的索引 */
public static final int DATA_CONTENT_COLUMN = 2;
/** 扩展数据 1 字段在投影数组中的索引 */
public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
/** 扩展数据 3 字段在投影数组中的索引 */
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver;
@ -71,6 +86,15 @@ public class SqlData {
private ContentValues mDiffDataValues;
/**
*
* <p>
*
* commit
* </p>
*
* @param context ContentResolver
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -82,6 +106,16 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
*
* <p>
*
* commit
* </p>
*
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -89,6 +123,14 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/**
*
* <p>
*
* </p>
*
* @param c
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -97,6 +139,16 @@ public class SqlData {
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 {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
@ -130,6 +182,15 @@ public class SqlData {
mDataContentData3 = dataContentData3;
}
/**
* JSON
* <p>
* JSON
* </p>
*
* @return JSON null
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
@ -144,6 +205,19 @@ public class SqlData {
return js;
}
/**
*
* <p>
*
* - ID
* -
* </p>
*
* @param noteId ID
* @param validateVersion true
* @param version
* @throws ActionFailureException
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
@ -166,6 +240,7 @@ public class SqlData {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
} else {
// 仅更新笔记版本号匹配的记录,防止并发更新冲突
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
@ -183,6 +258,11 @@ public class SqlData {
mIsCreate = false;
}
/**
* ID
*
* @return ID
*/
public long getId() {
return mDataId;
}

@ -38,11 +38,21 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* SQLite
* <p>
*
* Google Tasks JSON JSON
*
* </p>
*/
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
/** 无效 ID 标识符 */
private static final int INVALID_ID = -99999;
/** 笔记表查询投影字段数组 */
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -52,38 +62,55 @@ public class SqlNote {
NoteColumns.VERSION
};
/** ID 字段在投影数组中的索引 */
public static final int ID_COLUMN = 0;
/** 提醒日期字段在投影数组中的索引 */
public static final int ALERTED_DATE_COLUMN = 1;
/** 背景颜色 ID 字段在投影数组中的索引 */
public static final int BG_COLOR_ID_COLUMN = 2;
/** 创建日期字段在投影数组中的索引 */
public static final int CREATED_DATE_COLUMN = 3;
/** 是否有附件字段在投影数组中的索引 */
public static final int HAS_ATTACHMENT_COLUMN = 4;
/** 修改日期字段在投影数组中的索引 */
public static final int MODIFIED_DATE_COLUMN = 5;
/** 子笔记数量字段在投影数组中的索引 */
public static final int NOTES_COUNT_COLUMN = 6;
/** 父文件夹 ID 字段在投影数组中的索引 */
public static final int PARENT_ID_COLUMN = 7;
/** 摘要文本字段在投影数组中的索引 */
public static final int SNIPPET_COLUMN = 8;
/** 笔记类型字段在投影数组中的索引 */
public static final int TYPE_COLUMN = 9;
/** Widget ID 字段在投影数组中的索引 */
public static final int WIDGET_ID_COLUMN = 10;
/** Widget 类型字段在投影数组中的索引 */
public static final int WIDGET_TYPE_COLUMN = 11;
/** 同步 ID 字段在投影数组中的索引 */
public static final int SYNC_ID_COLUMN = 12;
/** 本地修改标记字段在投影数组中的索引 */
public static final int LOCAL_MODIFIED_COLUMN = 13;
/** 原始父文件夹 ID 字段在投影数组中的索引 */
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
/** Google Tasks ID 字段在投影数组中的索引 */
public static final int GTASK_ID_COLUMN = 15;
/** 版本号字段在投影数组中的索引 */
public static final int VERSION_COLUMN = 16;
private Context mContext;
@ -122,6 +149,15 @@ public class SqlNote {
private ArrayList<SqlData> mDataList;
/**
*
* <p>
*
* commit
* </p>
*
* @param context ContentResolver
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -143,6 +179,16 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>();
}
/**
*
* <p>
*
* commit
* </p>
*
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -154,6 +200,16 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
}
/**
* ID
* <p>
* ID
* commit
* </p>
*
* @param context
* @param id ID
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -166,6 +222,14 @@ public class SqlNote {
}
/**
* ID
* <p>
* ID loadFromCursor(Cursor)
* </p>
*
* @param id ID
*/
private void loadFromCursor(long id) {
Cursor c = null;
try {
@ -185,6 +249,14 @@ public class SqlNote {
}
}
/**
*
* <p>
*
* </p>
*
* @param c
*/
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -200,6 +272,13 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN);
}
/**
*
* <p>
* Data SqlData
*
* </p>
*/
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
@ -226,6 +305,17 @@ public class SqlNote {
}
}
/**
* JSON
* <p>
* JSON
*
*
* </p>
*
* @param js JSON
* @return true false
*/
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -359,6 +449,15 @@ public class SqlNote {
return true;
}
/**
* JSON
* <p>
* JSON
* JSON
* </p>
*
* @return JSON null
*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -407,39 +506,102 @@ public class SqlNote {
return null;
}
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID
*/
public void setParentId(long id) {
mParentId = 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) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
/**
* ID
* <p>
*
* </p>
*
* @param syncId
*/
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
/**
*
* <p>
* 0
* </p>
*/
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
/**
* ID
*
* @return ID INVALID_ID
*/
public long getId() {
return mId;
}
/**
* ID
*
* @return ID
*/
public long getParentId() {
return mParentId;
}
/**
*
*
* @return
*/
public String getSnippet() {
return mSnippet;
}
/**
*
*
* @return true false
*/
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
/**
*
* <p>
*
* - ID
* -
* -
* </p>
*
* @param validateVersion true
* @throws ActionFailureException
* @throws IllegalStateException ID
*/
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
@ -476,6 +638,7 @@ public class SqlNote {
String.valueOf(mId)
});
} else {
// 仅更新版本号不大于当前版本的记录,防止并发更新冲突
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
@ -494,7 +657,7 @@ public class SqlNote {
}
}
// refresh local info
// 从数据库重新加载最新数据,确保内存状态与数据库一致
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();

@ -32,19 +32,51 @@ import org.json.JSONException;
import org.json.JSONObject;
/**
* Google Tasks
* <p>
* Node Google Tasks
*
* JSON
* </p>
*/
public class Task extends Node {
/**
*
*/
private static final String TAG = Task.class.getSimpleName();
/**
* true
*/
private boolean mCompleted;
/**
*
*/
private String mNotes;
/**
* JSON
*/
private JSONObject mMetaInfo;
/**
*
*/
private Task mPriorSibling;
/**
*
*/
private TaskList mParent;
/**
*
* <p>
* null
* </p>
*/
public Task() {
super();
mCompleted = false;
@ -54,6 +86,16 @@ public class Task extends Node {
mMetaInfo = null;
}
/**
* JSON
* <p>
* JSON ID
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -103,6 +145,16 @@ public class Task extends Node {
return js;
}
/**
* JSON
* <p>
* JSON
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -135,6 +187,15 @@ public class Task extends Node {
return js;
}
/**
* JSON
* <p>
* JSON ID
* </p>
*
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -175,6 +236,15 @@ public class Task extends Node {
}
}
/**
* JSON
* <p>
* JSON
*
* </p>
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
@ -190,6 +260,7 @@ public class Task extends Node {
return;
}
// 遍历数据数组,查找笔记内容
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
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() {
String name = getName();
try {
@ -229,6 +309,7 @@ public class Task extends Node {
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 更新数据数组中的笔记内容
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
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) {
if (metaData != null && metaData.getNotes() != null) {
try {
@ -258,6 +348,16 @@ public class Task extends Node {
}
}
/**
*
* <p>
*
*
* </p>
*
* @param c
* @return SYNC_ACTION_*
*/
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
@ -311,39 +411,87 @@ public class Task extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
* <p>
*
* </p>
*
* @return true false
*/
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}
/**
*
*
* @param completed true
*/
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}
/**
*
*
* @param notes
*/
public void setNotes(String notes) {
this.mNotes = notes;
}
/**
*
*
* @param priorSibling
*/
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}
/**
*
*
* @param parent
*/
public void setParent(TaskList parent) {
this.mParent = parent;
}
/**
*
*
* @return true
*/
public boolean getCompleted() {
return this.mCompleted;
}
/**
*
*
* @return
*/
public String getNotes() {
return this.mNotes;
}
/**
*
*
* @return
*/
public Task getPriorSibling() {
return this.mPriorSibling;
}
/**
*
*
* @return
*/
public TaskList getParent() {
return this.mParent;
}

@ -30,19 +30,52 @@ import org.json.JSONObject;
import java.util.ArrayList;
/**
* Google Tasks
* <p>
* Node Google Tasks
*
* JSON
* </p>
*/
public class TaskList extends Node {
/**
*
*/
private static final String TAG = TaskList.class.getSimpleName();
/**
*
*/
private int mIndex;
/**
*
*/
private ArrayList<Task> mChildren;
/**
*
* <p>
* 1
* </p>
*/
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
/**
* JSON
* <p>
* JSON
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -74,6 +107,16 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* <p>
* JSON
* </p>
*
* @param actionId ID
* @return JSON
* @throws ActionFailureException JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -103,6 +146,15 @@ public class TaskList extends Node {
return js;
}
/**
* JSON
* <p>
* JSON
* </p>
*
* @param js JSON
* @throws ActionFailureException JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
@ -129,6 +181,15 @@ public class TaskList extends Node {
}
}
/**
* JSON
* <p>
* JSON
*
* </p>
*
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
@ -138,9 +199,11 @@ public class TaskList extends Node {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 普通文件夹,使用文件夹名称
String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
// 系统文件夹,根据 ID 设置对应的名称
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);
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() {
try {
JSONObject js = new JSONObject();
JSONObject folder = new JSONObject();
// 去除文件夹名称前缀
String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length());
folder.put(NoteColumns.SNIPPET, folderName);
// 根据文件夹名称判断类型
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
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) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
@ -216,10 +300,24 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
/**
*
*
* @return
*/
public int getChildTaskCount() {
return mChildren.size();
}
/**
*
* <p>
*
* </p>
*
* @param task
* @return true false
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
@ -234,6 +332,16 @@ public class TaskList extends Node {
return ret;
}
/**
*
* <p>
*
* </p>
*
* @param task
* @param index 0
* @return true false
*/
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
@ -260,6 +368,16 @@ public class TaskList extends Node {
return true;
}
/**
*
* <p>
*
*
* </p>
*
* @param task
* @return true false
*/
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -281,6 +399,16 @@ public class TaskList extends Node {
return ret;
}
/**
*
* <p>
*
* </p>
*
* @param task
* @param index 0 1
* @return true false
*/
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -299,6 +427,12 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index));
}
/**
* GID
*
* @param gid Google Tasks ID
* @return null
*/
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -309,10 +443,22 @@ public class TaskList extends Node {
return null;
}
/**
*
*
* @param task
* @return -1
*/
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
/**
*
*
* @param index 0 1
* @return null
*/
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -321,6 +467,12 @@ public class TaskList extends Node {
return mChildren.get(index);
}
/**
* GID
*
* @param gid Google Tasks ID
* @return null
*/
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
@ -329,14 +481,29 @@ public class TaskList extends Node {
return null;
}
/**
*
*
* @return
*/
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}
/**
*
*
* @param index
*/
public void setIndex(int index) {
this.mIndex = index;
}
/**
*
*
* @return
*/
public int getIndex() {
return this.mIndex;
}

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

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

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

@ -61,15 +61,27 @@ import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/**
* Google Tasks
* <p>
* Google Tasks API Google Tasks
*
* 使 HTTP Google Tasks API Cookie
* </p>
*/
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
/** Google Tasks 基础 URL */
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";
/** Google Tasks POST 请求 URL */
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
/** 单例实例 */
private static GTaskClient mInstance = null;
private DefaultHttpClient mHttpClient;
@ -90,6 +102,12 @@ public class GTaskClient {
private JSONArray mUpdateArray;
/**
*
* <p>
*
* </p>
*/
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -102,6 +120,14 @@ public class GTaskClient {
mUpdateArray = null;
}
/**
* GTaskClient
* <p>
* 使线
* </p>
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -109,6 +135,17 @@ public class GTaskClient {
return mInstance;
}
/**
* Google Tasks
* <p>
*
* Cookie 5
* Gmail/Googlemail
* </p>
*
* @param activity Activity
* @return true false
*/
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
@ -164,6 +201,26 @@ public class GTaskClient {
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) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
@ -207,6 +264,16 @@ public class GTaskClient {
return authToken;
}
/**
* Google Tasks
* <p>
* 使 Google Tasks使
* </p>
*
* @param activity Activity
* @param authToken
* @return true false
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
@ -225,6 +292,15 @@ public class GTaskClient {
return true;
}
/**
* 使 Google Tasks
* <p>
* Google Tasks GET Cookie
* </p>
*
* @param authToken
* @return true false
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000;
@ -280,10 +356,26 @@ public class GTaskClient {
return true;
}
/**
* ID
* <p>
* ID
* </p>
*
* @return ID
*/
private int getActionId() {
return mActionId++;
}
/**
* HTTP POST
* <p>
* application/x-www-form-urlencoded
* </p>
*
* @return HttpPost
*/
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -291,6 +383,16 @@ public class GTaskClient {
return httpPost;
}
/**
* HTTP
* <p>
* HTTP gzip deflate
* </p>
*
* @param entity HTTP
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = 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 {
if (!mLoggedin) {
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 {
commitUpdate();
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 {
commitUpdate();
try {
@ -412,6 +545,16 @@ public class GTaskClient {
}
}
/**
*
* <p>
* Google Tasks
*
* </p>
*
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
@ -433,6 +576,15 @@ public class GTaskClient {
}
}
/**
*
* <p>
* 10
* </p>
*
* @param node null
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// 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)
throws NetworkFailureException {
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 {
commitUpdate();
try {
@ -509,6 +683,16 @@ public class GTaskClient {
}
}
/**
*
* <p>
* Google Tasks
* </p>
*
* @return JSON
* @throws NetworkFailureException
* @throws ActionFailureException JSON
*/
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
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 {
commitUpdate();
try {
@ -575,10 +770,21 @@ public class GTaskClient {
}
}
/**
*
*
* @return Google
*/
public Account getSyncAccount() {
return mAccount;
}
/**
*
* <p>
*
* </p>
*/
public void resetUpdateArray() {
mUpdateArray = null;
}

@ -48,17 +48,30 @@ import java.util.Iterator;
import java.util.Map;
/**
* Google Tasks
* <p>
* Google Tasks
*
*
* </p>
*/
public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName();
/** 同步成功状态码 */
public static final int STATE_SUCCESS = 0;
/** 网络错误状态码 */
public static final int STATE_NETWORK_ERROR = 1;
/** 内部错误状态码 */
public static final int STATE_INTERNAL_ERROR = 2;
/** 同步进行中状态码 */
public static final int STATE_SYNC_IN_PROGRESS = 3;
/** 同步已取消状态码 */
public static final int STATE_SYNC_CANCELLED = 4;
private static GTaskManager mInstance = null;
@ -87,6 +100,12 @@ public class GTaskManager {
private HashMap<Long, String> mNidToGid;
/**
*
* <p>
*
* </p>
*/
private GTaskManager() {
mSyncing = false;
mCancelled = false;
@ -99,6 +118,14 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>();
}
/**
* GTaskManager
* <p>
* 使线
* </p>
*
* @return GTaskManager
*/
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -106,11 +133,30 @@ public class GTaskManager {
return mInstance;
}
/**
* Activity
* <p>
* Google
* </p>
*
* @param activity Activity
*/
public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
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) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
@ -790,10 +836,21 @@ public class GTaskManager {
}
}
/**
*
*
* @return Google
*/
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
return mActivity == null ? null : GTaskClient.getInstance().getSyncAccount().name;
}
/**
*
* <p>
*
* </p>
*/
public void cancelSync() {
mCancelled = true;
}

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

@ -34,15 +34,36 @@ import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
*
* <p>
*
*
* </p>
*/
public class Note {
/** 笔记差异值,用于记录需要同步的字段变更 */
private ContentValues mNoteDiffValues;
/** 笔记数据对象,包含文本数据和通话数据 */
private NoteData mNoteData;
/** 日志标签 */
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) {
// Create a new note in the database
// 在数据库中创建新笔记
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime);
@ -54,6 +75,7 @@ public class Note {
long noteId = 0;
try {
// 从 URI 中提取笔记 ID
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
@ -65,41 +87,114 @@ public class Note {
return noteId;
}
/**
*
* <p>
*
* </p>
*/
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
}
/**
*
* <p>
*
* </p>
*
* @param key
* @param value
*/
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
*
* <p>
*
* </p>
*
* @param key
* @param value
*/
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID
*/
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
/**
* ID
*
* @return ID
*/
public long getTextDataId() {
return mNoteData.mTextDataId;
}
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID
*/
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
/**
*
* <p>
*
* </p>
*
* @param key
* @param value
*/
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
/**
*
* <p>
*
* </p>
*
* @return true false
*/
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
*
* <p>
*
*
* </p>
*
* @param context
* @param noteId ID
* @return true false
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
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#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
* {@link NoteColumns#LOCAL_MODIFIED}
* {@link NoteColumns#MODIFIED_DATE}使
*/
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
// 不返回,继续执行
}
mNoteDiffValues.clear();
@ -130,17 +224,35 @@ public class Note {
return true;
}
/**
*
* <p>
*
*
* </p>
*/
private class NoteData {
/** 文本数据 ID */
private long mTextDataId;
/** 文本数据值 */
private ContentValues mTextDataValues;
/** 通话数据 ID */
private long mCallDataId;
/** 通话数据值 */
private ContentValues mCallDataValues;
/** 日志标签 */
private static final String TAG = "NoteData";
/**
*
* <p>
* ContentValues
* </p>
*/
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
@ -148,10 +260,26 @@ public class Note {
mCallDataId = 0;
}
/**
*
* <p>
*
* </p>
*
* @return true false
*/
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID 0
*/
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
@ -159,6 +287,14 @@ public class Note {
mTextDataId = id;
}
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID 0
*/
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
@ -166,21 +302,50 @@ public class Note {
mCallDataId = id;
}
/**
*
* <p>
*
* </p>
*
* @param key
* @param value
*/
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
*
* <p>
*
* </p>
*
* @param key
* @param value
*/
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
/**
* ContentResolver
* <p>
*
*
* </p>
*
* @param context
* @param noteId ID
* @return URI null
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
@ -189,9 +354,11 @@ public class Note {
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
// 处理文本数据
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
// 新增文本数据
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
@ -203,6 +370,7 @@ public class Note {
return null;
}
} else {
// 更新现有文本数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
@ -211,9 +379,11 @@ public class Note {
mTextDataValues.clear();
}
// 处理通话数据
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
// 新增通话数据
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
@ -225,6 +395,7 @@ public class Note {
return null;
}
} else {
// 更新现有通话数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
@ -233,6 +404,7 @@ public class Note {
mCallDataValues.clear();
}
// 批量执行更新操作
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(

@ -32,36 +32,57 @@ import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
*
* <p>
*
*
* </p>
*/
public class WorkingNote {
// Note for the working note
/** 底层笔记对象 */
private Note mNote;
// Note Id
/** 笔记 ID */
private long mNoteId;
// Note content
/** 笔记内容 */
private String mContent;
// Note mode
/** 笔记模式 */
private int mMode;
/** 提醒日期 */
private long mAlertDate;
/** 修改日期 */
private long mModifiedDate;
/** 背景颜色 ID */
private int mBgColorId;
/** Widget ID */
private int mWidgetId;
/** Widget 类型 */
private int mWidgetType;
/** 父文件夹 ID */
private long mFolderId;
/** 应用上下文 */
private Context mContext;
/** 日志标签 */
private static final String TAG = "WorkingNote";
/** 是否已删除 */
private boolean mIsDeleted;
/** 笔记设置变更监听器 */
private NoteSettingChangedListener mNoteSettingStatusListener;
/** 数据查询投影 - 笔记数据 */
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
@ -72,6 +93,7 @@ public class WorkingNote {
DataColumns.DATA4,
};
/** 数据查询投影 - 笔记元数据 */
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
@ -81,26 +103,45 @@ public class WorkingNote {
NoteColumns.MODIFIED_DATE
};
/** 数据 ID 列索引 */
private static final int DATA_ID_COLUMN = 0;
/** 数据内容列索引 */
private static final int DATA_CONTENT_COLUMN = 1;
/** 数据 MIME 类型列索引 */
private static final int DATA_MIME_TYPE_COLUMN = 2;
/** 数据模式列索引 */
private static final int DATA_MODE_COLUMN = 3;
/** 笔记父 ID 列索引 */
private static final int NOTE_PARENT_ID_COLUMN = 0;
/** 笔记提醒日期列索引 */
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
/** 笔记背景颜色 ID 列索引 */
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
/** 笔记 Widget ID 列索引 */
private static final int NOTE_WIDGET_ID_COLUMN = 3;
/** 笔记 Widget 类型列索引 */
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
/** 笔记修改日期列索引 */
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
/**
*
* <p>
*
* </p>
*
* @param context
* @param folderId ID
*/
// New note construct
private WorkingNote(Context context, long folderId) {
mContext = context;
@ -114,6 +155,16 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
/**
*
* <p>
*
* </p>
*
* @param context
* @param noteId ID
* @param folderId ID
*/
// Existing note construct
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
@ -125,6 +176,12 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
* <p>
* Widget
* </p>
=======
*
*
* ID
@ -132,6 +189,7 @@ public class WorkingNote {
*
*
* @throws IllegalArgumentException ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
private void loadNote() {
// 构建查询URI通过笔记ID定位特定的笔记记录
@ -163,8 +221,15 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
* <p>
*
* </p>
=======
* loadNote()loadNoteData()
* ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
private void loadNoteData() {
// 通过ContentResolver查询数据库获取指定笔记ID的数据
@ -188,16 +253,25 @@ public class WorkingNote {
// 如果是普通文本笔记类型
if (DataConstants.NOTE.equals(type)) {
<<<<<<< HEAD
// 加载文本笔记数据
=======
// 获取笔记的文本内容
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
mContent = cursor.getString(DATA_CONTENT_COLUMN);
// 获取笔记的显示模式(普通模式或清单模式)
mMode = cursor.getInt(DATA_MODE_COLUMN);
// 设置文本数据的ID用于后续更新操作
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
<<<<<<< HEAD
} else if (DataConstants.CALL_NOTE.equals(type)) {
// 加载通话记录数据
=======
}
// 如果是通话记录笔记类型
else if (DataConstants.CALL_NOTE.equals(type)) {
// 设置通话记录数据的ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
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 defaultBgColorId ID
* @return WorkingNote
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
@ -244,6 +332,16 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
* <p>
* ID
* </p>
*
* @param context
* @param id ID
* @return WorkingNote
=======
* ID
*
*
@ -254,6 +352,7 @@ public class WorkingNote {
* @param id IDID
* @return WorkingNote
* @throws IllegalArgumentException ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
public static WorkingNote load(Context context, long id) {
// 创建一个新的WorkingNote实例传入笔记ID和文件夹ID(0表示不指定)
@ -262,32 +361,56 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
* <p>
*
*
* Widget Widget
* </p>
*
* @return true false
=======
*
*
* ID
* 使synchronized线
*
* @return truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
public synchronized boolean saveNote() {
// 检查笔记是否值得保存(非空内容或已修改)
if (isWorthSaving()) {
// 如果笔记在数据库中不存在新笔记则需要先获取一个新的笔记ID
if (!existInDatabase()) {
<<<<<<< HEAD
// 创建新笔记
=======
// 调用Note.getNewNoteId()方法获取一个新的笔记ID
// 如果获取失败返回0记录错误日志并返回false
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
<<<<<<< HEAD
// 同步笔记数据
mNote.syncNote(mContext, mNoteId);
/**
* Widget Widget
*/
=======
// 将笔记数据同步到数据库
// 这会更新笔记的基本信息和内容数据
mNote.syncNote(mContext, mNoteId);
// 如果笔记关联了桌面小部件,则更新小部件显示内容
// 检查条件小部件ID有效、小部件类型有效、状态监听器不为空
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
@ -303,9 +426,15 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
*
* @return ID 0 true false
=======
*
*
* @return truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
public boolean existInDatabase() {
// 通过检查笔记ID是否大于0来判断笔记是否已保存到数据库
@ -314,9 +443,18 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
* <p>
*
* </p>
*
* @return true false
=======
*
*
* @return truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
private boolean isWorthSaving() {
// 检查笔记是否已被删除、是否为空内容(新笔记)、是否已修改(已存在笔记)
@ -329,6 +467,11 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
*
* @param l
=======
*
*
*
@ -340,6 +483,7 @@ public class WorkingNote {
*
* @param l NoteSettingChangedListener
* null
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
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 set truefalse
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
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
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
public void markDeleted(boolean mark) {
// 设置笔记的删除标记状态
@ -403,6 +566,14 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
* ID
* <p>
*
* </p>
*
* @param id ID
=======
* ID
*
* setAlertDate
@ -414,6 +585,7 @@ public class WorkingNote {
*
*
* @param id ID
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
public void setBgColorId(int id) {
// 检查新的背景颜色ID是否与当前ID不同
@ -434,6 +606,14 @@ public class WorkingNote {
}
/**
<<<<<<< HEAD
*
* <p>
*
* </p>
*
* @param mode
=======
*
*
*
@ -445,6 +625,7 @@ public class WorkingNote {
*
*
* @param mode
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
public void setCheckListMode(int mode) {
// 检查新的模式是否与当前模式不同
@ -464,6 +645,11 @@ public class WorkingNote {
}
}
/**
* Widget
*
* @param type Widget
*/
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -471,6 +657,11 @@ public class WorkingNote {
}
}
/**
* Widget ID
*
* @param id Widget ID
*/
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -478,6 +669,14 @@ public class WorkingNote {
}
}
/**
*
* <p>
*
* </p>
*
* @param text
*/
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -485,61 +684,140 @@ public class WorkingNote {
}
}
/**
*
* <p>
*
* </p>
*
* @param phoneNumber
* @param callDate
*/
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
/**
*
*
* @return true false
*/
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
/**
*
*
* @return
*/
public String getContent() {
return mContent;
}
/**
*
*
* @return
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
*
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
*
* @return ID
*/
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
/**
* ID
*
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
*
* @return ID
*/
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
/**
*
*
* @return
*/
public int getCheckListMode() {
return mMode;
}
/**
* ID
*
* @return ID
*/
public long getNoteId() {
return mNoteId;
}
/**
* ID
*
* @return ID
*/
public long getFolderId() {
return mFolderId;
}
/**
* Widget ID
*
* @return Widget ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* Widget
*
* @return Widget
*/
public int getWidgetType() {
return mWidgetType;
}
/**
<<<<<<< HEAD
*
* <p>
* UI
* </p>
*/
public interface NoteSettingChangedListener {
/**
*
=======
*
*
* UI
@ -550,27 +828,45 @@ public class WorkingNote {
*
*
* UI
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
void onBackgroundColorChanged();
/**
<<<<<<< HEAD
*
*
* @param date
* @param set
=======
*
*
* @param date 0
* @param set truefalse
*
* 使AlarmManagerPendingIntent
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
void onClockAlertChanged(long date, boolean set);
/**
<<<<<<< HEAD
* Widget
=======
*
*
* 广
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
void onWidgetChanged();
/**
<<<<<<< HEAD
*
*
* @param oldMode
* @param newMode
=======
*
*
* @param oldMode
@ -578,6 +874,7 @@ public class WorkingNote {
*
* UI
*
>>>>>>> 8cd4ff2539c552b724aa36c59ade10d85e72d6f8
*/
void onCheckListModeChanged(int oldMode, int newMode);
}

@ -36,11 +36,27 @@ import java.io.IOException;
import java.io.PrintStream;
/**
*
* <p>
*
* SD
* 使
* </p>
*/
public class BackupUtils {
/** 日志标签 */
private static final String TAG = "BackupUtils";
// Singleton stuff
/** 单例实例 */
private static BackupUtils sInstance;
/**
*
*
* @param context
* @return
*/
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
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
/** SD 卡未挂载 */
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
/** 备份文件不存在 */
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
/** 数据格式损坏,可能被其他程序修改 */
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
/** 系统错误,运行时异常导致备份或恢复失败 */
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
/** 备份或恢复成功 */
public static final int STATE_SUCCESS = 4;
/** 文本导出对象 */
private TextExport mTextExport;
/**
*
*
* @param context
*/
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
/**
*
*
* @return true false
*/
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
/**
*
*
* @return STATE_SD_CARD_UNMOUONTEDSTATE_SYSTEM_ERROR STATE_SUCCESS
*/
public int exportToText() {
return mTextExport.exportToText();
}
/**
*
*
* @return
*/
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
/**
*
*
* @return
*/
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
/**
*
* <p>
*
*
* </p>
*/
private static class TextExport {
/** 笔记查询投影字段 */
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
@ -93,12 +150,16 @@ public class BackupUtils {
NoteColumns.TYPE
};
/** 笔记 ID 列索引 */
private static final int NOTE_COLUMN_ID = 0;
/** 笔记修改日期列索引 */
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
/** 笔记摘要列索引 */
private static final int NOTE_COLUMN_SNIPPET = 2;
/** 数据查询投影字段 */
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
@ -108,23 +169,39 @@ public class BackupUtils {
DataColumns.DATA4,
};
/** 数据内容列索引 */
private static final int DATA_COLUMN_CONTENT = 0;
/** 数据 MIME 类型列索引 */
private static final int DATA_COLUMN_MIME_TYPE = 1;
/** 通话日期列索引 */
private static final int DATA_COLUMN_CALL_DATE = 2;
/** 电话号码列索引 */
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
/** 导出文本格式数组 */
private final String [] TEXT_FORMAT;
/** 文件夹名称格式索引 */
private static final int FORMAT_FOLDER_NAME = 0;
/** 笔记日期格式索引 */
private static final int FORMAT_NOTE_DATE = 1;
/** 笔记内容格式索引 */
private static final int FORMAT_NOTE_CONTENT = 2;
/** 应用上下文 */
private Context mContext;
/** 导出文件名 */
private String mFileName;
/** 导出文件目录 */
private String mFileDirectory;
/**
*
*
* @param context
*/
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
@ -132,12 +209,24 @@ public class BackupUtils {
mFileDirectory = "";
}
/**
*
*
* @param id
* @return
*/
private String getFormat(int 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) {
// 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) {
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() {
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() {
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) {
StringBuilder sb = new StringBuilder();
@ -325,9 +439,11 @@ public class BackupUtils {
try {
if (!filedir.exists()) {
// 创建目录
filedir.mkdir();
}
if (!file.exists()) {
// 创建文件
file.createNewFile();
}
return file;

@ -35,8 +35,28 @@ import java.util.ArrayList;
import java.util.HashSet;
/**
*
* <p>
*
*
* </p>
*/
public class 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) {
if (ids == null) {
Log.d(TAG, "the ids is null");
@ -50,6 +70,7 @@ public class DataUtils {
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
// 跳过系统根文件夹
Log.e(TAG, "Don't delete system folder root");
continue;
}
@ -72,6 +93,17 @@ public class DataUtils {
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) {
ContentValues values = new ContentValues();
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);
}
/**
*
* <p>
*
* </p>
*
* @param resolver ContentResolver
* @param ids ID
* @param folderId ID
* @return true false
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
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) {
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
@ -136,6 +186,17 @@ public class DataUtils {
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) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
@ -153,6 +214,16 @@ public class DataUtils {
return exist;
}
/**
*
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param noteId ID
* @return true false
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
@ -167,6 +238,16 @@ public class DataUtils {
return exist;
}
/**
*
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param dataId ID
* @return true false
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
@ -181,6 +262,16 @@ public class DataUtils {
return exist;
}
/**
*
* <p>
*
* </p>
*
* @param resolver ContentResolver
* @param name
* @return true false
*/
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
@ -197,6 +288,16 @@ public class DataUtils {
return exist;
}
/**
* Widget
* <p>
* Widget
* </p>
*
* @param resolver ContentResolver
* @param folderId ID
* @return Widget null
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
@ -224,6 +325,16 @@ public class DataUtils {
return set;
}
/**
* ID
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param noteId ID
* @return
*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
@ -243,6 +354,17 @@ public class DataUtils {
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) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
@ -264,6 +386,17 @@ public class DataUtils {
return 0;
}
/**
* ID
* <p>
* ID
* </p>
*
* @param resolver ContentResolver
* @param noteId ID
* @return
* @throws IllegalArgumentException
*/
public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
@ -282,9 +415,20 @@ public class DataUtils {
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
/**
*
* <p>
*
* </p>
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) {
if (snippet != null) {
// 去除首尾空格
snippet = snippet.trim();
// 截取到第一个换行符之前的内容
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);

@ -16,98 +16,150 @@
package net.micode.notes.tool;
/**
* Google Tasks
* <p>
* Google Tasks JSON
*
* </p>
*/
public class GTaskStringUtils {
/** 操作 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_TYPE = "action_type";
/** 创建操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
/** 获取所有操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
/** 移动操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
/** 更新操作类型 */
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
/** 创建者 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_CLIENT_VERSION = "client_version";
/** 完成状态 */
public final static String GTASK_JSON_COMPLETED = "completed";
/** 当前列表 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_DELETED = "deleted";
/** 目标列表 */
public final static String GTASK_JSON_DEST_LIST = "dest_list";
/** 目标父节点 */
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
/** 目标父节点类型 */
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
/** 实体增量 */
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
/** 实体类型 */
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
/** 获取已删除标记 */
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_INDEX = "index";
/** 最后修改时间 */
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
/** 最新同步点 */
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_LISTS = "lists";
/** 名称 */
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_NOTES = "notes";
/** 父节点 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_RESULTS = "results";
/** 源列表 */
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
/** 任务集合 */
public final static String GTASK_JSON_TASKS = "tasks";
/** 类型 */
public final static String GTASK_JSON_TYPE = "type";
/** 分组类型 */
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
/** 任务类型 */
public final static String GTASK_JSON_TYPE_TASK = "TASK";
/** 用户信息 */
public final static String GTASK_JSON_USER = "user";
/** MIUI 文件夹前缀 */
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
/** 默认文件夹名称 */
public final static String FOLDER_DEFAULT = "Default";
/** 通话记录文件夹名称 */
public final static String FOLDER_CALL_NOTE = "Call_Note";
/** 元数据文件夹名称 */
public final static String FOLDER_META = "METADATA";
/** 元数据 GTask ID 头 */
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_DATA = "meta_data";
/** 元数据笔记名称 */
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.ui.NotesPreferenceActivity;
/**
*
* <p>
* Widget
*
* </p>
*/
public class ResourceParser {
/** 黄色背景 */
public static final int YELLOW = 0;
/** 蓝色背景 */
public static final int BLUE = 1;
/** 白色背景 */
public static final int WHITE = 2;
/** 绿色背景 */
public static final int GREEN = 3;
/** 红色背景 */
public static final int RED = 4;
/** 默认背景颜色 */
public static final int BG_DEFAULT_COLOR = YELLOW;
/** 小号字体 */
public static final int TEXT_SMALL = 0;
/** 中号字体 */
public static final int TEXT_MEDIUM = 1;
/** 大号字体 */
public static final int TEXT_LARGE = 2;
/** 超大号字体 */
public static final int TEXT_SUPER = 3;
/** 默认字体大小 */
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
/**
*
* <p>
*
*
* </p>
*/
public static class NoteBgResources {
/** 编辑区域背景资源数组 */
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
@ -48,6 +81,7 @@ public class ResourceParser {
R.drawable.edit_red
};
/** 标题栏背景资源数组 */
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
@ -56,25 +90,56 @@ public class ResourceParser {
R.drawable.edit_title_red
};
/**
* ID
*
* @param id ID0-4
* @return ID
*/
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
/**
* ID
*
* @param id ID0-4
* @return ID
*/
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
/**
* ID
* <p>
*
* ID
* </p>
*
* @param context
* @return ID0-4
*/
public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 随机选择背景颜色
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
return BG_DEFAULT_COLOR;
}
}
/**
*
* <p>
*
*
* </p>
*/
public static class NoteItemBgResources {
/** 首项背景资源数组 */
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
@ -83,6 +148,7 @@ public class ResourceParser {
R.drawable.list_red_up
};
/** 中间项背景资源数组 */
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
@ -91,6 +157,7 @@ public class ResourceParser {
R.drawable.list_red_middle
};
/** 末项背景资源数组 */
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
@ -99,6 +166,7 @@ public class ResourceParser {
R.drawable.list_red_down,
};
/** 单项背景资源数组 */
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
@ -107,28 +175,65 @@ public class ResourceParser {
R.drawable.list_red_single
};
/**
* ID
*
* @param id ID0-4
* @return ID
*/
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
/**
* ID
*
* @param id ID0-4
* @return ID
*/
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
/**
* ID
*
* @param id ID0-4
* @return ID
*/
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
/**
* ID
*
* @param id ID0-4
* @return ID
*/
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
/**
* ID
*
* @return ID
*/
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
/**
* Widget
* <p>
* Widget
* 2x2 4x4 Widget
* </p>
*/
public static class WidgetBgResources {
/** 2x2 Widget 背景资源数组 */
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
@ -137,10 +242,17 @@ public class ResourceParser {
R.drawable.widget_2x_red,
};
/**
* 2x2 Widget ID
*
* @param id ID0-4
* @return 2x2 Widget ID
*/
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
/** 4x4 Widget 背景资源数组 */
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
@ -149,12 +261,26 @@ public class ResourceParser {
R.drawable.widget_4x_red
};
/**
* 4x4 Widget ID
*
* @param id ID0-4
* @return 4x4 Widget ID
*/
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
/**
*
* <p>
*
*
* </p>
*/
public static class TextAppearanceResources {
/** 文本外观样式资源数组 */
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
@ -162,11 +288,20 @@ public class ResourceParser {
R.style.TextAppearanceSuper
};
/**
* ID
* <p>
* ID
* </p>
*
* @param id ID0-3
* @return ID
*/
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
* HACKME: SharedPreferences ID bug
* ID
* {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
@ -174,6 +309,11 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id];
}
/**
*
*
* @return
*/
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}

@ -39,33 +39,70 @@ import net.micode.notes.tool.DataUtils;
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 {
// 当前提醒的笔记ID
private long mNoteId;
// 笔记内容摘要
private String mSnippet;
// 摘要预览最大长度
private static final int SNIPPET_PREW_MAX_LEN = 60;
// 媒体播放器,用于播放闹钟声音
MediaPlayer mPlayer;
/**
*
*
*
*
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 请求无标题窗口
requestWindowFeature(Window.FEATURE_NO_TITLE);
final Window win = getWindow();
// 添加FLAG_SHOW_WHEN_LOCKED标志使活动可以在锁屏界面上显示
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 如果屏幕当前是关闭状态,添加以下标志
if (!isScreenOn()) {
// 保持屏幕常亮
// 打开屏幕
// 允许在屏幕亮起时锁定
// 设置窗口布局包含系统装饰区域
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
}
// 获取启动此活动的Intent
Intent intent = getIntent();
try {
// 从Intent中解析出笔记ID
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 通过笔记ID获取笔记内容摘要
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 如果摘要超过最大长度,截取并添加省略号
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
@ -74,85 +111,150 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
return;
}
// 初始化媒体播放器
mPlayer = new MediaPlayer();
// 检查笔记是否在数据库中存在且可见
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 显示操作对话框
showActionDialog();
// 播放闹钟声音
playAlarmSound();
} else {
// 如果笔记不存在,直接关闭活动
finish();
}
}
/**
*
*
* @return truefalse
*/
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
/**
*
*
*
*
*/
private void playAlarmSound() {
// 获取系统默认的闹钟铃声URI
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取受静音模式影响的音频流类型
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 如果闹钟音频流受静音模式影响,使用受影响的流类型
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
// 否则使用标准闹钟音频流
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
// 设置音频源
mPlayer.setDataSource(this, url);
// 准备播放
mPlayer.prepare();
// 设置循环播放
mPlayer.setLooping(true);
// 开始播放
mPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
*
* AlertDialog
* "查看笔记"
*/
private void showActionDialog() {
// 创建AlertDialog构建器
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
// 设置对话框标题为应用名称
dialog.setTitle(R.string.app_name);
// 设置对话框内容为笔记摘要
dialog.setMessage(mSnippet);
// 添加"确定"按钮,点击事件由当前类处理
dialog.setPositiveButton(R.string.notealert_ok, this);
// 如果屏幕是开启状态,添加"查看笔记"按钮
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
// 显示对话框并设置关闭监听器
dialog.show().setOnDismissListener(this);
}
/**
*
*
*
*
* @param dialog null
* @param which ID DialogInterface.BUTTON_POSITIVE
* DialogInterface.BUTTON_NEGATIVE
*/
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 如果点击了"查看笔记"按钮(负按钮)
case DialogInterface.BUTTON_NEGATIVE:
// 创建跳转到笔记编辑活动的Intent
Intent intent = new Intent(this, NoteEditActivity.class);
// 设置动作为查看
intent.setAction(Intent.ACTION_VIEW);
// 传递笔记ID
intent.putExtra(Intent.EXTRA_UID, mNoteId);
// 启动笔记编辑活动
startActivity(intent);
break;
// 默认情况(点击"确定"按钮)
default:
break;
}
}
/**
*
*
*
*
*
* @param dialog null
*/
public void onDismiss(DialogInterface dialog) {
// 停止闹钟声音
stopAlarmSound();
// 关闭当前活动
finish();
}
/**
*
*
*
*/
private void stopAlarmSound() {
if (mPlayer != null) {
// 停止播放
mPlayer.stop();
// 释放资源
mPlayer.release();
// 将播放器对象置空
mPlayer = null;
}
}
}
}

@ -16,50 +16,91 @@
package net.micode.notes.ui;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import android.app.AlarmManager; // 系统闹钟管理器,用于设置和管理系统级闹钟
import android.app.PendingIntent; // 延迟意图,用于在指定时间触发操作
import android.content.BroadcastReceiver; // 广播接收器基类,用于接收系统广播
import android.content.ContentUris; // 用于处理内容URI的工具类
import android.content.Context; // 应用上下文,提供访问应用环境和资源的接口
import android.content.Intent; // 意图,用于组件间通信
import android.database.Cursor; // 数据库游标,用于遍历查询结果
import net.micode.notes.data.Notes; // 笔记数据相关类
import net.micode.notes.data.Notes.NoteColumns; // 笔记表列定义
/**
*
*
* BroadcastReceiver
*
*
*
* 1. BOOT_COMPLETED广
* 2.
*/
public class AlarmInitReceiver extends BroadcastReceiver {
/**
*
* ID
*/
private static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
NoteColumns.ID, // 笔记ID
NoteColumns.ALERTED_DATE // 提醒日期
};
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;
// 列索引常量,用于从查询结果中获取对应列的数据
private static final int COLUMN_ID = 0; // ID列在结果集中的索引
private static final int COLUMN_ALERTED_DATE = 1; // 提醒日期列在结果集中的索引
/**
* 广
*
* 广广
*
*
* @param context 访
* @param intent 广
*/
@Override
public void onReceive(Context context, Intent intent) {
// 获取当前系统时间,作为查询条件
long currentDate = System.currentTimeMillis();
// 查询所有提醒时间晚于当前时间的笔记
// 查询条件:提醒日期 > 当前时间 AND 笔记类型 = 普通笔记
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) },
null);
PROJECTION, // 指定查询的列
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, // 查询条件
new String[] { String.valueOf(currentDate) }, // 查询参数
null); // 排序方式null表示默认排序
// 处理查询结果
if (c != null) {
// 如果有查询结果,遍历所有符合条件的笔记
if (c.moveToFirst()) {
do {
// 获取笔记的提醒时间
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建一个指向AlarmReceiver的Intent用于在闹钟触发时接收广播
Intent sender = new Intent(context, AlarmReceiver.class);
// 将笔记ID作为URI数据附加到Intent中这样AlarmReceiver就能知道是哪个笔记的闹钟触发了
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建PendingIntent它封装了上述Intent可以在指定时间触发
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取系统闹钟服务
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 设置闹钟
// 使用RTC_WAKEUP模式即使设备处于睡眠状态也会唤醒设备并触发广播
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
} while (c.moveToNext()); // 移动到下一条记录
}
// 关闭游标,释放资源
c.close();
}
}
}
}

@ -16,15 +16,48 @@
package net.micode.notes.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver; // 广播接收器基类,用于接收系统广播
import android.content.Context; // 应用上下文,提供访问应用环境和资源的接口
import android.content.Intent; // 意图,用于组件间通信
/**
*
*
* BroadcastReceiverAlarmManager
* AlarmManager广广
* (AlarmAlertActivity)
*
*
* 1. AlarmInitReceiver
* 2. 广
* 3. AlarmReceiver广AlarmAlertActivity
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
*
* 广
* IntentAlarmAlertActivityFLAG_ACTIVITY_NEW_TASK
* 使UIActivity
*
* @param context Activity
* @param intent 广IntentID
*/
@Override
public void onReceive(Context context, Intent intent) {
// 将Intent的目标组件设置为AlarmAlertActivity
// 这样当启动Activity时就会显示闹钟提醒界面
intent.setClass(context, AlarmAlertActivity.class);
// 添加FLAG_ACTIVITY_NEW_TASK标志
// 这是必需的因为从非Activity上下文(如BroadcastReceiver)启动Activity时
// 必须指定这个标志,表示启动一个新的任务栈
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动AlarmAlertActivity显示闹钟提醒
// 原始Intent中包含了触发闹钟的笔记ID等信息AlarmAlertActivity会使用这些信息
// 来显示相应的笔记内容和提醒信息
context.startActivity(intent);
}
}
}

@ -28,6 +28,28 @@ import android.view.View;
import android.widget.FrameLayout;
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 {
private static final boolean DEFAULT_ENABLE_STATE = true;
@ -64,36 +86,55 @@ public class DateTimePicker extends FrameLayout {
private OnDateTimeChangedListener mOnDateTimeChangedListener;
/**
*
* <p>
*
* </p>
*/
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 根据选择器的变化调整日期
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
}
};
/**
*
* <p>
* 230023
* 12/
* </p>
*/
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
// 处理12小时制下的跨日情况
if (!mIs24HourView) {
// 从下午11点变为12点日期加1天
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
// 从12点变为下午11点日期减1天
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
// 切换上午/下午
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}
} else {
// 处理24小时制下的跨日情况
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
@ -104,9 +145,11 @@ public class DateTimePicker extends FrameLayout {
isDateChanged = true;
}
}
// 计算新的小时数
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
// 如果日期发生变化,更新年月日
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
@ -115,21 +158,31 @@ public class DateTimePicker extends FrameLayout {
}
};
/**
*
* <p>
* 590059
* </p>
*/
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
// 从最大值变为最小值小时加1
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
// 从最小值变为最大值小时减1
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
// 如果跨小时,更新小时和日期
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
// 更新上午/下午状态
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
@ -144,10 +197,17 @@ public class DateTimePicker extends FrameLayout {
}
};
/**
* /
* <p>
* //
* </p>
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
// 切换上午/下午,调整小时数
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
@ -158,39 +218,88 @@ public class DateTimePicker extends FrameLayout {
}
};
/**
*
* <p>
*
* </p>
*/
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,
int dayOfMonth, int hourOfDay, int minute);
}
/**
*
*
* 使
* 使24
*
* @param context
*/
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
/**
*
*
* 使
* 使24
*
* @param context
* @param date
*/
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
/**
*
*
* 使
* NumberPicker
*
* @param context
* @param date
* @param is24HourView 使24true24false12
*/
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
mDate = Calendar.getInstance();
mInitialising = true;
// 判断当前是否为下午
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
// 加载布局
inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化上午/下午选择器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
@ -198,22 +307,31 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
// 更新控件到初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
// 设置24小时制显示模式
set24HourView(is24HourView);
// set to current time
// 设置当前时间
setCurrentDate(date);
// 设置启用状态
setEnabled(isEnabled());
// set the content descriptions
// 设置内容描述
mInitialising = false;
}
/**
*
*
* NumberPicker
*
* @param enabled truefalse
*/
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
@ -227,24 +345,29 @@ public class DateTimePicker extends FrameLayout {
mIsEnabled = enabled;
}
/**
*
*
* @return truefalse
*/
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Get the current date in millis
*
* @return the current date in millis
*
*
* @return
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
* Set the current date
*
* @param date The current date in millis
*
*
* @param date
*/
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
@ -254,13 +377,13 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Set the current date
*
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*
*
* @param year
* @param month 0-11
* @param dayOfMonth 1-31
* @param hourOfDay 0-23
* @param minute 0-59
*/
public void setCurrentDate(int year, int month,
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() {
return mDate.get(Calendar.YEAR);
}
/**
* Set current year
*
* @param year The current year
*
*
* @param year
*/
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
@ -295,18 +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() {
return mDate.get(Calendar.MONTH);
}
/**
* Set current month in the year
*
* @param month The month in the year
*
*
* @param month 0-11
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
@ -318,18 +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() {
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) {
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)
* @return The current hour in 24 hour mode
* 24
*
* @return 0-23
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
/**
*
*
* 240-23121-12
*
* @return
*/
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
@ -362,9 +493,9 @@ public class DateTimePicker extends FrameLayout {
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
* 24
*
* @param hourOfDay 0-23
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
@ -372,6 +503,7 @@ public class DateTimePicker extends FrameLayout {
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) {
// 处理12小时制下的上午/下午状态
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
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() {
return mDate.get(Calendar.MINUTE);
}
/**
* Set current minute
*
*
* @param minute 0-59
*/
public void setCurrentMinute(int minute) {
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 () {
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) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
// 根据显示模式显示或隐藏上午/下午选择器
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
@ -434,30 +571,53 @@ public class DateTimePicker extends FrameLayout {
updateAmPmControl();
}
/**
*
*
* 37
* "MM.dd EEEE".
*/
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
// 设置为当前日期的前4天
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
// 生成7天的日期显示值
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
// 设置当前选中项为中间项
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}
/**
* /
*
* //
* 24/12
*/
private void updateAmPmControl() {
if (mIs24HourView) {
// 24小时制下隐藏上午/下午选择器
mAmPmSpinner.setVisibility(View.GONE);
} else {
// 12小时制下显示上午/下午选择器
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
/**
*
*
*
* 240-23121-12
*/
private void updateHourControl() {
if (mIs24HourView) {
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) {
mOnDateTimeChangedListener = callback;
}
/**
*
*
*
*/
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),

@ -29,6 +29,25 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
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 {
private Calendar mDate = Calendar.getInstance();
@ -36,52 +55,122 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
private OnDateTimeSetListener mOnDateTimeSetListener;
private DateTimePicker mDateTimePicker;
/**
*
* <p>
*
* </p>
*/
public interface OnDateTimeSetListener {
/**
*
*
* @param dialog
* @param date
*/
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
*
*
* DateTimePicker
* 使24
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 创建日期时间选择器组件
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
// 设置日期时间变更监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
// 更新内部Calendar对象
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
// 更新对话框标题
updateTitle(mDate.getTimeInMillis());
}
});
// 设置初始日期时间
mDate.setTimeInMillis(date);
// 将秒数清零
mDate.set(Calendar.SECOND, 0);
// 设置选择器当前日期
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置确定按钮
setButton(context.getString(R.string.datetime_dialog_ok), this);
// 设置取消按钮
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置判断是否使用24小时制
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 更新对话框标题
updateTitle(mDate.getTimeInMillis());
}
/**
* 使24
* <p>
* 使24
* true使24false使12
* </p>
*
* @param is24HourView true使24false使12
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
/**
*
* <p>
* OnDateTimeSet
*
* </p>
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
*
*
* mIs24HourView使24
*
* @param date
*/
private void updateTitle(long date) {
// 设置日期时间格式标志
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
// 根据是否24小时制设置相应的格式标志
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 格式化日期时间并设置为对话框标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
*
*
* OnDateTimeSet
*
* @param arg0
* @param arg1 ID
*/
public void onClick(DialogInterface arg0, int arg1) {
// 如果设置了监听器,通知监听器用户选择的日期时间
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}

@ -27,17 +27,49 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
*
* <p>
* PopupMenuButton
*
* </p>
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
public class DropdownMenu {
// 下拉按钮
private Button mButton;
// 弹出菜单
private PopupMenu mPopupMenu;
// 菜单对象
private Menu mMenu;
/**
*
*
* PopupMenu
*
* @param context
* @param button
* @param menuId ID
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置下拉图标背景
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建弹出菜单
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
// 加载菜单资源
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击监听器,点击时显示弹出菜单
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
@ -45,16 +77,32 @@ public class DropdownMenu {
});
}
/**
*
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
/**
* ID
*
* @param id ID
* @return null
*/
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
/**
*
*
* @param title
*/
public void setTitle(CharSequence 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.NoteColumns;
/**
*
* <p>
* CursorAdapterListView
*
* </p>
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*
* @see NotesListActivity
*/
public class FoldersListAdapter extends CursorAdapter {
// 数据库查询投影,指定需要从笔记表中获取的列
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
};
// 列索引常量,用于从查询结果中获取对应列的数据
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
/**
*
*
*
*
* @param context
* @param c
*/
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
/**
*
*
* FolderListItem
*
* @param context
* @param cursor
* @param parent
* @return FolderListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
}
/**
*
*
*
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
// 如果是根文件夹,显示特殊文本;否则显示文件夹名称
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName);
}
}
/**
*
*
* @param context
* @param position 0
* @return
*/
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
/**
*
* <p>
* LinearLayout
* </p>
*/
private class FolderListItem extends LinearLayout {
// 文件夹名称文本视图
private TextView mName;
/**
*
*
*
*
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 加载布局文件
inflate(context, R.layout.folder_list_item, this);
// 获取文件夹名称文本视图
mName = (TextView) findViewById(R.id.tv_folder_name);
}
/**
*
*
* @param name
*/
public void bind(String name) {
mName.setText(name);
}

@ -74,6 +74,12 @@ import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
/**
*
* <p>
* UI
* </p>
*/
private class HeadViewHolder {
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
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) {
/**
* 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();
}
/**
*
* <p>
*
* <ul>
* <li></li>
* <li>/</li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
private void initNoteScreen() {
mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId));
@ -295,6 +329,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
showAlertHeader();
}
/**
*
* <p>
*
*
* </p>
*/
private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis();
@ -318,6 +359,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
initActivityState(intent);
}
/**
*
* <p>
* ID便
* ID
* </p>
* @param outState Bundle
*/
@Override
protected void onSaveInstanceState(Bundle 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");
}
/**
*
* <p>
*
*
* </p>
* @param ev
* @return truefalse
*/
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
@ -349,6 +407,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return super.dispatchTouchEvent(ev);
}
/**
*
* <p>
*
* </p>
* @param view
* @param ev
* @return truefalse
*/
private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2];
view.getLocationOnScreen(location);
@ -363,6 +430,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true;
}
/**
*
* <p>
* UI
* SharedPreferences
* </p>
*/
private void initResources() {
mHeadViewPanel = findViewById(R.id.note_title);
mNoteHeaderHolder = new HeadViewHolder();
@ -397,6 +471,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
}
/**
*
* <p>
*
* </p>
*/
@Override
protected void onPause() {
super.onPause();
@ -406,6 +486,12 @@ public class NoteEditActivity extends Activity implements OnClickListener,
clearSettingState();
}
/**
*
* <p>
* 广2x4x
* </p>
*/
private void updateWidget() {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {
@ -425,6 +511,18 @@ public class NoteEditActivity extends Activity implements OnClickListener,
setResult(RESULT_OK, intent);
}
/**
*
* <p>
* UI
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* @param v
*/
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_set_bg_color) {
@ -452,6 +550,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
}
/**
*
* <p>
*
* 退
* </p>
*/
@Override
public void onBackPressed() {
if(clearSettingState()) {
@ -462,6 +567,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
super.onBackPressed();
}
/**
*
* <p>
*
* </p>
* @return truefalse
*/
private boolean clearSettingState() {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE);
@ -473,6 +585,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return false;
}
/**
*
* <p>
* UI
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
public void onBackgroundColorChanged() {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE);
@ -480,6 +603,19 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
}
/**
*
* <p>
*
* <ul>
* <li>使</li>
* <li></li>
* <li>/</li>
* </ul>
* </p>
* @param menu
* @return true
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (isFinishing()) {
@ -505,6 +641,24 @@ public class NoteEditActivity extends Activity implements OnClickListener,
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
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
@ -553,6 +707,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return true;
}
/**
*
* <p>
*
*
* </p>
*/
private void setReminder() {
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());
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) {
Intent intent = new Intent(Intent.ACTION_SEND);
@ -574,6 +739,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
context.startActivity(intent);
}
/**
*
* <p>
* NoteEditActivity
*
* </p>
*/
private void createNewNote() {
// Firstly, save current editing notes
saveNote();
@ -586,6 +758,13 @@ public class NoteEditActivity extends Activity implements OnClickListener,
startActivity(intent);
}
/**
*
* <p>
*
*
* </p>
*/
private void deleteCurrentNote() {
if (mWorkingNote.existInDatabase()) {
HashSet<Long> ids = new HashSet<Long>();
@ -608,10 +787,27 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mWorkingNote.markDeleted(true);
}
/**
*
* <p>
*
* </p>
* @return truefalse
*/
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
/**
*
* <p>
*
*
* 使AlarmManager
* </p>
* @param date
* @param set truefalse
*/
public void onClockAlertChanged(long date, boolean set) {
/**
* 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() {
updateWidget();
}
/**
*
* <p>
*
*
* </p>
* @param index
* @param text
*/
public void onEditTextDelete(int index, String text) {
int childCount = mEditTextList.getChildCount();
if (childCount == 1) {
@ -672,6 +883,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
edit.setSelection(length);
}
/**
*
* <p>
*
*
* </p>
* @param index
* @param text
*/
public void onEditTextEnter(int index, String text) {
/**
* 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) {
mEditTextList.removeAllViews();
String[] items = text.split("\n");
@ -708,6 +936,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
mEditTextList.setVisibility(View.VISIBLE);
}
/**
*
* <p>
*
* 使
* </p>
* @param fullText
* @param userQuery
* @return Spannable
*/
private Spannable getHighlightQueryResult(String fullText, String userQuery) {
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
if (!TextUtils.isEmpty(userQuery)) {
@ -725,6 +963,16 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return spannable;
}
/**
*
* <p>
*
*
* </p>
* @param item
* @param index
* @return
*/
private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
@ -756,6 +1004,15 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return view;
}
/**
*
* <p>
*
*
* </p>
* @param index
* @param hasText
*/
public void onTextChange(int index, boolean hasText) {
if (index >= mEditTextList.getChildCount()) {
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) {
if (newMode == TextNote.MODE_CHECK_LIST) {
switchToListMode(mNoteEditor.getText().toString());
@ -782,6 +1049,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
}
/**
*
* <p>
* WorkingNote
*
* </p>
* @return truefalse
*/
private boolean getWorkingText() {
boolean hasChecked = false;
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
@ -805,6 +1080,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return hasChecked;
}
/**
*
* <p>
*
* RESULT_OK/
* </p>
* @return truefalse
*/
private boolean saveNote() {
getWorkingText();
boolean saved = mWorkingNote.saveNote();
@ -821,6 +1104,14 @@ public class NoteEditActivity extends Activity implements OnClickListener,
return saved;
}
/**
*
* <p>
*
*
* 使10
* </p>
*/
private void sendToDesktop() {
/**
* 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) {
content = content.replace(TAG_CHECKED, "");
content = content.replace(TAG_UNCHECKED, "");
@ -863,10 +1163,25 @@ public class NoteEditActivity extends Activity implements OnClickListener,
SHORTCUT_ICON_TITLE_MAX_LEN) : content;
}
/**
* Toast
* <p>
* Toast
* </p>
* @param resId ID
*/
private void showToast(int resId) {
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) {
Toast.makeText(this, resId, duration).show();
}

@ -37,15 +37,40 @@ import net.micode.notes.R;
import java.util.HashMap;
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 {
// 日志标签
private static final String TAG = "NoteEditText";
// 当前EditText的索引
private int mIndex;
// 删除前的光标位置
private int mSelectionStartBeforeDelete;
// 电话号码URI方案
private static final String SCHEME_TEL = "tel:" ;
// HTTP URI方案
private static final String SCHEME_HTTP = "http:" ;
// 邮件URI方案
private static final String SCHEME_EMAIL = "mailto:" ;
// URI方案与上下文菜单资源ID的映射
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
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 {
/**
* 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);
/**
* 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);
/**
* Hide or show item option when text change
*
*
* @param index EditText
* @param hasText
*/
void onTextChange(int index, boolean hasText);
}
// 文本视图变更监听器
private OnTextViewChangeListener mOnTextViewChangeListener;
/**
*
*
* @param context
*/
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
}
/**
* EditText
*
* @param index EditText
*/
public void setIndex(int index) {
mIndex = index;
}
/**
*
*
* @param listener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
/**
*
*
* @param context
* @param attrs XML
*/
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
/**
*
*
* @param context
* @param attrs XML
* @param defStyle
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/**
*
*
*
*
* @param event
* @return truefalse
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 获取触摸坐标
int x = (int) event.getX();
int y = (int) event.getY();
// 减去内边距,得到内容区域的坐标
x -= getTotalPaddingLeft();
y -= getTotalPaddingTop();
// 加上滚动偏移量
x += getScrollX();
y += getScrollY();
Layout layout = getLayout();
// 获取触摸点所在的行号
int line = layout.getLineForVertical(y);
// 获取触摸点在行中的字符偏移量
int off = layout.getOffsetForHorizontal(line, x);
// 设置文本选择光标位置
Selection.setSelection(getText(), off);
break;
}
@ -121,15 +199,26 @@ public class NoteEditText extends EditText {
return super.onTouchEvent(event);
}
/**
*
*
*
*
* @param keyCode
* @param event
* @return truefalse
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
// 如果设置了监听器返回false让onKeyUp处理
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
// 记录删除前的光标位置
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
@ -138,11 +227,22 @@ public class NoteEditText extends EditText {
return super.onKeyDown(keyCode, event);
}
/**
*
*
*
*
* @param keyCode
* @param event
* @return truefalse
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
// 处理删除键
if (mOnTextViewChangeListener != null) {
// 如果光标在开头且不是第一个EditText删除当前EditText
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
@ -152,10 +252,14 @@ public class NoteEditText extends EditText {
}
break;
case KeyEvent.KEYCODE_ENTER:
// 处理回车键
if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart();
// 获取光标后的文本
String text = getText().subSequence(selectionStart, length()).toString();
// 保留光标前的文本
setText(getText().subSequence(0, selectionStart));
// 通知监听器创建新的EditText
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
@ -167,10 +271,20 @@ public class NoteEditText extends EditText {
return super.onKeyUp(keyCode, event);
}
/**
*
*
*
*
* @param focused
* @param direction
* @param previouslyFocusedRect
*/
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
if (!focused && TextUtils.isEmpty(getText())) {
// 失去焦点且文本为空
mOnTextViewChangeListener.onTextChange(mIndex, false);
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);
@ -179,18 +293,28 @@ public class NoteEditText extends EditText {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
*
*
* URL
*
* @param menu
*/
@Override
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
// 获取选区的起始和结束位置
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 获取选区内的所有URLSpan
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
int defaultResId = 0;
// 根据URL类型确定菜单项文本
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
@ -202,10 +326,11 @@ public class NoteEditText extends EditText {
defaultResId = R.string.note_link_other;
}
// 添加菜单项
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
// 点击菜单项时打开链接
urls[0].onClick(NoteEditText.this);
return true;
}

@ -25,8 +25,27 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
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 {
// 数据库查询投影,指定需要从笔记表中获取的列
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
@ -42,6 +61,7 @@ public class NoteItemData {
NoteColumns.WIDGET_TYPE,
};
// 列索引常量,用于从查询结果中获取对应列的数据
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
@ -55,27 +75,55 @@ public class NoteItemData {
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
// 笔记ID
private long mId;
// 提醒日期
private long mAlertDate;
// 背景颜色ID
private int mBgColorId;
// 创建日期
private long mCreatedDate;
// 是否有附件
private boolean mHasAttachment;
// 修改日期
private long mModifiedDate;
// 笔记数量(用于文件夹)
private int mNotesCount;
// 父文件夹ID
private long mParentId;
// 笔记摘要
private String mSnippet;
// 笔记类型
private int mType;
// 桌面小部件ID
private int mWidgetId;
// 桌面小部件类型
private int mWidgetType;
// 联系人名称(用于通话记录)
private String mName;
// 电话号码(用于通话记录)
private String mPhoneNumber;
// 是否为列表最后一项
private boolean mIsLastItem;
// 是否为列表第一项
private boolean mIsFirstItem;
// 是否为列表唯一一项
private boolean mIsOnlyOneItem;
// 是否为文件夹后跟随的单个笔记
private boolean mIsOneNoteFollowingFolder;
// 是否为文件夹后跟随的多个笔记之一
private boolean mIsMultiNotesFollowingFolder;
/**
*
*
*
*
*
* @param context 访
* @param cursor PROJECTION
*/
public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
@ -86,6 +134,7 @@ public class NoteItemData {
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
// 移除清单项的勾选标记,只保留文本内容
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
@ -93,10 +142,12 @@ public class NoteItemData {
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = "";
// 如果是通话记录笔记,获取电话号码和联系人名称
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
// 如果找不到联系人,使用电话号码作为名称
if (mName == null) {
mName = mPhoneNumber;
}
@ -106,9 +157,17 @@ public class NoteItemData {
if (mName == null) {
mName = "";
}
// 检查当前项在列表中的位置状态
checkPostion(cursor);
}
/**
*
*
*
*
* @param cursor
*/
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
@ -116,17 +175,21 @@ public class NoteItemData {
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
// 如果是普通笔记且不是第一项,检查前一项是否为文件夹
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
// 前一项是文件夹或系统文件夹
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
// 检查文件夹后是否还有更多笔记
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
} else {
mIsOneNoteFollowingFolder = true;
}
}
// 移动回原位置
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
@ -134,90 +197,203 @@ public class NoteItemData {
}
}
/**
*
*
* @return truefalse
*/
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
/**
*
*
* @return truefalse
*/
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
/**
*
*
* @return truefalse
*/
public boolean isLast() {
return mIsLastItem;
}
/**
*
*
* @return
*/
public String getCallName() {
return mName;
}
/**
*
*
* @return truefalse
*/
public boolean isFirst() {
return mIsFirstItem;
}
/**
*
*
* @return truefalse
*/
public boolean isSingle() {
return mIsOnlyOneItem;
}
/**
* ID
*
* @return ID
*/
public long getId() {
return mId;
}
/**
*
*
* @return 0
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
*
* @return
*/
public long getCreatedDate() {
return mCreatedDate;
}
/**
*
*
* @return truefalse
*/
public boolean hasAttachment() {
return mHasAttachment;
}
/**
*
*
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
*
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
*
* @return ID
*/
public long getParentId() {
return mParentId;
}
/**
*
*
* @return
*/
public int getNotesCount() {
return mNotesCount;
}
/**
* ID
*
* @return IDgetParentId
*/
public long getFolderId () {
return mParentId;
}
/**
*
*
* @return Notes.TYPE_NOTENotes.TYPE_FOLDERNotes.TYPE_SYSTEM
*/
public int getType() {
return mType;
}
/**
*
*
* @return
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* ID
*
* @return ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
*
*
* @return
*/
public String getSnippet() {
return mSnippet;
}
/**
*
*
* @return truefalse
*/
public boolean hasAlert() {
return (mAlertDate > 0);
}
/**
*
*
* @return truefalse
*/
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
*
*
* NoteItemData
*
* @param cursor TYPE_COLUMN
* @return
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}

@ -78,63 +78,119 @@ import java.io.InputStream;
import java.io.InputStreamReader;
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 {
// 笔记列表查询令牌
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
// 文件夹列表查询令牌
private static final int FOLDER_LIST_QUERY_TOKEN = 1;
// 文件夹删除菜单ID
private static final int MENU_FOLDER_DELETE = 0;
// 文件夹查看菜单ID
private static final int MENU_FOLDER_VIEW = 1;
// 文件夹重命名菜单ID
private static final int MENU_FOLDER_CHANGE_NAME = 2;
// 首次使用应用时添加介绍笔记的偏好设置键
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
/**
*
*
*
*/
private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
NOTE_LIST, // 笔记列表状态
SUB_FOLDER, // 子文件夹状态
CALL_RECORD_FOLDER // 通话记录文件夹状态
};
// 当前列表编辑状态
private ListEditState mState;
// 后台查询处理器
private BackgroundQueryHandler mBackgroundQueryHandler;
// 笔记列表适配器
private NotesListAdapter mNotesListAdapter;
// 笔记列表视图
private ListView mNotesListView;
// 新建笔记按钮
private Button mAddNewNote;
// 是否正在分发触摸事件
private boolean mDispatch;
// 触摸事件的原始Y坐标
private int mOriginY;
// 分发触摸事件的Y坐标
private int mDispatchY;
// 标题栏文本视图
private TextView mTitleBar;
// 当前文件夹ID
private long mCurrentFolderId;
// 内容解析器
private ContentResolver mContentResolver;
// 多选模式回调
private ModeCallback mModeCallBack;
private static final String TAG = "NotesListActivity";
// 笔记列表滚动速率
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
// 当前聚焦的笔记数据项
private NoteItemData mFocusNoteDataItem;
// 普通选择条件指定父文件夹ID
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
// 根文件夹选择条件:显示所有非系统笔记和有内容的通话记录文件夹
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)";
// 打开笔记的请求码
private final static int REQUEST_CODE_OPEN_NODE = 102;
// 新建笔记的请求码
private final static int REQUEST_CODE_NEW_NODE = 103;
/**
*
*
* 使
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@ -147,6 +203,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
setAppInfoFromRawRes();
}
/**
*
*
*
*
* @param requestCode
* @param resultCode RESULT_OK
* @param data Intent
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK
@ -157,6 +222,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
/**
*
*
* 使res/raw/introduction
*/
private void setAppInfoFromRawRes() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
@ -203,12 +273,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
/**
*
*
*
*/
@Override
protected void onStart() {
super.onStart();
startAsyncNotesListQuery();
}
/**
*
*
* UI
*/
private void initResources() {
mContentResolver = this.getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
@ -231,11 +311,23 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mModeCallBack = new ModeCallback();
}
/**
*
*
* ListView.MultiChoiceModeListener
*/
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
private DropdownMenu mDropDownMenu;
private ActionMode mActionMode;
private MenuItem mMoveMenu;
/**
*
*
* @param mode ActionMode
* @param menu
* @return true
*/
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.note_list_options, menu);
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),
R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) {
/**
*
*
* @param item
* @return true
*/
public boolean onMenuItemClick(MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu();
return true;
@ -269,6 +367,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true;
}
/**
*
*
*
*/
private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount();
// 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) {
// TODO Auto-generated method stub
return false;
}
/**
*
*
* @param mode ActionMode
* @param item
* @return false
*/
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
return false;
}
/**
*
*
* 退
*
* @param mode ActionMode
*/
public void onDestroyActionMode(ActionMode mode) {
mNotesListAdapter.setChoiceMode(false);
mNotesListView.setLongClickable(true);
mAddNewNote.setVisibility(View.VISIBLE);
}
/**
*
*
* ActionMode
*/
public void finishActionMode() {
mActionMode.finish();
}
/**
*
*
* @param mode ActionMode
* @param position
* @param id ID
* @param checked
*/
public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) {
mNotesListAdapter.setCheckedItem(position, checked);
@ -408,6 +545,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
};
/**
*
* <p>
* ID
* 使使
* </p>
*/
private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION;
@ -417,11 +561,35 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
}
/**
*
* <p>
* AsyncQueryHandler线
* UI线
* </p>
*/
private final class BackgroundQueryHandler extends AsyncQueryHandler {
/**
*
* @param contentResolver
*/
public BackgroundQueryHandler(ContentResolver 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
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) {
@ -441,6 +609,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
/**
*
* <p>
*
*
* </p>
* @param cursor
*/
private void showFolderListMenu(Cursor cursor) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder);
@ -462,6 +638,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.show();
}
/**
*
* <p>
* NoteEditActivityID
* </p>
*/
private void createNewNote() {
Intent intent = new Intent(this, NoteEditActivity.class);
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);
}
/**
*
* <p>
* 线
*
*
* </p>
*/
private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
@ -506,6 +696,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute();
}
/**
*
* <p>
*
*
*
* </p>
* @param folderId ID
*/
private void deleteFolder(long folderId) {
if (folderId == Notes.ID_ROOT_FOLDER) {
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) {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
@ -540,6 +746,14 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
}
/**
*
* <p>
*
*
* </p>
* @param data
*/
private void openFolder(NoteItemData data) {
mCurrentFolderId = data.getId();
startAsyncNotesListQuery();
@ -567,6 +781,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
/**
*
* <p>
*
* </p>
*/
private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
@ -574,11 +794,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
}
/**
*
* <p>
*
* </p>
* @param view
*/
private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
*
* <p>
*
* create
* </p>
* @param create truefalse
*/
private void showCreateOrModifyFolderDialog(final boolean create) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
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
public void onBackPressed() {
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) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) {
@ -707,6 +960,12 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
setResult(RESULT_OK, intent);
}
/**
*
* <p>
*
* </p>
*/
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) {
@ -760,6 +1019,19 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true;
}
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* @param menu
* @return true
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
@ -778,6 +1050,22 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true;
}
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
* @param item
* @return true
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
@ -818,12 +1106,26 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
return true;
}
/**
*
* <p>
*
* </p>
* @return true
*/
@Override
public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false);
return true;
}
/**
*
* <p>
* 线SD
*
* </p>
*/
private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() {
@ -866,19 +1168,51 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}.execute();
}
/**
*
* <p>
*
* </p>
* @return truefalse
*/
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
/**
* Activity
* <p>
* NotesPreferenceActivity
* </p>
*/
private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1);
}
/**
*
* <p>
*
* <ul>
* <li></li>
* <li></li>
* <li>/</li>
* </ul>
* </p>
*/
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) {
NoteItemData item = ((NotesListItem) view).getItemData();
if (mNotesListAdapter.isInChoiceMode()) {
@ -917,6 +1251,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}
/**
*
* <p>
*
*
* </p>
*/
private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection:
@ -935,6 +1276,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
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) {
if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData();

@ -31,18 +31,51 @@ import java.util.HashSet;
import java.util.Iterator;
/**
*
*
* CursorAdapterListView
*
*
*
* 1. NotesListItem
* 2.
* 3. ID
* 4.
*
* @see NotesListItem
* @see NoteItemData
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter";
// 应用上下文
private Context mContext;
// 记录选中状态的Mapkey为位置value为是否选中
private HashMap<Integer, Boolean> mSelectedIndex;
// 笔记总数
private int mNotesCount;
// 是否处于选择模式
private boolean mChoiceMode;
/**
*
*
* ID
*/
public static class AppWidgetAttribute {
// 桌面小部件ID
public int widgetId;
// 桌面小部件类型
public int widgetType;
};
/**
*
*
* Map
*
* @param context null
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
@ -50,11 +83,28 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0;
}
/**
*
*
* @param context
* @param cursor
* @param parent
* @return NotesListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
}
/**
*
*
*
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
@ -64,20 +114,41 @@ public class NotesListAdapter extends CursorAdapter {
}
}
/**
*
*
* @param position 0
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
}
/**
*
*
* @return truefalse
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
*
* @param mode truefalse退
*/
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mChoiceMode = mode;
}
/**
*
*
* @param checked truefalse
*/
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
@ -89,6 +160,11 @@ public class NotesListAdapter extends CursorAdapter {
}
}
/**
* ID
*
* @return IDHashSet
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
@ -105,6 +181,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
*
* @return HashSetnull
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
@ -128,6 +209,11 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/**
*
*
* @return 0
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
@ -143,11 +229,22 @@ public class NotesListAdapter extends CursorAdapter {
return count;
}
/**
*
*
* @return truefalse
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
}
/**
*
*
* @param position 0
* @return truefalse
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
@ -155,12 +252,22 @@ public class NotesListAdapter extends CursorAdapter {
return mSelectedIndex.get(position);
}
/**
*
*
*
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
}
/**
*
*
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);

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

@ -48,27 +48,85 @@ import net.micode.notes.data.Notes.NoteColumns;
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 {
/**
* SharedPreferences
*/
public static final String PREFERENCE_NAME = "notes_preferences";
/**
* SharedPreferences
*/
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";
/**
* SharedPreferences
*/
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";
/**
* Intent
*/
private static final String AUTHORITIES_FILTER_KEY = "authorities";
/**
* PreferenceCategory
*/
private PreferenceCategory mAccountCategory;
/**
* 广
*/
private GTaskReceiver mReceiver;
/**
*
*/
private Account[] mOriAccounts;
/**
*
*/
private boolean mHasAddedAccount;
/**
* Activity
* <p>
*
* <ul>
* <li>ActionBar</li>
* <li>preferences.xml</li>
* <li>广</li>
* <li></li>
* </ul>
* </p>
* @param icicle
*/
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
@ -88,6 +146,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
getListView().addHeaderView(header, null, true);
}
/**
* Activity
* <p>
* Google
* UI
* </p>
*/
@Override
protected void onResume() {
super.onResume();
@ -116,6 +181,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
refreshUI();
}
/**
* Activity
* <p>
* 广
* </p>
*/
@Override
protected void onDestroy() {
if (mReceiver != null) {
@ -124,6 +195,18 @@ public class NotesPreferenceActivity extends PreferenceActivity {
super.onDestroy();
}
/**
*
* <p>
* Preference
* Preference
* <ul>
* <li></li>
* <li></li>
* <li></li>
* </ul>
* </p>
*/
private void loadAccountPreference() {
mAccountCategory.removeAll();
@ -154,6 +237,17 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref);
}
/**
*
* <p>
*
* <ul>
* <li>"取消同步"</li>
* <li>"立即同步"</li>
* </ul>
*
* </p>
*/
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
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() {
loadAccountPreference();
loadSyncButton();
}
/**
*
* <p>
* Google
* "添加账户"
* </p>
*/
private void showSelectAccountAlertDialog() {
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() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
@ -283,11 +401,29 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.show();
}
/**
* Google
* <p>
* AccountManager"com.google"
* </p>
* @return Google
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
/**
*
* <p>
* SharedPreferences
* <ul>
* <li></li>
* <li>GTASK_IDSYNC_ID</li>
* </ul>
* </p>
* @param account
*/
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
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() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
@ -340,12 +483,28 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start();
}
/**
*
* <p>
* SharedPreferences
* </p>
* @param context
* @return
*/
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
/**
*
* <p>
* SharedPreferences
* </p>
* @param context
* @param time
*/
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
@ -354,14 +513,36 @@ public class NotesPreferenceActivity extends PreferenceActivity {
editor.commit();
}
/**
*
* <p>
* SharedPreferences
* </p>
* @param context
* @return 0
*/
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
/**
* 广
* <p>
* GTaskSyncService广UI
* </p>
*/
private class GTaskReceiver extends BroadcastReceiver {
/**
* 广
* <p>
* 广UI
* </p>
* @param context
* @param intent 广Intent
*/
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
@ -374,6 +555,15 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
/**
*
* <p>
* ActionBar
*
* </p>
* @param item
* @return truefalse
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:

Loading…
Cancel
Save