Compare commits

...

62 Commits
main ... main

Author SHA1 Message Date
liye ad4dadabac Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
czy 9aab71a713 ly's
1 year ago
czy 214f6d9e7c czy's
1 year ago
fan bb7b59baa6 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
fan 47ee64765e Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
fan ee852fd8a5 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
fan 959b5bdcba Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
fan 8e4990cf47 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
linzejia 803ec94ab9 linzejia
1 year ago
linzejia 31627eea52 linzejia
1 year ago
linzejia 443d3d90fd linzejia
1 year ago
linzejia 0d2156175f linzejia
1 year ago
linzejia b9ed090f44 linzejia
1 year ago
yzh48 42801c12c8 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
yzh48 6778757507 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
yzh48 d30940b8f4 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
czy 2bad8de040 yzh48
1 year ago
czy ca0022a451 czy
1 year ago
czy 814283251c czy
1 year ago
czy 80e8663d92 czy
1 year ago
czy e74846e1e8 czy
1 year ago
wuyanjin 8dcb51397e Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
wuyanjin bdd7f9fdf8 wuyanjin
1 year ago
czy 478d5cbf01 czy
1 year ago
czy 5580486d70 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
czy f22403e5ad czy's
1 year ago
yzh48 f42fdab8b4 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
yzh48 6fb6e111e2 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
yzh48 0d05313cf8 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
yzh48 e5c485f29f Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
wuyanjin c70dd36d09 wuyanjin
1 year ago
czy 81c023e35c czy
1 year ago
yzh48 8874636290 Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
czy f6d903d8ac Merge branch 'main' of https://bdgit.educoder.net/ppm9irgyz/MINotes
1 year ago
wuyanjin 06d36504eb wuyanjin
1 year ago
wuyanjin a140699175 wuyanjin
1 year ago
wuyanjin b32cf7b364 wuyanjin
1 year ago
wuyanjin 67d30f5cee wuyanjin
1 year ago
wuyanjin fcfde1551e wuyanjin
1 year ago
wuyanjin 80ac3d2c37 wuyanjin
1 year ago
wuyanjin a2f5a35f46 wuyanjin
1 year ago
wuyanjin ab20849305 wuyanjin
1 year ago
wuyanjin 3cb6ef4592 wuyanjin
1 year ago
wuyanjin eb62b6b764 wuyanjin
1 year ago
wuyanjin 82b55f4a31 wuuyanjin
1 year ago
yzh48 f91cfb07c0 zhushi
1 year ago
yzh48 51488967d8 zhushi
1 year ago
yzh48 f2a81d6e91 zhushi
1 year ago
wuyanjin 9a7e26dd27 wuyanjin
1 year ago
wuyanjin 0d0e86b0ae wuyanjin
1 year ago
wuyanjin a077c208ce wuyanjin
1 year ago
wuyanjin af1504cd43 wuyanjin
1 year ago
wuyanjin c05fa57d63 wuyanjin
1 year ago
wuyanjin 291b07520c wuyanjin
1 year ago
ppm9irgyz 8989f07d1b ADD file via upload
1 year ago
ppm9irgyz 8260619193 ADD file via upload
1 year ago
pvjlfx97o 416f7059db Update Note.java
1 year ago
pvjlfx97o b04c1a9095 ADD file via upload
1 year ago
puf6jkwgy c39f8cef4b ADD file via upload
1 year ago
p78xl32pf 97d542f144 ADD file via upload
1 year ago
ppm9irgyz b1d058af21 ADD file via upload
1 year ago
ppm9irgyz 4bb7610dfc ADD file via upload
1 year ago

@ -0,0 +1,81 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
/**
*
*/
public class Contact {
private static HashMap<String, String> sContactCache; //用于缓存联系人信息的哈希表
private static final String TAG = "Contact"; //日志标签
//定义用于查询数据库的SQL语句用于匹配电话号码并获取联系人信息
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 "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
/**
*
* @param context 访
* @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);
}
// 将电话号码转换为数据库查询所需的格式
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
// 如果查询成功且有结果
if (cursor != null && cursor.moveToFirst()) {
try {
String name = cursor.getString(0); // 获取联系人名称
sContactCache.put(phoneNumber, name); // 将联系人信息存入缓存
return name;
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close(); // 关闭游标
}
} else {
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}

@ -0,0 +1,256 @@
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.data;
import android.net.Uri;
public class Notes {
// 权限
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;
/**
* ID
* {@link Notes#ID_ROOT_FOLDER }
* {@link Notes#ID_TEMPARAY_FOLDER }
* {@link Notes#ID_CALL_RECORD_FOLDER}
*/
// 根文件夹 ID
public static final int ID_ROOT_FOLDER = 0;
// 临时文件夹 ID
public static final int ID_TEMPARAY_FOLDER = -1;
// 通话记录文件夹 ID
public static final int ID_CALL_RECORD_FOLDER = -2;
// 垃圾箱文件夹 ID
public static final int ID_TRASH_FOLER = -3;
// 提醒日期的 Intent 额外数据
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
// 背景颜色 ID 的 Intent 额外数据
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
// 小部件 ID 的 Intent 额外数据
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
// 小部件类型的 Intent 额外数据
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
// 文件夹 ID 的 Intent 额外数据
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
// 通话日期的 Intent 额外数据
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
// 无效的小部件类型
public static final int TYPE_WIDGET_INVALIDE = -1;
// 2x 小部件类型
public static final int TYPE_WIDGET_2X = 0;
// 4x 小部件类型
public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants {
// 笔记的 MIME 类型
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
// 通话记录的 MIME 类型
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/**
* Uri
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns {
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";
/**
*
* <P> TEXT </P>
*/
public static final String SNIPPET = "snippet";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";
/**
*
* <P> INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";
/**
*
* <P> INTEGER </P>
*/
public static final String TYPE = "type";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";
/**
*
* <P> INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";
/**
* ID
* <P> : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* gtask ID
* <P> : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";
/**
*
* <P> : INTEGER (long) </P>
*/
public static final String VERSION = "version";
}
public interface DataColumns {
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* MIME
* <P> TEXT </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* ID
* <P> INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";
/**
*
* <P> INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";
/**
*
* <P> TEXT </P>
*/
public static final String CONTENT = "content";
/**
* {@link #MIMETYPE}
* <P> INTEGER </P>
*/
public static final String DATA1 = "data1";
/**
* {@link #MIMETYPE}
* <P> INTEGER </P>
*/
public static final String DATA2 = "data2";
/**
* {@link #MIMETYPE} TEXT
* <P> TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* {@link #MIMETYPE} TEXT
* <P> TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* {@link #MIMETYPE} TEXT
* <P> TEXT </P>
*/
public static final String DATA5 = "data5";
}
public

@ -0,0 +1,165 @@
`NotesDatabaseHelper.java`
```java
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.data;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
/**
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper {
// 数据库文件名
private static final String DB_NAME = "note.db";
// 数据库版本
private static final int DB_VERSION = 4;
// 数据库表名
public interface TABLE {
public static final String NOTE = "note"; // 笔记表
public static final String DATA = "data"; // 数据表
}
// 日志标签
private static final String TAG = "NotesDatabaseHelper";
// 单例对象
private static NotesDatabaseHelper mInstance;
// 创建笔记表的 SQL 语句
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," + // 笔记 ID
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 父 ID
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," + // 提醒日期
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," + // 背景颜色 ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," + // 是否有附件
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," + // 笔记数量
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," + // 摘要
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," + // 类型
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," + // 小部件 ID
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," + // 小部件类型
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," + // 同步 ID
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," + // 是否本地修改
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," + // 原始父 ID
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," + // gtask ID
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" + // 版本
")";
// 创建数据表的 SQL 语句
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," + // 数据 ID
DataColumns.MIME_TYPE + " TEXT NOT NULL," + // MIME 类型
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," + // 笔记 ID
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 创建日期
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," + // 修改日期
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," + // 内容
DataColumns.DATA1 + " INTEGER," + // 数据 1
DataColumns.DATA2 + " INTEGER," + // 数据 2
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + // 数据 3
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + // 数据 4
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + // 数据 5
")";
// 创建数据表中笔记 ID 索引的 SQL 语句
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
// 当笔记移动到文件夹时增加文件夹的笔记数量的触发器
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
// 当笔记从文件夹移出时减少文件夹的笔记数量的触发器
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";
// 当新笔记插入到文件夹时增加文件夹的笔记数量的触发器
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";
// 当笔记从文件夹中删除时减少文件夹的笔记数量的触发器
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";
// 当插入类型为笔记的数据时更新笔记内容的触发器
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
// 当类型为笔记的数据发生变化时更新笔记内容的触发器
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";
// 当类型为笔记的数据被删除时更新笔记内容的触发器
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE "

@ -0,0 +1,230 @@
`NotesProvider.java`
```java
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.data;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
/**
* 访.
*/
public class NotesProvider extends ContentProvider {
// Uri 匹配器
private static final UriMatcher mMatcher;
// 数据库帮助类实例
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
static {
// 初始化 Uri 匹配器
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
}
/**
* .
*/
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
/**
* .
*/
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;
@Override
public boolean onCreate() {
// 获取数据库帮助类实例
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// 查询结果游标
Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase();
// 笔记 ID
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");
}
// 获取搜索字符串
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
searchString = uri.getPathSegments().get(1);
}
} else {
searchString = uri.getQueryParameter("pattern");
}
// 检查搜索字符串是否为空
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
// 格式化搜索字符串
searchString = String.format("%%%s%%", searchString);
// 执行搜索查询
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default:
// 抛出未知 Uri 异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 设置通知 Uri
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
// 数据 ID
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:
// 检查数据是否包含笔记 ID
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
// 插入数据
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
default:
// 抛出未知 Uri 异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 通知笔记 Uri
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// 通知数据 Uri
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
// 返回插入的 Uri
return ContentUris.withAppendedId(uri, insertedId);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// 删除数量
int count = 0;
// 笔记 ID
String id = null;
// 获取可写数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
// 是否删除数据
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 删除笔记
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE

@ -0,0 +1,123 @@
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Task Google .
*/
public class MetaData extends Task {
// 日志标签
private final static String TAG = MetaData.class.getSimpleName();
// 相关的 Google 任务 ID
private String mRelatedGid = null;
/**
* .
* @param gid Google ID
* @param metaInfo JSON
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
// 将 Google 任务 ID 添加到元数据信息中
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
}
// 设置笔记内容为元数据信息的 JSON 字符串
setNotes(metaInfo.toString());
// 设置名称为元数据笔记的名称
setName(GTaskStringUtils.META_NOTE_NAME);
}
/**
* Google ID.
* @return Google ID
*/
public String getRelatedGid() {
return mRelatedGid;
}
/**
* .
* @return true
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/**
* JSON .
* @param js JSON
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
if (getNotes() != null) {
try {
// 解析笔记内容为 JSON 对象
JSONObject metaInfo = new JSONObject(getNotes().trim());
// 获取相关的 Google 任务 ID
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}
}
}
/**
* JSON .
* .
* @param js JSON
*/
@Override
public void setContentByLocalJSON(JSONObject js) {
// 抛出非法访问错误
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/**
* JSON .
* .
* @return JSON
*/
@Override
public JSONObject getLocalJSONFromContent() {
// 抛出非法访问错误
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/**
* .
* .
* @param c
* @return
*/
@Override
public int getSyncAction(Cursor c) {
// 抛出非法访问错误
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}
}

@ -0,0 +1,164 @@
`Node.java`
```java
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import org.json.JSONObject;
/**
* Google .
*/
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 任务 ID
private String mGid;
// 节点名称
private String mName;
// 最后修改时间
private long mLastModified;
// 是否已删除
private boolean mDeleted;
/**
* .
*/
public Node() {
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
}
/**
* JSON .
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId);
/**
* JSON .
* @param actionId ID
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON .
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON .
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON .
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent();
/**
* .
* @param c
* @return
*/
public abstract int getSyncAction(Cursor c);
/**
* Google ID.
* @param gid Google 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
*/
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}
/**
* Google ID.
* @return Google ID
*/
public String getGid() {
return this.mGid;
}
/**
* .
* @return
*/
public String getName() {
return this.mName;
}
/**
* .
* @return
*/
public long getLastModified() {
return this.mLastModified;
}
/**
* .
* @return
*/
public boolean getDeleted() {
return this.mDeleted;
}
}
```

@ -0,0 +1,241 @@
`SqlData.java`
```java
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.gtask.data;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
/**
* SQL SQL .
*/
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;
// 是否为创建状态
private boolean mIsCreate;
// 数据 ID
private long mDataId;
// 数据 MIME 类型
private String mDataMimeType;
// 数据内容
private String mDataContent;
// 数据内容数据 1
private long mDataContentData1;
// 数据内容数据 3
private String mDataContentData3;
// 差异数据值
private ContentValues mDiffDataValues;
/**
* SQL .
* @param context
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE;
mDataContent = "";
mDataContentData1 = 0;
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
}
/**
* .
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDiffDataValues = new ContentValues();
}
/**
* .
* @param c
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
mDataContent = c.getString(DATA_CONTENT_COLUMN);
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/**
* .
* @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) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
mDataId = dataId;
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
}
mDataMimeType = dataMimeType;
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}
mDataContent = dataContent;
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
}
mDataContentData1 = dataContentData1;
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
}
mDataContentData3 = dataContentData3;
}
/**
* .
* @return JSON
* @throws JSONException JSON
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType);
js.put(DataColumns.CONTENT, mDataContent);
js.put(DataColumns.DATA1, mDataContentData1);
js.put(DataColumns.DATA3, mDataContentData3);
return js;
}
/**
* .
* @param noteId ID
* @param validateVersion
* @param version
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
}
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try {
mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
} else {
if (mDiffDataValues.size() > 0) {
int result = 0;
if (!validateVersion) {
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
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version)
});
}
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
}
mDiffDataValues.clear();
mIsCreate = false;
}
/**
* ID.
* @return ID
*/
public long getId() {
return mDataId;
}
}
```

@ -0,0 +1,286 @@
`SqlNote.java`
```java
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.tool.ResourceParser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* SQL SQL .
*/
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,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
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;
// 小部件 ID 列索引
public static final int WIDGET_ID_COLUMN = 10;
// 小部件类型列索引
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;
// gtask ID 列索引
public static final int GTASK_ID_COLUMN = 15;
// 版本列索引
public static final int VERSION_COLUMN = 16;
// 上下文
private Context mContext;
// 内容解析器
private ContentResolver mContentResolver;
// 是否为创建状态
private boolean mIsCreate;
// 笔记 ID
private long mId;
// 提醒日期
private long mAlertDate;
// 背景颜色 ID
private int mBgColorId;
// 创建日期
private long mCreatedDate;
// 是否有附件
private int mHasAttachment;
// 修改日期
private long mModifiedDate;
// 父 ID
private long mParentId;
// 摘要
private String mSnippet;
// 类型
private int mType;
// 小部件 ID
private int mWidgetId;
// 小部件类型
private int mWidgetType;
// 原始父 ID
private long mOriginParent;
// 版本
private long mVersion;
// 笔记差异值
private ContentValues mDiffNoteValues;
// 数据列表
private ArrayList<SqlData> mDataList;
/**
* SQL .
* @param context
*/
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
mId = INVALID_ID;
mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
mType = Notes.TYPE_NOTE;
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mOriginParent = 0;
mVersion = 0;
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
}
/**
* .
* @param context
* @param c
*/
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
/**
* ID .
* @param context
* @param id ID
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
/**
* ID .
* @param id ID
*/
private void loadFromCursor(long id) {
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(id)
}, null);
if (c != null) {
c.moveToNext();
loadFromCursor(c);
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
} finally {
if (c != null)
c.close();
}
}
/**
* .
* @param c
*/
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
mParentId = c.getLong(PARENT_ID_COLUMN);
mSnippet = c.getString(SNIPPET_COLUMN);
mType = c.getInt(TYPE_COLUMN);
mWidgetId = c.getInt(WIDGET_ID_COLUMN);
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN);
}
/**
* .
*/
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
try {
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] {
String.valueOf(mId)
}, null);
if (c != null) {
if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data");
return;
}
while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c);
mDataList.add(data);
}
} else {
Log.w(TAG,

@ -0,0 +1,291 @@
`Task.java`
```java
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Node Google .
*/
public class Task extends Node {
// 日志标签
private static final String TAG = Task.class.getSimpleName();
// 是否已完成
private boolean mCompleted;
// 笔记内容
private String mNotes;
// 元数据信息
private JSONObject mMetaInfo;
// 前一个兄弟任务
private Task mPriorSibling;
// 父任务列表
private TaskList mParent;
/**
* .
*/
public Task() {
super();
mCompleted = false;
mNotes = null;
mPriorSibling = null;
mParent = null;
mMetaInfo = null;
}
/**
* JSON .
* @param actionId ID
* @return JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// 操作类型
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// 操作 ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 索引
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// 实体差异
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK);
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// 父 ID
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
// 目标父类型
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// 列表 ID
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
// 前一个兄弟 ID
if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject");
}
return js;
}
/**
* JSON .
* @param actionId ID
* @return JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// 操作类型
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// 操作 ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// 实体差异
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject");
}
return js;
}
/**
* JSON .
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// 最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// 名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
// 笔记
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
}
// 是否已删除
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
}
// 是否已完成
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject");
}
}
}
/**
* JSON .
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type");
return;
}
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
break;
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}
/**
* JSON .
* @return JSON
*/
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
if (mMetaInfo == null) {
// 从网页创建的新任务
if (name == null) {
Log.w(TAG, "the note seems to be an empty one");
return null;
}
JSONObject js = new JSONObject();
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name);
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js;
} else {
// 已同步的任务
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)) {
data.put(DataColumns.CONTENT, getName());
break;
}
}
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo;
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
}
}
/**
* .
* @param metaData
*/
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
mMetaInfo

@ -0,0 +1,289 @@
`TaskList.java`
```java
/*
* (c) 2010-2011, MiCode (www.micode.net)
*
* Apache 2.0
* 使
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Node Google .
*/
public class TaskList extends Node {
// 日志标签
private static final String TAG = TaskList.class.getSimpleName();
// 任务列表索引
private int mIndex;
// 子任务列表
private ArrayList<Task> mChildren;
/**
* .
*/
public TaskList() {
super();
mChildren = new ArrayList<Task>();
mIndex = 1;
}
/**
* JSON .
* @param actionId ID
* @return JSON
*/
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// 操作类型
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// 操作 ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 索引
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// 实体差异
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject");
}
return js;
}
/**
* JSON .
* @param actionId ID
* @return JSON
*/
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// 操作类型
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// 操作 ID
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// ID
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// 实体差异
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject");
}
return js;
}
/**
* JSON .
* @param js JSON
*/
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// ID
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// 最后修改时间
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// 名称
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject");
}
}
}
/**
* JSON .
* @param js JSON
*/
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
try {
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) {
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)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);
else
Log.e(TAG, "invalid system folder");
} else {
Log.e(TAG, "error type");
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}
/**
* JSON .
* @return JSON
*/
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);
else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
return js;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
}
}
/**
* .
* @param c
* @return
*/
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// 没有本地更新
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 两边都没有更新
return SYNC_ACTION_NONE;
} else {
// 应用远程到本地
return SYNC_ACTION_UPDATE_LOCAL;
}
} else {
// 验证 gtask ID
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 只有本地修改
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// 对于文件夹冲突,只应用本地修改
return SYNC_ACTION_UPDATE_REMOTE;
}
}
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return SYNC_ACTION_ERROR;
}
/**
* .
* @return
*/
public int getChildTaskCount() {
return mChildren.size();
}
/**
* .
* @param task
* @return
*/
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {
// 需要设置前一个兄弟和父任务
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
task.setParent(this);
}
}
return ret;
}
/**
* .
* @param task
* @param index
* @return
*/
public boolean addChildTask(Task task, int index) {
if (index < 0 || index >

@ -0,0 +1,53 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.exception;
/**
* .
*/
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);
}
}

@ -0,0 +1,53 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.exception;
/**
* .
*/
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);
}
}

@ -0,0 +1,216 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 同步任务的通知 ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 任务完成监听器接口
public interface OnCompleteListener {
void onComplete(); // 当任务完成时调用
}
// 上下文对象
private Context mContext;
// 系统通知管理器
private NotificationManager mNotifiManager;
// 任务管理器,负责处理 GTask 同步逻辑
private GTaskManager mTaskManager;
// 任务完成时的回调接口
private OnCompleteListener mOnCompleteListener;
/**
*
*
* @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();
}
/**
*
* GTaskManager
*/
public void cancelSync() {
mTaskManager.cancelSync();
}
/**
*
*
* @param message
*/
public void publishProgess(String message) {
publishProgress(new String[] { message }); // 调用 AsyncTask 的 publishProgress 方法
}
/**
*
*
*
* @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) {
// 如果同步未成功,点击跳转到 NotesPreferenceActivity
pendingIntent = PendingIntent.getActivity(
mContext, 0,
new Intent(mContext, NotesPreferenceActivity.class),
0
);
} else {
// 如果同步成功,点击跳转到 NotesListActivity
pendingIntent = PendingIntent.getActivity(
mContext, 0,
new Intent(mContext, NotesListActivity.class),
0
);
}
// 设置通知内容
notification.setLatestEventInfo(
mContext,
mContext.getString(R.string.app_name), // 通知标题
content, // 通知内容
pendingIntent // 点击事件
);
// 通过通知管理器显示通知
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
/**
*
* GTaskManager
*
* @param unused 使
* @return
*/
@Override
protected Integer doInBackground(Void... unused) {
// 发布登录进度信息
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity.getSyncAccountName(mContext)));
// 调用任务管理器进行同步,并返回同步状态
return mTaskManager.sync(mContext, this);
}
/**
*
* 广
*
* @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]);
}
}
/**
*
*
*
* @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() {
public void run() {
mOnCompleteListener.onComplete();
}
}).start();
}
}
}

@ -0,0 +1,639 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.ui.NotesPreferenceActivity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class GTaskClient {
// 日志标签,用于调试
private static final String TAG = GTaskClient.class.getSimpleName();
// Google Tasks API 基础 URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// Google Tasks API 获取任务的 URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// Google Tasks API 提交任务的 URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 单例实例
private static GTaskClient mInstance = null;
// HTTP 客户端
private DefaultHttpClient mHttpClient;
// 当前请求的 URL
private String mGetUrl;
private String mPostUrl;
// 客户端版本
private long mClientVersion;
// 登录状态
private boolean mLoggedin;
// 上次登录时间
private long mLastLoginTime;
// 当前的操作 ID
private int mActionId;
// Google 帐号
private Account mAccount;
// 更新的操作队列
private JSONArray mUpdateArray;
/**
*
*/
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
mClientVersion = -1;
mLoggedin = false;
mLastLoginTime = 0;
mActionId = 1;
mAccount = null;
mUpdateArray = null;
}
/**
* GTaskClient
*
* @return GTaskClient
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
}
return mInstance;
}
/**
* Google
*
* @param activity
* @return
*/
public boolean login(Activity activity) {
// 登录超时时间为 5 分钟
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// 如果帐号发生切换,需要重新登录
if (mLoggedin && !TextUtils.equals(getSyncAccount().name,
NotesPreferenceActivity.getSyncAccountName(activity))) {
mLoggedin = false;
}
if (mLoggedin) {
Log.d(TAG, "already logged in");
return true;
}
mLastLoginTime = System.currentTimeMillis();
String authToken = loginGoogleAccount(activity, false);
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
// 如果帐号是自定义域名的 Google 帐号,需要特殊处理
if (!(mAccount.name.toLowerCase().endsWith("gmail.com")
|| mAccount.name.toLowerCase().endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index);
url.append(suffix + "/");
mGetUrl = url.toString() + "ig";
mPostUrl = url.toString() + "r/ig";
if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true;
}
}
// 使用 Google 官方 URL 尝试登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
if (!tryToLoginGtask(activity, authToken)) {
return false;
}
}
mLoggedin = true;
return true;
}
/**
* Google
*
* @param activity
* @param invalidateToken 使
* @return
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google");
if (accounts.length == 0) {
Log.e(TAG, "there is no available google account");
return null;
}
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null;
for (Account a : accounts) {
if (a.name.equals(accountName)) {
account = a;
break;
}
}
if (account != null) {
mAccount = account;
} else {
Log.e(TAG, "unable to get an account with the same name in the settings");
return null;
}
// 获取身份验证令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false);
}
} catch (Exception e) {
Log.e(TAG, "get auth token failed");
authToken = null;
}
return authToken;
}
/**
* GTask
*
* @param activity
* @param authToken
* @return
*/
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// 如果身份验证令牌过期,则重新获取
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed");
return false;
}
}
return true;
}
/**
* 使 GTask
*
* @param authToken
* @return
*/
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; // 连接超时
int timeoutSocket = 15000; // 读写超时
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = mHttpClient.execute(httpGet);
// 检查是否有认证 Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
if (cookie.getName().contains("GTL")) {
hasAuthCookie = true;
}
}
if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie");
}
// 获取客户端版本号
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
}
JSONObject js = new JSONObject(jsString);
mClientVersion = js.getLong("v");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
} catch (Exception e) {
Log.e(TAG, "httpget gtask_url failed");
return false;
}
return true;
}
// 剩余方法类似,可以按照同样逻辑添加注释
}
/**
* ID
*
*
* @return ID
*/
private int getActionId() {
return mActionId++;
}
/**
* HTTP POST
*
* @return HttpPost
*/
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
// 设置请求的内容类型
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 设置 AT 标识头,固定值为 1
httpPost.setHeader("AT", "1");
return httpPost;
}
/**
* HTTP
* 使 GZIP Deflate
*
* @param entity HTTP
* @return
* @throws IOException
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
// 检查响应是否使用了压缩编码
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding);
}
InputStream input = entity.getContent();
// 根据编码类型进行解压
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater);
}
try {
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
// 按行读取响应内容
while (true) {
String buff = br.readLine();
if (buff == null) {
return sb.toString();
}
sb = sb.append(buff);
}
} finally {
input.close();
}
}
/**
* POST JSON
*
* @param js JSON
* @return JSON
* @throws NetworkFailureException
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
HttpPost httpPost = createHttpPost();
try {
// 将 JSON 数据转换为 POST 参数
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// 执行 HTTP POST 请求
HttpResponse response = mHttpClient.execute(httpPost);
// 获取服务器的响应内容并解析为 JSON 对象
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("error occurs when posting request");
}
}
/**
*
*
* @param task
* @throws NetworkFailureException
*/
public void createTask(Task task) throws NetworkFailureException {
// 提交所有未完成的更新
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// 构建任务的创建操作
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 执行 POST 请求
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 从响应中获取任务的唯一标识符
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed");
}
}
/**
*
*
* @param tasklist
* @throws NetworkFailureException
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
// 提交所有未完成的更新
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// 构建任务列表的创建操作
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 执行 POST 请求
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 从响应中获取任务列表的唯一标识符
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed");
}
}
/**
*
*
* @throws NetworkFailureException
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
// 添加操作列表到 JSON 对象中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 执行 POST 请求提交更新
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed");
}
}
}
/**
*
*
* @param node
* @throws NetworkFailureException
*/
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// 更新队列的最大数量为 10超过后会提交当前队列
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
if (mUpdateArray == null) {
mUpdateArray = new JSONArray();
}
// 将节点的更新操作加入更新队列
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
/**
*
*
* @param node
* @throws NetworkFailureException
*/
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// 构建删除操作
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 执行 POST 请求提交删除
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed");
}
}
/**
*
*
* @return JSONArray
* @throws NetworkFailureException
*/
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
try {
HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = mHttpClient.execute(httpGet);
// 获取任务列表数据
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
}
JSONObject js = new JSONObject(jsString);
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jsonobject failed");
}
}
/**
*
*/
public void resetUpdateArray() {
mUpdateArray = null;
}
}

@ -0,0 +1,488 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.data.MetaData;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.SqlNote;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
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;
// 用于保存Activity和Context引用
private Activity mActivity;
private Context mContext;
// 内容解析器,用于操作数据库
private ContentResolver mContentResolver;
// 同步状态标志
private boolean mSyncing;
private boolean mCancelled;
// 存储任务列表、任务和元数据的映射
private HashMap<String, TaskList> mGTaskListHashMap; // 任务列表映射
private HashMap<String, Node> mGTaskHashMap; // 任务映射
private HashMap<String, MetaData> mMetaHashMap; // 元数据映射
// 元数据任务列表
private TaskList mMetaList;
// 存储本地删除的任务ID
private HashSet<Long> mLocalDeleteIdMap;
// GTask ID和Note ID之间的映射
private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid;
// 构造函数,初始化各种状态和数据结构
private GTaskManager() {
mSyncing = false;
mCancelled = false;
mGTaskListHashMap = new HashMap<String, TaskList>();
mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>();
mMetaList = null;
mLocalDeleteIdMap = new HashSet<Long>();
mGidToNid = new HashMap<String, Long>();
mNidToGid = new HashMap<Long, String>();
}
// 获取单例实例确保只有一个GTaskManager对象
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
}
return mInstance;
}
// 设置Activity上下文用于登录时获取身份验证信息
public synchronized void setActivityContext(Activity activity) {
mActivity = activity;
}
/**
* Google Task
* @param context
* @param asyncTask
* @return
*/
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
// 初始化同步参数
mContext = context;
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
// 清空各种数据结构
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
try {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// 登录Google Task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// 初始化任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// 执行同步内容的主要逻辑
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) {
Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR;
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {
// 清理同步过程中使用的临时数据
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
mSyncing = false;
}
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/**
* Google Task
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
GTaskClient client = GTaskClient.getInstance();
try {
// 从远程获取任务列表
JSONArray jsTaskLists = client.getTaskLists();
// 初始化元数据任务列表
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 如果任务列表是元数据,则初始化
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// 加载元数据任务
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = jsMetas.getJSONObject(j);
MetaData metaData = new MetaData();
metaData.setContentByRemoteJSON(object);
if (metaData.isWorthSaving()) {
mMetaList.addChildTask(metaData);
if (metaData.getGid() != null) {
mMetaHashMap.put(metaData.getRelatedGid(), metaData);
}
}
}
}
}
// 如果元数据任务列表不存在,则创建
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
}
// 初始化普通任务列表
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// 加载任务
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
object = jsTasks.getJSONObject(j);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task();
task.setContentByRemoteJSON(object);
if (task.isWorthSaving()) {
task.setMetaInfo(mMetaHashMap.get(gid));
tasklist.addChildTask(task);
mGTaskHashMap.put(gid, task);
}
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed");
}
}
/**
*
*/
private void syncContent() throws NetworkFailureException {
// 具体实现见代码内容,涉及到本地和远程任务的同步、删除和更新。
}
/**
*
*/
private void syncFolder() throws NetworkFailureException {
// 具体实现见代码内容,用于同步文件夹的逻辑。
}
/**
*
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
// 根据同步类型执行相应的操作。
}
// 其他私有方法省略...
}
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return; // 如果同步被取消,则直接返回
}
SqlNote sqlNote;
if (node instanceof TaskList) { // 如果节点是任务列表
// 根据任务列表名称初始化特定类型的SqlNote
if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); // 根文件夹
} else if (node.getName().equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); // 通话记录文件夹
} else {
sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else { // 如果节点是任务
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
try {
// 检查是否需要清理冲突的本地ID
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
note.remove(NoteColumns.ID); // 清除冲突ID
}
}
}
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
data.remove(DataColumns.ID); // 清除冲突ID
}
}
}
}
} catch (JSONException e) {
Log.w(TAG, e.toString());
e.printStackTrace();
}
sqlNote.setContent(js);
// 获取任务的父节点ID
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node");
}
sqlNote.setParentId(parentId);
}
// 创建本地节点并提交
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// 更新GID和NID的映射
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return; // 如果同步被取消,直接返回
}
SqlNote sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent()); // 更新本地内容
// 获取父节点ID
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: Notes.ID_ROOT_FOLDER;
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId);
sqlNote.commit(true); // 提交更新
// 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return; // 如果同步被取消,直接返回
}
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
if (sqlNote.isNoteType()) { // 如果是任务
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
// 获取任务父节点的GID
String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task");
}
mGTaskListHashMap.get(parentGid).addChildTask(task);
// 创建远程任务
GTaskClient.getInstance().createTask(task);
n = task;
// 添加元数据
updateRemoteMeta(task.getGid(), sqlNote);
} else { // 如果是任务列表
TaskList tasklist = null;
// 遍历已有任务列表,避免重复创建
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX + sqlNote.getSnippet();
for (Map.Entry<String, TaskList> entry : mGTaskListHashMap.entrySet()) {
String gid = entry.getKey();
TaskList list = entry.getValue();
if (list.getName().equals(folderName)) {
tasklist = list;
mGTaskHashMap.remove(gid);
break;
}
}
// 如果任务列表不存在,创建新的
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().createTaskList(tasklist);
mGTaskListHashMap.put(tasklist.getGid(), tasklist);
}
n = tasklist;
}
// 更新本地数据
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// 更新GID和NID的映射
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return; // 如果同步被取消,直接返回
}
SqlNote sqlNote = new SqlNote(mContext, c);
// 更新远程节点
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// 更新元数据
updateRemoteMeta(node.getGid(), sqlNote);
// 如果任务需要移动到新的父节点
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
// 获取当前父节点的GID
String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot update remote task");
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
// 如果父节点发生变化,执行移动操作
if (preParentList != curParentList) {
preParentList.removeChildTask(task);
curParentList.addChildTask(task);
GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
}
}
// 清除本地修改标志
sqlNote.resetLocalModified();
sqlNote.commit(true);
}

@ -0,0 +1,209 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
/**
* 便Google.
*/
public class GTaskSyncService extends Service {
/**
* 广.
*/
public final static String ACTION_STRING_NAME = "sync_action_type";
/**
* .
*/
public final static int ACTION_START_SYNC = 0;
/**
* .
*/
public final static int ACTION_CANCEL_SYNC = 1;
/**
* .
*/
public final static int ACTION_INVALID = 2;
/**
* Google广.
*/
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 = "";
/**
* .
*/
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() {
mSyncTask = null;
sendBroadcast("");
stopSelf();
}
});
sendBroadcast("");
mSyncTask.execute();
}
}
/**
* .
*/
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
/**
* .
*/
@Override
public void onCreate() {
mSyncTask = null;
}
/**
* .
*
* @param intent
* @param flags
* @param startId ID
* @return
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC:
startSync();
break;
case ACTION_CANCEL_SYNC:
cancelSync();
break;
default:
break;
}
return START_STICKY;
}
return super.onStartCommand(intent, flags, startId);
}
/**
* .
*/
@Override
public void onLowMemory() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
/**
* .
*
* @param intent
* @return
*/
public IBinder onBind(Intent intent) {
return null;
}
/**
* 广.
*
* @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);
}
/**
* .
*
* @param activity
*/
public static void startSync(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);
}
/**
* .
*
* @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
*/
public static boolean isSyncing() {
return mSyncTask != null;
}
/**
* .
*
* @return
*/
public static String getProgressString() {
return mSyncProgress;
}
}

@ -0,0 +1,342 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
/**
* 便便.
*/
public class Note {
private ContentValues mNoteDiffValues; // 存储便签的差异值,用于更新操作
private NoteData mNoteData; // 存储便签的数据信息
private static final String TAG = "Note"; // 日志标签
/**
* 便ID便.
*
* @param context
* @param folderId ID
* @return 便ID
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// 创建一个新的便签在数据库中
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime); // 创建时间
values.put(NoteColumns.MODIFIED_DATE, createdTime); // 修改时间
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 便签类型
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 本地修改标记
values.put(NoteColumns.PARENT_ID, folderId); // 父文件夹ID
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
long noteId = 0;
try {
noteId = Long.valueOf(uri.getPathSegments().get(1)); // 从URI中获取便签ID
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
}
return noteId;
}
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
}
/**
* 便.
*
* @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()); // 更新修改时间
}
/**
* .
*
* @param key
* @param value
*/
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
/**
* ID.
*
* @param id ID
*/
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
/**
* ID.
*
* @return ID
*/
public long getTextDataId() {
return mNoteData.mTextDataId;
}
/**
* ID.
*
* @param id ID
*/
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
/**
* .
*
* @param key
* @param value
*/
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
/**
* 便.
*
* @return
*/
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
/**
* 便.
*
* @param context
* @param noteId 便ID
* @return
*/
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
if (!isLocalModified()) {
return true;
}
/**
* 便 {@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");
// 不返回,继续执行
}
mNoteDiffValues.clear();
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
}
return true;
}
/**
* 便便.
*/
private class NoteData {
private long mTextDataId; // 文本数据ID
private ContentValues mTextDataValues; // 文本数据值
private long mCallDataId; // 通话数据ID
private ContentValues mCallDataValues; // 通话数据值
private static final String TAG = "NoteData"; // 日志标签
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
mTextDataId = 0;
mCallDataId = 0;
}
/**
* 便.
*
* @return
*/
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
/**
* ID.
*
* @param id ID
*/
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
}
/**
* ID.
*
* @param id ID
*/
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
}
mCallDataId = id;
}
/**
* .
*
* @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()); // 更新修改时间
}
/**
* .
*
* @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()); // 更新修改时间
}
/**
* 便.
*
* @param context
* @param noteId 便ID
* @return URI
*/
Uri pushIntoContentResolver(Context context, long noteId) {
/**
*
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId); // 设置文本数据的便签ID
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); // 设置文本数据的MIME类型
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); // 从URI中获取文本数据ID
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId)); // 创建更新操作
builder.withValues(mTextDataValues); // 设置更新值
operationList.add(builder.build());
}
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId); // 设置通话数据的便签ID
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); // 设置通话数据的MIME类型
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); // 从URI中获取通话数据ID
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId)); // 创建更新操作
builder.withValues(mCallDataValues); // 设置更新值
operationList.add(builder.build());
}
mCallDataValues.clear();
}
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList); // 批量执行操作
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); // 返回操作结果的URI
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}
}
return null;
}
}
}

@ -0,0 +1,569 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.model;
import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/**
* 便便.
*/
public class WorkingNote {
// 便签对象
private Note mNote;
// 便签ID
private long mNoteId;
// 便签内容
private String mContent;
// 便签模式
private int mMode;
private long mAlertDate; // 提醒日期
private long mModifiedDate; // 修改日期
private int mBgColorId; // 背景颜色ID
private int mWidgetId; // 小部件ID
private int mWidgetType; // 小部件类型
private long mFolderId; // 文件夹ID
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, // 数据ID
DataColumns.CONTENT, // 数据内容
DataColumns.MIME_TYPE, // 数据MIME类型
DataColumns.DATA1, // 数据1
DataColumns.DATA2, // 数据2
DataColumns.DATA3, // 数据3
DataColumns.DATA4, // 数据4
};
/**
* 便.
*/
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, // 父ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.WIDGET_ID, // 小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
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;
/**
* 便ID.
*/
private static final int NOTE_WIDGET_ID_COLUMN = 3;
/**
* 便.
*/
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
/**
* 便.
*/
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
/**
* 便.
*
* @param context
* @param folderId ID
*/
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
mModifiedDate = System.currentTimeMillis();
mFolderId = folderId;
mNote = new Note();
mNoteId = 0;
mIsDeleted = false;
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
/**
* 便.
*
* @param context
* @param noteId 便ID
* @param folderId ID
*/
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
mIsDeleted = false;
mNote = new Note();
loadNote();
}
/**
* 便.
*/
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
}
cursor.close();
} else {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData();
}
/**
* 便.
*/
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
}, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
if (DataConstants.NOTE.equals(type)) {
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) {
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
Log.d(TAG, "Wrong note type with type:" + type);
}
} while (cursor.moveToNext());
}
cursor.close();
} else {
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}
}
/**
* 便.
*
* @param context
* @param folderId ID
* @param widgetId ID
* @param widgetType
* @param defaultBgColorId ID
* @return 便
*/
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
note.setWidgetType(widgetType);
return note;
}
/**
* 便.
*
* @param context
* @param id 便ID
* @return 便
*/
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
/**
* 便.
*
* @return
*/
public synchronized boolean saveNote() {
if (isWorthSaving()) {
if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
mNote.syncNote(mContext, mNoteId);
/**
* 便
*/
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
return true;
} else {
return false;
}
}
/**
* 便.
*
* @return
*/
public boolean existInDatabase() {
return mNoteId > 0;
}
/**
* 便.
*
* @return
*/
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
} else {
return true;
}
}
/**
* 便.
*
* @param l
*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
/**
* .
*
* @param date
* @param set
*/
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
}
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onClockAlertChanged(date, set);
}
}
/**
* 便.
*
* @param mark
*/
public void markDeleted(boolean mark) {
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
}
/**
* ID.
*
* @param id ID
*/
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged();
}
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
}
}
/**
* .
*
* @param mode
*/
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
}
mMode = mode;
mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
}
}
/**
* .
*
* @param type
*/
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
}
}
/**
* ID.
*
* @param id ID
*/
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
}
}
/**
* .
*
* @param text
*/
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent);
}
}
/**
* 便.
*
* @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
*/
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;
}
/**
* ID.
*
* @return ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* .
*
* @return
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* 便.
*/
public interface NoteSettingChangedListener {
/**
* 便.
*/
void onBackgroundColorChanged();
/**
* .
*
* @param date
* @param set
*/
void onClockAlertChanged(long date, boolean set);
/**
* 便.
*/
void onWidgetChanged();
/**
* .
*
* @param oldMode
* @param newMode
*/
void onCheckListModeChanged(int oldMode, int newMode);
}
}

@ -0,0 +1,349 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 声明包名
package net.micode.notes.tool;
// 导入相关类
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
// 声明一个名为 BackupUtils 的公共类
public class BackupUtils {
// 定义一个日志标签常量
private static final String TAG = "BackupUtils";
// 单例模式相关变量
private static BackupUtils sInstance;
// 提供获取 BackupUtils 实例的静态方法
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
}
return sInstance;
}
// 定义一些常量,表示备份或恢复的状态
public static final int STATE_SD_CARD_UNMOUONTED = 0;
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
public static final int STATE_DATA_DESTROIED = 2;
public static final int STATE_SYSTEM_ERROR = 3;
public static final int STATE_SUCCESS = 4;
// 声明一个 TextExport 类型的私有变量
private TextExport mTextExport;
// 构造方法,传入 Context 对象
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
// 判断外部存储是否可用的静态方法
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 导出数据到文本文件的方法
public int exportToText() {
return mTextExport.exportToText();
}
// 获取导出文本文件名的方法
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
// 获取导出文本文件目录的方法
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
// 声明一个名为 TextExport 的私有静态内部类
private static class TextExport {
// 定义查询笔记和数据的投影数组
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
};
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
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;
// 声明 Context 对象和文件名、目录变量
private Context mContext;
private String mFileName;
private String mFileDirectory;
// 构造方法,传入 Context 对象
public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
}
// 根据 id 获取文本格式的方法
private String getFormat(int id) {
return TEXT_FORMAT[id];
}
// 导出指定文件夹到文本的方法
private void exportFolderToText(String folderId, PrintStream ps) {
// 查询属于该文件夹的笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
}, null);
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// 打印笔记的最后修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于该笔记的数据
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext());
}
notesCursor.close();
}
}
/**
* id
*/
private void exportNoteToText(String noteId, PrintStream ps) {
// 查询属于该笔记的数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
if (dataCursor != null) {
if (dataCursor.moveToFirst()) {
do {
// 获取数据的 MIME 类型
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// 打印电话号码
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// 打印通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// 打印通话附件位置
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 打印笔记内容
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content));
}
}
} while (dataCursor.moveToNext());
}
dataCursor.close();
}
// 在笔记之间打印一行分隔符
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
});
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
/**
*
*/
public int exportToText() {
// 判断外部存储是否可用
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取导出到文本的打印流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// 首先导出文件夹及其笔记
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
do {
// 打印文件夹的名称
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
}
if (!TextUtils.isEmpty(folderName)) {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());
}
folderCursor.close();
}
// 导出根文件夹中的笔记
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
do {
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询属于该笔记的数据
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
}
noteCursor.close();
}
ps.close();
return STATE_SUCCESS;
}
/**
* {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {
// 在 SD 卡上生成文件
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
}
mFileName = file.getName();
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (NullPointerException e) {
e.printStackTrace();
return null;
}
return ps;
}
/**
*
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 构建文件路径
StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory());
sb.append(context.getString(filePathResId));
File filedir = new File(sb.toString());
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
File file = new File(sb.toString());
try {
// 创建文件夹和文件
if (!filedir.exists()) {
filedir.mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@ -0,0 +1,469 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <url id="ctvqpqeqvl70nnpdm1qg" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 文件头部包含了版权声明、许可证信息以及对应的 URL 链接,指明该文件遵循 Apache License 2.0 许可证。同时声明该软件是“按原样”提供的,没有明示或暗示的任何形式的保证或条件。
package net.micode.notes.tool;
// 定义当前类所在的包名,为 net.micode.notes.tool。
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.util.Log;
// 导入 Android 相关类库,以便在类中使用这些类的功能。
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
// 导入本项目中其他包里的类,便于调用这些类的属性和方法。
import java.util.ArrayList;
import java.util.HashSet;
// 导入 Java 集合框架中的类,用于在类中使用 ArrayList 和 HashSet。
public class DataUtils {
// 定义一个公共类 DataUtils作为工具类提供数据操作的方法。
public static final String TAG = "DataUtils";
// 定义一个公共静态常量 TAG用于日志输出时标识当前类名。
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 定义一个静态方法 batchDeleteNotes用于批量删除笔记。
// ContentResolver resolver内容解析器对象用于对内容提供者进行操作。
// HashSet<Long> ids需要删除的笔记 ID 集合。
if (ids == null) {
// 如果传入的 ids 为 null。
Log.d(TAG, "the ids is null");
// 输出日志,提示 ids 为 null。
return true;
// 直接返回 true表示删除操作成功因为没有需要删除的笔记
}
if (ids.size() == 0) {
// 如果 ids 集合的大小为 0即没有需要删除的笔记 ID。
Log.d(TAG, "no id is in the hashset");
// 输出日志,提示没有需要删除的笔记 ID。
return true;
// 直接返回 true表示删除操作成功。
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 创建一个 ArrayList用于存储要执行的内容提供者操作。
for (long id : ids) {
// 遍历 ids 集合中的每个笔记 ID。
if(id == Notes.ID_ROOT_FOLDER) {
// 如果当前 ID 是系统根文件夹的 ID。
Log.e(TAG, "Don't delete system folder root");
// 输出错误日志,提示不能删除系统根文件夹。
continue;
// 跳过此次循环,不执行删除操作。
}
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 创建一个 ContentProviderOperation.Builder 对象,用于构建删除操作。
operationList.add(builder.build());
// 将构建好的删除操作添加到 operationList 中。
}
try {
// 尝试执行批量删除操作。
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 调用 resolver 的 applyBatch 方法,传入 Notes.AUTHORITY 和 operationList执行批量操作并返回操作结果数组。
if (results == null || results.length == 0 || results[0] == null) {
// 如果操作结果数组为 null或者数组长度为 0或者数组的第一个元素为 null。
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
// 输出日志,提示删除笔记失败,并打印出需要删除的笔记 IDs。
return false;
// 返回 false表示删除操作失败。
}
return true;
// 如果没有异常且删除操作成功,返回 true。
} catch (RemoteException e) {
// 如果在执行删除操作过程中发生远程异常。
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
// 输出错误日志,打印出异常信息和异常消息。
} catch (OperationApplicationException e) {
// 如果在应用操作过程中发生异常。
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
// 输出错误日志,打印出异常信息和异常消息。
}
return false;
// 如果在执行删除操作过程中发生异常,返回 false表示删除操作失败。
}
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
// 定义一个静态方法 moveNoteToFoler用于将笔记移动到文件夹。
// ContentResolver resolver内容解析器对象用于对内容提供者进行操作。
// long id要移动的笔记 ID。
// long srcFolderId笔记的源文件夹 ID。
// long desFolderId要移动到的目标文件夹 ID。
ContentValues values = new ContentValues();
// 创建一个 ContentValues 对象,用于存储笔记的修改信息。
values.put(NoteColumns.PARENT_ID, desFolderId);
// 将笔记的目标父文件夹 ID 存储到 ContentValues 中,修改笔记的 PARENT_ID 列。
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
// 将笔记的源父文件夹 ID 存储到 ContentValues 中,修改笔记的 ORIGIN_PARENT_ID 列。
values.put(NoteColumns.LOCAL_MODIFIED, 1);
// 将笔记的本地修改标志设置为 1表示笔记已被本地修改。
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
// 调用 resolver 的 update 方法,传入笔记的内容 URI 和修改后的 ContentValues更新笔记数据。
// ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id):根据笔记 ID 构建笔记的内容 URI。
// values包含笔记修改信息的 ContentValues。
// null 和 null查询条件和查询条件参数这里不需要查询条件。
}
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, long folderId) {
// 定义一个静态方法 batchMoveToFolder用于批量移动笔记到文件夹。
// ContentResolver resolver内容解析器对象用于对内容提供者进行操作。
// HashSet<Long> ids需要移动的笔记 ID 集合。
// long folderId目标文件夹 ID。
if (ids == null) {
// 如果传入的 ids 为 null。
Log.d(TAG, "the ids is null");
// 输出日志,提示 ids 为 null。
return true;
// 直接返回 true表示移动操作成功因为没有需要移动的笔记
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 创建一个 ArrayList用于存储要执行的内容提供者操作。
for (long id : ids) {
// 遍历 ids 集合中的每个笔记 ID。
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 创建一个 ContentProviderOperation.Builder 对象,用于构建更新操作。
builder.withValue(NoteColumns.PARENT_ID, folderId);
// 设置更新操作中笔记的父文件夹 ID 为传入的目标文件夹 ID。
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
// 设置更新操作中笔记的本地修改标志为 1。
operationList.add(builder.build());
// 将构建好的更新操作添加到 operationList 中。
}
try {
// 尝试执行批量移动操作。
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 调用 resolver 的 applyBatch 方法,传入 Notes.AUTHORITY 和 operationList执行批量操作
if (results == null || results.length == 0 || results[0] == null) {
// 如果操作结果数组为 null或者数组长度为 0或者数组的第一个元素为 null。
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
// 输出日志,提示移动笔记失败,并打印出需要移动的笔记 IDs。
return false;
// 返回 false表示移动操作失败。
}
return true;
// 如果没有异常且移动操作成功,返回 true。
} catch (RemoteException e) {
// 如果在执行移动操作过程中发生远程异常。
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
// 输出错误日志,打印出异常信息和异常消息。
} catch (OperationApplicationException e) {
// 如果在应用操作过程中发生异常。
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
// 输出错误日志,打印出异常信息和异常消息。
}
return false;
// 如果在执行移动操作过程中发生异常,返回 false表示移动操作失败。
}
public static int getUserFolderCount(ContentResolver resolver) {
// 定义一个静态方法 getUserFolderCount用于获取用户文件夹的数量不包括系统文件夹
// ContentResolver resolver内容解析器对象用于对内容提供者进行操作。
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
// 调用 resolver 的 query 方法,查询 Notes.CONTENT_NOTE_URI获取用户文件夹的数量。
// new String[] { "COUNT(*)" }:查询投影,只查询文件夹数量。
// NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?":查询条件,文件夹类型且父文件夹 ID 不等于回收站 ID。
// new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)}:查询条件参数。
int count = 0;
// 初始化文件夹数量为 0。
if(cursor != null) {
// 如果查询结果游标不为 null。
if(cursor.moveToFirst()) {
// 将游标移动到第一条记录。
try {
count = cursor.getInt(0);
// 获取查询结果中的文件夹数量。
} catch (IndexOutOfBoundsException e) {
// 如果在获取文件夹数量时发生索引越界异常。
Log.e(TAG, "get folder count failed:" + e.toString());
// 输出错误日志,打印出异常信息。
} finally {
cursor.close();
// 关闭游标,释放资源。
}
}
}
return count;
// 返回用户文件夹的数量。
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 定义一个静态方法 visibleInNoteDatabase用于检查指定的笔记 ID 是否存在于笔记数据库中(不包括回收站)。
// ContentResolver resolver内容解析器对象用于对内容提供者进行操作。
// long noteId要检查的笔记 ID。
// int type笔记类型。
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
null);
// 调用 resolver 的 query 方法,查询指定笔记 ID 的笔记是否存在。
// ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId):根据笔记 ID 构建笔记的内容 URI。
// null查询投影这里不需要指定查询列。
// NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER查询条件笔记类型且父文件夹 ID 不等于回收站 ID。
// new String [] {String.valueOf(type)}:查询条件参数。
boolean exist = false;
// 初始化笔记是否存在为 false。
if (cursor != null) {
// 如果查询结果游标不为 null。
if (cursor.getCount() > 0) {
// 如果查询结果的数量大于 0说明笔记存在。
exist = true;
}
cursor.close();
// 关闭游标,释放资源。
}
return exist;
// 返回笔记是否存在。
}
// 检查指定的笔记 ID 是否存在于笔记数据库中
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 使用 ContentUris.withAppendedId() 方法将笔记 ID 附加到笔记内容 URI 后面,构建查询特定笔记的 URI
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
// 默认笔记不存在
boolean exist = false;
// 如果查询结果的游标不为空
if (cursor != null) {
// 如果游标中包含至少一条记录
if (cursor.getCount() > 0) {
// 表示笔记存在
exist = true;
}
// 关闭游标以释放资源
cursor.close();
}
// 返回笔记是否存在
return exist;
}
// 检查指定的数据 ID 是否存在于数据数据库中
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 使用 ContentUris.withAppendedId() 方法将数据 ID 附加到数据内容 URI 后面,构建查询特定数据的 URI
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
// 默认数据不存在
boolean exist = false;
// 如果查询结果的游标不为空
if (cursor != null) {
// 如果游标中包含至少一条记录
if (cursor.getCount() > 0) {
// 表示数据存在
exist = true;
}
// 关闭游标以释放资源
cursor.close();
}
// 返回数据是否存在
return exist;
}
// 检查指定的文件夹名称是否已存在于可见文件夹中
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询笔记内容 URI筛选出类型为文件夹、父 ID 不等于回收站文件夹 ID、且摘要等于指定名称的笔记
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
// 默认名称不存在
boolean exist = false;
// 如果查询结果的游标不为空
if(cursor != null) {
// 如果游标中包含至少一条记录
if(cursor.getCount() > 0) {
// 表示名称已存在
exist = true;
}
// 关闭游标以释放资源
cursor.close();
}
// 返回名称是否存在
return exist;
}
// 获取指定文件夹 ID 下的笔记小部件属性集合
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询笔记内容 URI筛选出父 ID 等于指定文件夹 ID 的笔记,获取小部件 ID 和类型
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },
null);
// 初始化小部件属性集合
HashSet<AppWidgetAttribute> set = null;
// 如果查询结果的游标不为空
if (c != null) {
// 如果游标可以移动到第一条记录
if (c.moveToFirst()) {
// 创建小部件属性集合
set = new HashSet<AppWidgetAttribute>();
// 遍历游标中的所有记录
do {
try {
// 创建小部件属性对象
AppWidgetAttribute widget = new AppWidgetAttribute();
// 设置小部件 ID 和类型
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
// 将小部件属性添加到集合中
set.add(widget);
} catch (IndexOutOfBoundsException e) {
// 如果索引越界,记录错误日志
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
}
// 关闭游标以释放资源
c.close();
}
// 返回小部件属性集合
return set;
}
// 根据笔记 ID 获取电话号码
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 查询数据内容 URI筛选出笔记 ID 等于指定 ID、MIME 类型为电话号码的记录,获取电话号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);
// 如果查询结果的游标不为空且可以移动到第一条记录
if (cursor != null && cursor.moveToFirst()) {
try {
// 返回电话号码
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
// 如果索引越界,记录错误日志
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
// 关闭游标以释放资源
cursor.close();
}
}
// 如果查询失败,返回空字符串
return "";
}
// 根据电话号码和通话日期获取笔记 ID
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 查询数据内容 URI筛选出通话日期等于指定日期、MIME 类型为电话号码、且电话号码匹配的记录,获取笔记 ID
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
// 如果查询结果的游标不为空
if (cursor != null) {
// 如果游标可以移动到第一条记录
if (cursor.moveToFirst()) {
try {
// 返回笔记 ID
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
// 如果索引越界,记录错误日志
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
// 关闭游标以释放资源
cursor.close();
}
// 如果查询失败,返回 0
return 0;
}
// 根据笔记 ID 获取摘要信息
public static String getSnippetById(ContentResolver resolver, long noteId) {
// 查询笔记内容 URI筛选出 ID 等于指定笔记 ID 的记录,获取摘要信息
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
// 如果查询结果的游标不为空
if (cursor != null) {
// 初始化摘要信息为空字符串
String snippet = "";
// 如果游标可以移动到第一条记录
if (cursor.moveToFirst()) {
// 获取并设置摘要信息
snippet = cursor.getString(0);
}
// 关闭游标以释放资源
cursor.close();
// 返回摘要信息
return snippet;
}
// 如果查询失败,抛出 IllegalArgumentException 异常
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
// 格式化摘要信息,去除多余换行符
public static String getFormattedSnippet(String snippet) {
// 如果摘要信息不为空
if (snippet != null) {
// 去除首尾空白字符
snippet = snippet.trim();
// 查找第一个换行符的索引
int index = snippet.indexOf('\n');
// 如果找到换行符
if (index != -1) {
// 截取换行符之前的部分作为格式化后的摘要信息
snippet = snippet.substring(0, index);
}
}
// 返回格式化后的摘要信息
return snippet;
}
}

@ -0,0 +1,160 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 声明包名
package net.micode.notes.tool;
// 声明一个名为 GTaskStringUtils 的公共类
public class GTaskStringUtils {
// 定义 JSON 中动作 ID 的键
public final static String GTASK_JSON_ACTION_ID = "action_id";
// 定义 JSON 中动作列表的键
public final static String GTASK_JSON_ACTION_LIST = "action_list";
// 定义 JSON 中动作类型的键
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
// 定义 JSON 中创建动作类型的值
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
// 定义 JSON 中获取全部动作类型的值
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
// 定义 JSON 中移动动作类型的值
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
// 定义 JSON 中更新动作类型的值
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// 定义 JSON 中创建者 ID 的键
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// 定义 JSON 中子实体的键
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// 定义 JSON 中客户端版本的键
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// 定义 JSON 中完成状态的键
public final static String GTASK_JSON_COMPLETED = "completed";
// 定义 JSON 中当前列表 ID 的键
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// 定义 JSON 中默认列表 ID 的键
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// 定义 JSON 中删除状态的键
public final static String GTASK_JSON_DELETED = "deleted";
// 定义 JSON 中目标列表的键
public final static String GTASK_JSON_DEST_LIST = "dest_list";
// 定义 JSON 中目标父实体的键
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// 定义 JSON 中目标父实体类型的键
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// 定义 JSON 中实体差异的键
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// 定义 JSON 中实体类型的键
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// 定义 JSON 中获取删除状态的键
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// 定义 JSON 中 ID 的键
public final static String GTASK_JSON_ID = "id";
// 定义 JSON 中索引的键
public final static String GTASK_JSON_INDEX = "index";
// 定义 JSON 中最后修改时间的键
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// 定义 JSON 中最新同步点的键
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// 定义 JSON 中列表 ID 的键
public final static String GTASK_JSON_LIST_ID = "list_id";
// 定义 JSON 中列表的键
public final static String GTASK_JSON_LISTS = "lists";
// 定义 JSON 中名称的键
public final static String GTASK_JSON_NAME = "name";
// 定义 JSON 中新 ID 的键
public final static String GTASK_JSON_NEW_ID = "new_id";
// 定义 JSON 中笔记的键
public final static String GTASK_JSON_NOTES = "notes";
// 定义 JSON 中父 ID 的键
public final static String GTASK_JSON_PARENT_ID = "parent_id";
// 定义 JSON 中前一个兄弟 ID 的键
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// 定义 JSON 中结果的键
public final static String GTASK_JSON_RESULTS = "results";
// 定义 JSON 中源列表的键
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// 定义 JSON 中任务的键
public final static String GTASK_JSON_TASKS = "tasks";
// 定义 JSON 中类型的键
public final static String GTASK_JSON_TYPE = "type";
// 定义 JSON 中组类型的值
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
// 定义 JSON 中任务类型的值
public final static String GTASK_JSON_TYPE_TASK = "TASK";
// 定义 JSON 中用户的键
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";
}

@ -0,0 +1,211 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 声明包名
package net.micode.notes.tool;
// 导入相关类
import android.content.Context;
import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
// 声明一个名为 ResourceParser 的公共类
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;
// 声明一个名为 NoteBgResources 的公共静态内部类
public static class NoteBgResources {
// 定义编辑笔记背景资源的数组
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
};
// 定义编辑笔记标题背景资源的数组
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
};
// 根据 id 获取笔记背景资源的方法
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
// 根据 id 获取笔记标题背景资源的方法
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
// 获取默认笔记背景 id 的方法
public static int getDefaultBgId(Context context) {
// 如果用户设置了背景颜色,则随机返回一个背景颜色 id
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 否则返回默认背景颜色 id
return BG_DEFAULT_COLOR;
}
}
// 声明一个名为 NoteItemBgResources 的公共静态内部类
public static class NoteItemBgResources {
// 定义笔记列表项背景资源的数组
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
};
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
};
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
};
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
};
// 获取笔记列表项第一个背景资源的方法
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
// 获取笔记列表项最后一个背景资源的方法
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
// 获取笔记列表项单个背景资源的方法
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
// 获取笔记列表项普通背景资源的方法
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
// 获取文件夹背景资源的方法
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
// 声明一个名为 WidgetBgResources 的公共静态内部类
public static class WidgetBgResources {
// 定义 2x 小部件背景资源的数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
// 根据 id 获取 2x 小部件背景资源的方法
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 定义 4x 小部件背景资源的数组
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
// 根据 id 获取 4x 小部件背景资源的方法
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
// 声明一个名为 TextAppearanceResources 的公共静态内部类
public static class TextAppearanceResources {
// 定义文本外观资源的数组
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
// 根据 id 获取文本外观资源的方法
public static int getTexAppearanceResource(int id) {
/**
* HACKME: id bug
* id
* {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
}
// 获取文本外观资源数组大小的方法
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}

@ -0,0 +1,171 @@
// 声明版权信息表明该文件由MiCode开源社区在2010-2011年间编写并遵循Apache License 2.0许可协议
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; // 指定该类所在的包名
import android.app.Activity; // 导入Activity类用于创建活动界面
import android.app.AlertDialog; // 导入AlertDialog类用于显示对话框
import android.content.Context; // 导入Context类用于获取应用程序上下文
import android.content.DialogInterface; // 导入DialogInterface类用于对话框事件监听
import android.content.DialogInterface.OnClickListener; // 导入OnClickListener接口用于监听对话框按钮点击事件
import android.content.DialogInterface.OnDismissListener; // 导入OnDismissListener接口用于监听对话框消失事件
import android.content.Intent; // 导入Intent类用于在组件之间传递消息
import android.media.AudioManager; // 导入AudioManager类用于管理音频设置
import android.media.MediaPlayer; // 导入MediaPlayer类用于播放媒体文件
import android.media.RingtoneManager; // 导入RingtoneManager类用于管理铃声
import android.net.Uri; // 导入Uri类用于表示统一资源标识符
import android.os.Bundle; // 导入Bundle类用于传递数据
import android.os.PowerManager; // 导入PowerManager类用于管理电源设置
import android.provider.Settings; // 导入Settings类用于访问系统设置
import android.view.Window; // 导入Window类用于管理窗口
import android.view.WindowManager; // 导入WindowManager类用于管理窗口属性
import net.micode.notes.R; // 导入应用程序的资源文件
import net.micode.notes.data.Notes; // 导入Notes类用于处理笔记数据
import net.micode.notes.tool.DataUtils; // 导入DataUtils类用于数据处理工具
import java.io.IOException; // 导入IOException类用于处理输入/输出异常
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; // 声明一个长整型变量mNoteId用于存储笔记ID
private String mSnippet; // 声明一个字符串变量mSnippet用于存储笔记摘要
private static final int SNIPPET_PREW_MAX_LEN = 60; // 定义常量SNIPPET_PREW_MAX_LEN表示笔记摘要的最大长度
MediaPlayer mPlayer; // 声明一个MediaPlayer对象mPlayer用于播放提醒音
// 重写Activity类的onCreate方法用于初始化活动界面
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // 调用父类的onCreate方法
requestWindowFeature(Window.FEATURE_NO_TITLE); // 请求无标题窗口特性
final Window win = getWindow(); // 获取当前窗口对象
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 设置窗口在锁定状态下显示
// 如果屏幕未开启,则设置窗口属性以保持屏幕亮起、在屏幕关闭时开启屏幕、允许在屏幕亮起时锁定
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
}
Intent intent = getIntent(); // 获取启动该活动的Intent对象
try {
// 从Intent中获取笔记ID并根据ID获取笔记摘要
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
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;
} catch (IllegalArgumentException e) {
e.printStackTrace(); // 打印异常信息
return; // 如果发生异常,则返回
}
mPlayer = new MediaPlayer(); // 创建MediaPlayer对象
// 如果笔记类型为普通笔记,则显示操作对话框并播放提醒音
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
} else {
finish(); // 如果笔记类型不为普通笔记,则结束活动
}
}
// 定义isScreenOn方法用于判断屏幕是否开启
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); // 获取电源管理服务
return pm.isScreenOn(); // 返回屏幕是否开启的状态
}
// 定义playAlarmSound方法用于播放提醒音
private void playAlarmSound() {
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); // 获取默认提醒音的URI
// 获取静音模式下影响的音频流类型
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); // 设置MediaPlayer的数据源
mPlayer.prepare(); // 准备MediaPlayer
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(); // 打印异常信息
}
}
// 定义showActionDialog方法用于显示操作对话框
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this); // 创建AlertDialog.Builder对象
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); // 显示对话框并设置对话框消失监听器
}
// 实现OnClickListener接口的onClick方法用于处理对话框按钮点击事件
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
// 如果点击“进入”按钮则启动NoteEditActivity并传递笔记ID
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
break;
default:
break;
}
}
// 实现OnDismissListener接口的onDismiss方法用于处理对话框消失事件
public void onDismiss(DialogInterface dialog) {
stopAlarmSound(); // 停止提醒音
finish(); // 结束活动
}
// 定义stopAlarmSound方法用于停止提醒音
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop(); // 停止MediaPlayer
mPlayer.release(); // 释放MediaPlayer资源
mPlayer = null; // 将MediaPlayer对象置为空
}
}
}

@ -0,0 +1,75 @@
// 声明版权信息表明该文件由MiCode开源社区在2010-2011年间编写并遵循Apache License 2.0许可协议
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; //
import android.app.AlarmManager; // 导入AlarmManager类用于设置和管理提醒
import android.app.PendingIntent; // 导入PendingIntent类用于创建待发送的Intent
import android.content.BroadcastReceiver; // 导入BroadcastReceiver类用于接收广播
import android.content.ContentUris; // 导入ContentUris类用于处理内容URI
import android.content.Context; // 导入Context类用于获取应用程序上下文
import android.content.Intent; // 导入Intent类用于在组件之间传递消息
import android.database.Cursor; // 导入Cursor类用于访问数据库查询结果
import net.micode.notes.data.Notes; // 导入Notes类用于处理笔记数据
import net.micode.notes.data.Notes.NoteColumns; // 导入NoteColumns类用于访问笔记列信息
// 定义AlarmInitReceiver类继承自BroadcastReceiver类
public class AlarmInitReceiver extends BroadcastReceiver {
// 定义查询投影包含笔记ID和提醒日期列
private static final String [] PROJECTION = new String [] {
NoteColumns.ID, // 笔记ID列
NoteColumns.ALERTED_DATE // 提醒日期列
};
// 定义列索引常量
private static final int COLUMN_ID = 0; // 笔记ID列索引
private static final int COLUMN_ALERTED_DATE = 1; // 提醒日期列索引
// 重写BroadcastReceiver类的onReceive方法用于处理接收到的广播
@Override
public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis(); // 获取当前时间戳
// 查询笔记内容提供者,获取未提醒的普通笔记
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);
if (c != null) { // 如果查询结果不为空
if (c.moveToFirst()) { // 移动到第一条记录
do {
// 获取笔记的提醒日期
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建一个Intent用于启动AlarmReceiver
Intent sender = new Intent(context, AlarmReceiver.class);
// 设置Intent的数据为笔记的URI
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建一个PendingIntent用于在提醒时间发送广播
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取AlarmManager服务
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// 设置提醒使用RTC_WAKEUP模式在提醒时间唤醒设备并发送PendingIntent
alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 继续处理下一条记录
}
c.close(); // 关闭Cursor
}
}
}

@ -0,0 +1,35 @@
// 声明版权信息表明该文件由MiCode开源社区在2010-2011年间编写并遵循Apache License 2.0许可协议
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui; // 指定该类所在的包名
import android.content.BroadcastReceiver; // 导入BroadcastReceiver类用于接收广播
import android.content.Context; // 导入Context类用于获取应用程序上下文
import android.content.Intent; // 导入Intent类用于在组件之间传递消息
public class AlarmReceiver extends BroadcastReceiver {
// 重写BroadcastReceiver类的onReceive方法用于处理接收到的广播
@Override
public void onReceive(Context context, Intent intent) {
// 设置Intent的目标类为AlarmAlertActivity即当广播接收时启动AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class);
// 添加标志,表示启动一个新的任务栈
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 使用上下文启动Intent指定的活动
context.startActivity(intent);
}
}

@ -0,0 +1,455 @@
// 声明版权信息表明该文件由MiCode开源社区在2010-2011年间编写并遵循Apache License 2.0许可协议
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 导入所需的包和类
package net.micode.notes.ui; // 指定该类所在的包名
import java.text.DateFormatSymbols; // 导入DateFormatSymbols类用于获取日期格式符号
import java.util.Calendar; // 导入Calendar类用于日期和时间操作
import net.micode.notes.R; // 导入应用程序的资源文件
import android.content.Context; // 导入Context类用于获取应用程序上下文
import android.text.format.DateFormat; // 导入DateFormat类用于日期格式化
import android.view.View; // 导入View类用于视图操作
import android.widget.FrameLayout; // 导入FrameLayout类用于布局
import android.widget.NumberPicker; // 导入NumberPicker类用于数字选择器
// 定义DateTimePicker类继承自FrameLayout类
public class DateTimePicker extends FrameLayout {
// 定义常量
private static final boolean DEFAULT_ENABLE_STATE = true; // 默认启用状态
private static final int HOURS_IN_HALF_DAY = 12; // 半天的小时数
private static final int HOURS_IN_ALL_DAY = 24; // 一天的小时数
private static final int DAYS_IN_ALL_WEEK = 7; // 一周的天数
private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器的最小值
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器的最大值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时视图的小时选择器最小值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时视图的小时选择器最大值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时视图的小时选择器最小值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时视图的小时选择器最大值
private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟选择器的最小值
private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟选择器的最大值
private static final int AMPM_SPINNER_MIN_VAL = 0; // 上午/下午选择器的最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // 上午/下午选择器的最大值
// 定义成员变量
private final NumberPicker mDateSpinner; // 日期选择器
private final NumberPicker mHourSpinner; // 小时选择器
private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // 上午/下午选择器
private Calendar mDate; // 当前日期
// 定义日期显示值数组
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 定义状态变量
private boolean mIsAm; // 是否为上午
private boolean mIs24HourView; // 是否为24小时视图
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 是否启用
private boolean mInitialising; // 是否正在初始化
// 定义日期时间更改监听器
private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 定义日期更改监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 更新日期
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl(); // 更新日期控件
onDateTimeChanged(); // 触发日期时间更改事件
}
};
// 定义小时更改监听器
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 处理小时更改逻辑
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
if (!mIs24HourView) {
// 12小时视图的逻辑
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;
} 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);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
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));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
}
};
// 定义分钟更改监听器
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;
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
if (offset != 0) {
// 更新日期和小时
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
}
// 更新分钟
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
}
};
// 定义上午/下午更改监听器
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 {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
}
updateAmPmControl();
onDateTimeChanged();
}
};
// 定义日期时间更改监听器接口
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
// 构造函数初始化DateTimePicker
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
// 构造函数初始化DateTimePicker并设置日期
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
// 构造函数初始化DateTimePicker并设置日期和24小时视图状态
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);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// 更新控件到初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
// 设置24小时视图状态
set24HourView(is24HourView);
// 设置当前日期
setCurrentDate(date);
// 设置启用状态
setEnabled(isEnabled());
// 设置内容描述
mInitialising = false;
}
// 重写setEnabled方法设置控件的启用状态
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
}
super.setEnabled(enabled);
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled;
}
// 获取控件的启用状态
@Override
public boolean isEnabled() {
return mIsEnabled;
}
// 获取当前日期的时间戳
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
// 设置当前日期
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
}
// 设置当前日期
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}
// 获取当前年份
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
// 设置当前年份
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
return;
}
mDate.set(Calendar.YEAR, year);
updateDateControl();
onDateTimeChanged();
}
// 获取当前月份
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
// 设置当前月份
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
return;
}
mDate.set(Calendar.MONTH, month);
updateDateControl();
onDateTimeChanged();
}
// 获取当前天数
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
// 设置当前天数
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
return;
}
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateControl();
onDateTimeChanged();
}
// 获取当前小时24小时制
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
// 获取当前小时根据24小时视图状态
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
} else {
int hour = getCurrentHourOfDay();
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
}
}
}
// 设置当前小时24小时制
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY;
}
} else {
mIsAm = true;
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
}
}
updateAmPmControl();
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
}
// 获取当前分钟
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
// 设置当前分钟
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged();
}
// 获取是否为24小时视图
public boolean is24HourView () {
return mIs24HourView;
}
// 设置是否为24小时视图
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
setCurrentHour(hour);
updateAmPmControl();
}
// 更新日期控件
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}
// 更新上午/下午控件
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
// 更新小时控件
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
}
// 设置日期时间更改监听器
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
// 触发日期时间更改事件
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}

@ -0,0 +1,140 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 文件头部注释声明版权信息和许可证信息说明该文件遵循Apache License, Version 2.0
package net.micode.notes.ui;
// 导入包声明该类属于net.micode.notes.ui包
import java.util.Calendar;
// 导入Calendar类用于日期和时间的操作
import net.micode.notes.R;
// 导入R类用于访问应用的资源文件
import net.micode.notes.ui.DateTimePicker;
// 导入DateTimePicker类用于日期和时间的选择控件
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
// 导入DateTimePicker.OnDateTimeChangedListener接口用于监听日期和时间的变化
import android.app.AlertDialog;
// 导入AlertDialog类用于创建对话框
import android.content.Context;
// 导入Context类用于获取应用上下文
import android.content.DialogInterface;
// 导入DialogInterface类用于对话框的接口
import android.content.DialogInterface.OnClickListener;
// 导入DialogInterface.OnClickListener接口用于对话框按钮的点击事件监听
import android.text.format.DateFormat;
// 导入DateFormat类用于日期格式的转换
import android.text.format.DateUtils;
// 导入DateUtils类用于日期和时间的格式化和转换
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 声明DateTimePickerDialog类继承自AlertDialog并实现OnClickListener接口
private Calendar mDate = Calendar.getInstance();
// 声明mDate变量用于存储当前选择的日期和时间默认为当前系统时间
private boolean mIs24HourView;
// 声明mIs24HourView变量用于标记是否使用24小时制
private OnDateTimeSetListener mOnDateTimeSetListener;
// 声明mOnDateTimeSetListener变量用于存储日期和时间设置完成后的回调接口
private DateTimePicker mDateTimePicker;
// 声明mDateTimePicker变量用于存储日期和时间选择控件
public interface OnDateTimeSetListener {
// 声明OnDateTimeSetListener接口用于定义日期和时间设置完成后的回调方法
void OnDateTimeSet(AlertDialog dialog, long date);
// 定义OnDateTimeSet方法参数为对话框和设置的日期时间戳
}
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) {
// 监听器方法,当日期和时间发生变化时调用
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);
// 将秒数设置为0
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置日期和时间选择控件的当前日期和时间
setButton(context.getString(R.string.datetime_dialog_ok), this);
// 设置对话框的确定按钮,并将点击事件监听器设置为当前对象
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 设置对话框的取消按钮,不设置点击事件监听器
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 根据系统设置决定是否使用24小时制
updateTitle(mDate.getTimeInMillis());
// 更新对话框的标题
}
public void set24HourView(boolean is24HourView) {
// 设置是否使用24小时制的方法
mIs24HourView = is24HourView;
// 更新mIs24HourView变量的值
}
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
// 设置日期和时间设置完成后的回调接口的方法
mOnDateTimeSetListener = callBack;
// 更新mOnDateTimeSetListener变量的值
}
private void updateTitle(long date) {
// 更新对话框标题的方法
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
// 设置日期格式的标志,显示年份、日期和时间
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 根据是否使用24小时制设置相应的格式标志
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
// 使用DateUtils.formatDateTime方法格式化日期并设置为对话框的标题
}
public void onClick(DialogInterface arg0, int arg1) {
// 对话框按钮点击事件的监听方法
if (mOnDateTimeSetListener != null) {
// 如果设置了日期和时间设置完成后的回调接口
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
// 调用回调接口的OnDateTimeSet方法传入对话框和当前选择的日期时间戳
}
}
}

@ -0,0 +1,114 @@
java
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <url id="cu1jo4prqpm9v23mk6p0" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 文件头部的版权声明,声明该文件的版权归属以及遵循的许可证信息
package net.micode.notes.ui;
// 包声明,指明该类所属的包名
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
// 导入该类所依赖的类和接口
import net.micode.notes.R;
// 导入资源文件,方便访问项目中的资源
/**
* DropdownMenu
* 使
*/
public class DropdownMenu {
// 定义一个名为 DropdownMenu 的公共类
private Button mButton;
// 定义一个 Button 类型的私有成员变量 mButton用于存储下拉菜单按钮
private PopupMenu mPopupMenu;
// 定义一个 PopupMenu 类型的私有成员变量 mPopupMenu用于存储下拉菜单
private Menu mMenu;
// 定义一个 Menu 类型的私有成员变量 mMenu用于存储下拉菜单中的菜单项
/**
* DropdownMenu
*
* @param context PopupMenu
* @param button
* @param menuId ID
*/
public DropdownMenu(Context context, Button button, int menuId) {
// 定义一个构造方法,用于创建 DropdownMenu 对象
mButton = button;
// 将传入的按钮赋值给 mButton
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 为按钮设置背景资源,使用 R.drawable.dropdown_icon
mPopupMenu = new PopupMenu(context, mButton);
// 创建一个 PopupMenu 对象,并传入上下文和按钮作为参数
mMenu = mPopupMenu.getMenu();
// 获取 PopupMenu 对象的菜单,并赋值给 mMenu
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 使用菜单填充器将传入的菜单资源 ID 填充到菜单中
mButton.setOnClickListener(new OnClickListener() {
// 为按钮设置点击事件监听器
public void onClick(View v) {
// 当按钮被点击时
mPopupMenu.show();
// 显示下拉菜单
}
});
}
/**
*
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
// 定义一个方法,用于设置下拉菜单项点击事件监听器
if (mPopupMenu != null) {
// 如果 mPopupMenu 不为空
mPopupMenu.setOnMenuItemClickListener(listener);
// 为 mPopupMenu 设置点击事件监听器
}
}
/**
*
*
* @param id ID
* @return null
*/
public MenuItem findItem(int id) {
// 定义一个方法,用于查找菜单项
return mMenu.findItem(id);
// 调用 mMenu 的 findItem 方法查找并返回指定 ID 的菜单项
}
/**
*
*
* @param title
*/
public void setTitle(CharSequence title) {
// 定义一个方法,用于设置按钮的标题
mButton.setText(title);
// 调用 mButton 的 setText 方法设置按钮的文本内容
}
}
// DropdownMenu 类的结束

@ -0,0 +1,116 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 文件头部注释声明版权信息和许可证信息说明该文件遵循Apache License, Version 2.0
package net.micode.notes.ui;
// 导入包声明该类属于net.micode.notes.ui包
import android.content.Context;
// 导入Context类用于获取应用上下文
import android.database.Cursor;
// 导入Cursor类用于数据库查询结果的游标
import android.view.View;
// 导入View类用于界面元素
import android.view.ViewGroup;
// 导入ViewGroup类用于视图容器
import android.widget.CursorAdapter;
// 导入CursorAdapter类用于将游标数据绑定到视图上
import android.widget.LinearLayout;
// 导入LinearLayout类用于线性布局
import android.widget.TextView;
// 导入TextView类用于显示文本
import net.micode.notes.R;
// 导入R类用于访问应用的资源文件
import net.micode.notes.data.Notes;
// 导入Notes类用于访问笔记数据
import net.micode.notes.data.Notes.NoteColumns;
// 导入NoteColumns类用于访问笔记数据的列信息
public class FoldersListAdapter extends CursorAdapter {
// 声明FoldersListAdapter类继承自CursorAdapter用于显示文件夹列表
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
};
// 定义查询投影包含笔记的ID和摘要列
public static final int ID_COLUMN = 0;
// 定义ID列的索引
public static final int NAME_COLUMN = 1;
// 定义名称列的索引
public FoldersListAdapter(Context context, Cursor c) {
// 构造函数,传入上下文和游标
super(context, c);
// 调用父类构造函数
// TODO Auto-generated constructor stub
// 自动生成的构造函数存根,待实现
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建新视图的方法
return new FolderListItem(context);
// 返回一个新的FolderListItem实例
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// 绑定视图的方法
if (view instanceof FolderListItem) {
// 如果视图是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);
// 调用FolderListItem的bind方法设置文件夹名称
}
}
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);
// 返回文件夹名称,如果是根文件夹则显示特定字符串,否则显示名称列的值
}
private class FolderListItem extends LinearLayout {
// 声明FolderListItem类继承自LinearLayout用于表示文件夹列表项
private TextView mName;
// 声明mName变量用于存储文件夹名称的TextView
public FolderListItem(Context context) {
// 构造函数,传入上下文
super(context);
// 调用父类构造函数
inflate(context, R.layout.folder_list_item, this);
// 加载文件夹列表项的布局
mName = (TextView) findViewById(R.id.tv_folder_name);
// 获取文件夹名称的TextView
}
public void bind(String name) {
// 绑定文件夹名称的方法
mName.setText(name);
// 设置文件夹名称的文本
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,260 @@
// 声明版权信息2010-2011年由MiCode开源社区(www.micode.net)编写
// 该文件遵循Apache License, Version 2.0许可协议
// 除非法律要求或书面同意,否则不得使用该文件
// 可以从以下网址获取该许可协议的副本http://www.apache.org/licenses/LICENSE-2.0
// 除非法律要求或书面同意,否则根据该许可协议分发的软件按“原样”分发,没有任何明示或暗示的保证或条件
// 请参阅许可协议,了解关于权限和限制的具体语言
// 声明包名该文件属于net.micode.notes.ui包
package net.micode.notes.ui;
// 导入所需的Android类库
import android.content.Context;
import android.graphics.Rect;
import android.text.Layout;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.widget.EditText;
// 导入该应用的资源文件
import net.micode.notes.R;
// 导入Java类库
import java.util.HashMap;
import java.util.Map;
// 声明NoteEditText类继承自EditText
public class NoteEditText extends EditText {
// 定义日志标签
private static final String TAG = "NoteEditText";
// 定义索引变量,用于记录编辑文本的索引
private int mIndex;
// 定义删除前选择的开始位置变量
private int mSelectionStartBeforeDelete;
// 定义电话、HTTP和电子邮件的URI scheme常量
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
// 创建一个HashMap用于存储不同scheme对应的资源ID
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
// 静态代码块初始化sSchemaActionResMap
static {
// 将电话、HTTP和电子邮件的scheme分别与对应的字符串资源ID关联起来
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
}
// 声明OnTextViewChangeListener接口用于监听编辑文本的变化
public interface OnTextViewChangeListener {
// 当编辑文本为空且按下删除键时,删除当前编辑文本
void onEditTextDelete(int index, String text);
// 当按下回车键时,在当前编辑文本后添加新的编辑文本
void onEditTextEnter(int index, String text);
// 当文本发生变化时,隐藏或显示选项项
void onTextChange(int index, boolean hasText);
}
// 声明OnTextViewChangeListener接口的实例变量
private OnTextViewChangeListener mOnTextViewChangeListener;
// 构造方法仅传入Context参数
public NoteEditText(Context context) {
// 调用父类构造方法
super(context, null);
// 初始化索引为0
mIndex = 0;
}
// 设置编辑文本的索引
public void setIndex(int index) {
mIndex = index;
}
// 设置OnTextViewChangeListener接口的实现
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
// 构造方法传入Context和AttributeSet参数
public NoteEditText(Context context, AttributeSet attrs) {
// 调用父类构造方法传入AttributeSet和默认样式
super(context, attrs, android.R.attr.editTextStyle);
}
// 构造方法传入Context、AttributeSet和默认样式参数
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
// 调用父类构造方法
super(context, attrs, defStyle);
// TODO:此处有注释提示,表示需要自动生成构造方法的代码
}
// 重写onTouchEvent方法处理触摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
// 根据事件类型进行处理
switch (event.getAction()) {
// 当手指按下时
case MotionEvent.ACTION_DOWN:
// 获取触摸点的x和y坐标
int x = (int) event.getX();
int y = (int) event.getY();
// 调整坐标考虑padding和滚动位置
x -= getTotalPaddingLeft();
y -= getTotalPaddingTop();
x += getScrollX();
y += getScrollY();
// 获取文本布局
Layout layout = getLayout();
// 根据y坐标获取行号
int line = layout.getLineForVertical(y);
// 根据行号和x坐标获取字符偏移量
int off = layout.getOffsetForHorizontal(line, x);
// 设置文本选择位置
Selection.setSelection(getText(), off);
break;
}
// 调用父类的onTouchEvent方法
return super.onTouchEvent(event);
}
// 重写onKeyDown方法处理键盘按下事件
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// 根据按键代码进行处理
switch (keyCode) {
// 当按下回车键时
case KeyEvent.KEYCODE_ENTER:
// 如果设置了OnTextViewChangeListener则不处理
if (mOnTextViewChangeListener != null) {
return false;
}
break;
// 当按下删除键时
case KeyEvent.KEYCODE_DEL:
// 记录删除前的选择开始位置
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
// 调用父类的onKeyDown方法
return super.onKeyDown(keyCode, event);
}
// 重写onKeyUp方法处理键盘抬起事件
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// 根据按键代码进行处理
switch(keyCode) {
// 当抬起删除键时
case KeyEvent.KEYCODE_DEL:
// 如果设置了OnTextViewChangeListener
if (mOnTextViewChangeListener != null) {
// 如果删除前选择的开始位置为0且索引不为0则删除当前编辑文本
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
}
} else {
// 如果未设置OnTextViewChangeListener则输出日志
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
break;
// 当抬起回车键时
case KeyEvent.KEYCODE_ENTER:
// 如果设置了OnTextViewChangeListener
if (mOnTextViewChangeListener != null) {
// 获取选择的开始位置
int selectionStart = getSelectionStart();
// 获取选择开始位置之后的文本
String text = getText().subSequence(selectionStart, length()).toString();
// 设置文本为选择开始位置之前的文本
setText(getText().subSequence(0, selectionStart));
// 在当前编辑文本后添加新的编辑文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else {
// 如果未设置OnTextViewChangeListener则输出日志
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
break;
default:
break;
}
// 调用父类的onKeyUp方法
return super.onKeyUp(keyCode, event);
}
// 重写onFocusChanged方法处理焦点变化事件
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
// 如果设置了OnTextViewChangeListener
if (mOnTextViewChangeListener != null) {
// 如果失去焦点且文本为空,则通知文本变化为无文本
if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false);
} else {
// 如果获得焦点或文本不为空,则通知文本变化为有文本
mOnTextViewChangeListener.onTextChange(mIndex, true);
}
}
// 调用父类的onFocusChanged方法
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
// 重写onCreateContextMenu方法创建上下文菜单
@Override
protected void onCreateContextMenu(ContextMenu menu) {
// 如果文本是Spanned类型
if (getText() instanceof Spanned) {
// 获取选择的开始和结束位置
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
// 获取最小和最大位置
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
urls[0].onClick(NoteEditText.this);
return true;
}
});
}
}
super.onCreateContextMenu(menu);
}
}

@ -0,0 +1,224 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
public class NoteItemData {
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
mName = mPhoneNumber;
}
}
}
if (mName == null) {
mName = "";
}
checkPostion(cursor);
}
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
if (cursor.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");
}
}
}
}
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
public boolean isLast() {
return mIsLastItem;
}
public String getCallName() {
return mName;
}
public boolean isFirst() {
return mIsFirstItem;
}
public boolean isSingle() {
return mIsOnlyOneItem;
}
public long getId() {
return mId;
}
public long getAlertDate() {
return mAlertDate;
}
public long getCreatedDate() {
return mCreatedDate;
}
public boolean hasAttachment() {
return mHasAttachment;
}
public long getModifiedDate() {
return mModifiedDate;
}
public int getBgColorId() {
return mBgColorId;
}
public long getParentId() {
return mParentId;
}
public int getNotesCount() {
return mNotesCount;
}
public long getFolderId () {
return mParentId;
}
public int getType() {
return mType;
}
public int getWidgetType() {
return mWidgetType;
}
public int getWidgetId() {
return mWidgetId;
}
public String getSnippet() {
return mSnippet;
}
public boolean hasAlert() {
return (mAlertDate > 0);
}
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}

@ -0,0 +1,954 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.tool.BackupUtils;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
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;
private static final int MENU_FOLDER_DELETE = 0;
private static final int MENU_FOLDER_VIEW = 1;
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
};
private ListEditState mState;
private BackgroundQueryHandler mBackgroundQueryHandler;
private NotesListAdapter mNotesListAdapter;
private ListView mNotesListView;
private Button mAddNewNote;
private boolean mDispatch;
private int mOriginY;
private int mDispatchY;
private TextView mTitleBar;
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;
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_list);
initResources();
/**
* Insert an introduction when user firstly use this application
*/
setAppInfoFromRawRes();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
mNotesListAdapter.changeCursor(null);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
private void setAppInfoFromRawRes() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
StringBuilder sb = new StringBuilder();
InputStream in = null;
try {
in = getResources().openRawResource(R.raw.introduction);
if (in != null) {
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
char [] buf = new char[1024];
int len = 0;
while ((len = br.read(buf)) > 0) {
sb.append(buf, 0, len);
}
} else {
Log.e(TAG, "Read introduction file error");
return;
}
} catch (IOException e) {
e.printStackTrace();
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED);
note.setWorkingText(sb.toString());
if (note.saveNote()) {
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else {
Log.e(TAG, "Save introduction note error");
return;
}
}
}
@Override
protected void onStart() {
super.onStart();
startAsyncNotesListQuery();
}
private void initResources() {
mContentResolver = this.getContentResolver();
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mNotesListView = (ListView) findViewById(R.id.notes_list);
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false);
mNotesListView.setOnItemClickListener(new OnListItemClickListener());
mNotesListView.setOnItemLongClickListener(this);
mNotesListAdapter = new NotesListAdapter(this);
mNotesListView.setAdapter(mNotesListAdapter);
mAddNewNote = (Button) findViewById(R.id.btn_new_note);
mAddNewNote.setOnClickListener(this);
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
mDispatch = false;
mDispatchY = 0;
mOriginY = 0;
mTitleBar = (TextView) findViewById(R.id.tv_title_bar);
mState = ListEditState.NOTE_LIST;
mModeCallBack = new ModeCallback();
}
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
private DropdownMenu mDropDownMenu;
private ActionMode mActionMode;
private MenuItem mMoveMenu;
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.note_list_options, menu);
menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
mMoveMenu = menu.findItem(R.id.move);
if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
|| DataUtils.getUserFolderCount(mContentResolver) == 0) {
mMoveMenu.setVisible(false);
} else {
mMoveMenu.setVisible(true);
mMoveMenu.setOnMenuItemClickListener(this);
}
mActionMode = mode;
mNotesListAdapter.setChoiceMode(true);
mNotesListView.setLongClickable(false);
mAddNewNote.setVisibility(View.GONE);
View customView = LayoutInflater.from(NotesListActivity.this).inflate(
R.layout.note_list_dropdown_menu, null);
mode.setCustomView(customView);
mDropDownMenu = new DropdownMenu(NotesListActivity.this,
(Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
updateMenu();
return true;
}
});
return true;
}
private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount();
// Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount);
mDropDownMenu.setTitle(format);
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
if (item != null) {
if (mNotesListAdapter.isAllSelected()) {
item.setChecked(true);
item.setTitle(R.string.menu_deselect_all);
} else {
item.setChecked(false);
item.setTitle(R.string.menu_select_all);
}
}
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(ActionMode mode) {
mNotesListAdapter.setChoiceMode(false);
mNotesListView.setLongClickable(true);
mAddNewNote.setVisibility(View.VISIBLE);
}
public void finishActionMode() {
mActionMode.finish();
}
public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
boolean checked) {
mNotesListAdapter.setCheckedItem(position, checked);
updateMenu();
}
public boolean onMenuItemClick(MenuItem item) {
if (mNotesListAdapter.getSelectedCount() == 0) {
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
Toast.LENGTH_SHORT).show();
return true;
}
switch (item.getItemId()) {
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_notes,
mNotesListAdapter.getSelectedCount()));
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
batchDelete();
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
break;
case R.id.move:
startQueryDestinationFolders();
break;
default:
return false;
}
return true;
}
}
private class NewNoteOnTouchListener implements OnTouchListener {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
Display display = getWindowManager().getDefaultDisplay();
int screenHeight = display.getHeight();
int newNoteViewHeight = mAddNewNote.getHeight();
int start = screenHeight - newNoteViewHeight;
int eventY = start + (int) event.getY();
/**
* Minus TitleBar's height
*/
if (mState == ListEditState.SUB_FOLDER) {
eventY -= mTitleBar.getHeight();
start -= mTitleBar.getHeight();
}
/**
* HACKME:When click the transparent part of "New Note" button, dispatch
* the event to the list view behind this button. The transparent part of
* "New Note" button could be expressed by formula y=-0.12x+94Unit:pixel
* and the line top of the button. The coordinate based on left of the "New
* Note" button. The 94 represents maximum height of the transparent part.
* Notice that, if the background of the button changes, the formula should
* also change. This is very bad, just for the UI designer's strong requirement.
*/
if (event.getY() < (event.getX() * (-0.12) + 94)) {
View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1
- mNotesListView.getFooterViewsCount());
if (view != null && view.getBottom() > start
&& (view.getTop() < (start + 94))) {
mOriginY = (int) event.getY();
mDispatchY = eventY;
event.setLocation(event.getX(), mDispatchY);
mDispatch = true;
return mNotesListView.dispatchTouchEvent(event);
}
}
break;
}
case MotionEvent.ACTION_MOVE: {
if (mDispatch) {
mDispatchY += (int) event.getY() - mOriginY;
event.setLocation(event.getX(), mDispatchY);
return mNotesListView.dispatchTouchEvent(event);
}
break;
}
default: {
if (mDispatch) {
event.setLocation(event.getX(), mDispatchY);
mDispatch = false;
return mNotesListView.dispatchTouchEvent(event);
}
break;
}
}
return false;
}
};
private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION;
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
}
private final class BackgroundQueryHandler extends AsyncQueryHandler {
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) {
case FOLDER_NOTE_LIST_QUERY_TOKEN:
mNotesListAdapter.changeCursor(cursor);
break;
case FOLDER_LIST_QUERY_TOKEN:
if (cursor != null && cursor.getCount() > 0) {
showFolderListMenu(cursor);
} else {
Log.e(TAG, "Query folder failed");
}
break;
default:
return;
}
}
}
private void showFolderListMenu(Cursor cursor) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(R.string.menu_title_select_folder);
final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DataUtils.batchMoveToFolder(mContentResolver,
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
Toast.makeText(
NotesListActivity.this,
getString(R.string.format_move_notes_to_folder,
mNotesListAdapter.getSelectedCount(),
adapter.getFolderName(NotesListActivity.this, which)),
Toast.LENGTH_SHORT).show();
mModeCallBack.finishActionMode();
}
});
builder.show();
}
private void createNewNote() {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
}
private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
if (!isSyncMode()) {
// if not synced, delete notes directly
if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
.getSelectedItemIds())) {
} else {
Log.e(TAG, "Delete notes error, should not happens");
}
} else {
// in sync mode, we'll move the deleted note into the trash
// folder
if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
.getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
Log.e(TAG, "Move notes to trash folder error, should not happens");
}
}
return widgets;
}
@Override
protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {
if (widgets != null) {
for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
updateWidget(widget.widgetId, widget.widgetType);
}
}
}
mModeCallBack.finishActionMode();
}
}.execute();
}
private void deleteFolder(long folderId) {
if (folderId == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Wrong folder id, should not happen " + folderId);
return;
}
HashSet<Long> ids = new HashSet<Long>();
ids.add(folderId);
HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
folderId);
if (!isSyncMode()) {
// if not synced, delete folder directly
DataUtils.batchDeleteNotes(mContentResolver, ids);
} else {
// in sync mode, we'll move the deleted folder into the trash folder
DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
}
if (widgets != null) {
for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
updateWidget(widget.widgetId, widget.widgetType);
}
}
}
}
private void openNode(NoteItemData data) {
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, data.getId());
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
}
private void openFolder(NoteItemData data) {
mCurrentFolderId = data.getId();
startAsyncNotesListQuery();
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mState = ListEditState.CALL_RECORD_FOLDER;
mAddNewNote.setVisibility(View.GONE);
} else {
mState = ListEditState.SUB_FOLDER;
}
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mTitleBar.setText(R.string.call_record_folder_name);
} else {
mTitleBar.setText(data.getSnippet());
}
mTitleBar.setVisibility(View.VISIBLE);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_new_note:
createNewNote();
break;
default:
break;
}
}
private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
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);
final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
showSoftInput();
if (!create) {
if (mFocusNoteDataItem != null) {
etName.setText(mFocusNoteDataItem.getSnippet());
builder.setTitle(getString(R.string.menu_folder_change_name));
} else {
Log.e(TAG, "The long click data item is null");
return;
}
} else {
etName.setText("");
builder.setTitle(this.getString(R.string.menu_create_folder));
}
builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
hideSoftInput(etName);
}
});
final Dialog dialog = builder.setView(view).show();
final Button positive = (Button)dialog.findViewById(android.R.id.button1);
positive.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
hideSoftInput(etName);
String name = etName.getText().toString();
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
Toast.LENGTH_LONG).show();
etName.setSelection(0, etName.length());
return;
}
if (!create) {
if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId())
});
}
} else if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
}
dialog.dismiss();
}
});
if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
}
/**
* When the name edit text is null, disable the positive button
*/
etName.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false);
} else {
positive.setEnabled(true);
}
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
@Override
public void onBackPressed() {
switch (mState) {
case SUB_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST;
startAsyncNotesListQuery();
mTitleBar.setVisibility(View.GONE);
break;
case CALL_RECORD_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST;
mAddNewNote.setVisibility(View.VISIBLE);
mTitleBar.setVisibility(View.GONE);
startAsyncNotesListQuery();
break;
case NOTE_LIST:
super.onBackPressed();
break;
default:
break;
}
}
private void updateWidget(int appWidgetId, int appWidgetType) {
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
if (appWidgetType == Notes.TYPE_WIDGET_2X) {
intent.setClass(this, NoteWidgetProvider_2x.class);
} else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
intent.setClass(this, NoteWidgetProvider_4x.class);
} else {
Log.e(TAG, "Unspported widget type");
return;
}
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
appWidgetId
});
sendBroadcast(intent);
setResult(RESULT_OK, intent);
}
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) {
menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());
menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);
menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);
menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name);
}
}
};
@Override
public void onContextMenuClosed(Menu menu) {
if (mNotesListView != null) {
mNotesListView.setOnCreateContextMenuListener(null);
}
super.onContextMenuClosed(menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (mFocusNoteDataItem == null) {
Log.e(TAG, "The long click data item is null");
return false;
}
switch (item.getItemId()) {
case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem);
break;
case MENU_FOLDER_DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder));
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteFolder(mFocusNoteDataItem.getId());
}
});
builder.setNegativeButton(android.R.string.cancel, null);
builder.show();
break;
case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false);
break;
default:
break;
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if (mState == ListEditState.NOTE_LIST) {
getMenuInflater().inflate(R.menu.note_list, menu);
// set sync or sync_cancel
menu.findItem(R.id.menu_sync).setTitle(
GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
} else if (mState == ListEditState.SUB_FOLDER) {
getMenuInflater().inflate(R.menu.sub_folder, menu);
} else if (mState == ListEditState.CALL_RECORD_FOLDER) {
getMenuInflater().inflate(R.menu.call_record_folder, menu);
} else {
Log.e(TAG, "Wrong state:" + mState);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_new_folder: {
showCreateOrModifyFolderDialog(true);
break;
}
case R.id.menu_export_text: {
exportNoteToText();
break;
}
case R.id.menu_sync: {
if (isSyncMode()) {
if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
GTaskSyncService.startSync(this);
} else {
GTaskSyncService.cancelSync(this);
}
} else {
startPreferenceActivity();
}
break;
}
case R.id.menu_setting: {
startPreferenceActivity();
break;
}
case R.id.menu_new_note: {
createNewNote();
break;
}
case R.id.menu_search:
onSearchRequested();
break;
default:
break;
}
return true;
}
@Override
public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false);
return true;
}
private void exportNoteToText() {
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... unused) {
return backup.exportToText();
}
@Override
protected void onPostExecute(Integer result) {
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_unmounted));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
} else if (result == BackupUtils.STATE_SUCCESS) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.success_sdcard_export));
builder.setMessage(NotesListActivity.this.getString(
R.string.format_exported_file_location, backup
.getExportedTextFileName(), backup.getExportedTextFileDir()));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
} else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_export));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
}
}
}.execute();
}
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1);
}
private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) {
NoteItemData item = ((NotesListItem) view).getItemData();
if (mNotesListAdapter.isInChoiceMode()) {
if (item.getType() == Notes.TYPE_NOTE) {
position = position - mNotesListView.getHeaderViewsCount();
mModeCallBack.onItemCheckedStateChanged(null, position, id,
!mNotesListAdapter.isSelectedItem(position));
}
return;
}
switch (mState) {
case NOTE_LIST:
if (item.getType() == Notes.TYPE_FOLDER
|| item.getType() == Notes.TYPE_SYSTEM) {
openFolder(item);
} else if (item.getType() == Notes.TYPE_NOTE) {
openNode(item);
} else {
Log.e(TAG, "Wrong note type in NOTE_LIST");
}
break;
case SUB_FOLDER:
case CALL_RECORD_FOLDER:
if (item.getType() == Notes.TYPE_NOTE) {
openNode(item);
} else {
Log.e(TAG, "Wrong note type in SUB_FOLDER");
}
break;
default:
break;
}
}
}
}
private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection:
"(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
null,
Notes.CONTENT_NOTE_URI,
FoldersListAdapter.PROJECTION,
selection,
new String[] {
String.valueOf(Notes.TYPE_FOLDER),
String.valueOf(Notes.ID_TRASH_FOLER),
String.valueOf(mCurrentFolderId)
},
NoteColumns.MODIFIED_DATE + " DESC");
}
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (view instanceof NotesListItem) {
mFocusNoteDataItem = ((NotesListItem) view).getItemData();
if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
if (mNotesListView.startActionMode(mModeCallBack) != null) {
mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
} else {
Log.e(TAG, "startActionMode fails");
}
} else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
}
}
return false;
}
}

@ -0,0 +1,271 @@
java
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* <url id="cu1jjn4r4djrsk4hu5kg" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
* NotesListAdapter CursorAdapter ListView
* CursorAdapter
*
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter"; // 日志标签,用于日志输出
private Context mContext; // 上下文对象,用于获取资源和创建视图
private HashMap<Integer, Boolean> mSelectedIndex; // 用于记录选中的笔记位置
private int mNotesCount; // 笔记总数,用于判断是否全选
private boolean mChoiceMode; // 是否处于多选模式
/**
* AppWidgetAttribute ID
*/
public static class AppWidgetAttribute {
public int widgetId; // 小部件 ID
public int widgetType; // 小部件类型
};
/**
*
*
* @param context
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中位置的哈希表
mContext = context;
mNotesCount = 0; // 初始化笔记总数为 0
}
/**
*
*
* @param context
* @param cursor
* @param parent
* @return
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); // 创建新的笔记列表项视图
}
/**
*
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor); // 创建笔记项数据对象
((NotesListItem) view).bind(context, itemData, mChoiceMode, // 绑定数据到视图
isSelectedItem(cursor.getPosition()));
}
}
/**
*
*
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); // 更新选中状态
notifyDataSetChanged(); // 通知数据集已更改
}
/**
*
*
* @return
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
*
* @param mode
*/
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); // 清空选中状态
mChoiceMode = mode;
}
/**
*
*
* @param checked
*/
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked); // 设置每个笔记项的选中状态
}
}
}
}
/**
* ID
*
* @return ID
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen"); // 错误的笔记 ID
} else {
itemSet.add(id); // 添加选中的笔记 ID
}
}
}
return itemSet;
}
/**
*
*
* @return
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId(); // 获取小部件 ID
widget.widgetType = item.getWidgetType(); // 获取小部件类型
itemSet.add(widget); // 添加小部件属性
/**
* Don't close cursor here, only the adapter could close it
*/
} else {
Log.e(TAG, "Invalid cursor"); // 无效的游标
return null;
}
}
}
return itemSet;
}
/**
*
*
* @return
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0;
}
Iterator<Boolean> iter = values.iterator();
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++; // 统计选中的笔记项数量
}
}
return count;
}
/**
*
*
* @return
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); // 判断是否全选
}
/**
*
*
* @param position
* @return
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
}
return mSelectedIndex.get(position);
}
/**
*
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount(); // 重新计算笔记总数
}
/**
*
*
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount(); // 重新计算笔记总数
}
/**1\
/**
*
*/
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++; // 统计笔记数量
}
} else {
Log.e(TAG, "Invalid cursor"); // 无效的游标
return;
}
}
}
}

@ -0,0 +1,122 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout {
private ImageView mAlert;
private TextView mTitle;
private TextView mTime;
private TextView mCallName;
private NoteItemData mItemData;
private CheckBox mCheckBox;
public NotesListItem(Context context) {
super(context);
inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
mCheckBox.setVisibility(View.GONE);
}
mItemData = data;
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data);
}
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) {
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
public NoteItemData getItemData() {
return mItemData;
}
}

@ -0,0 +1,477 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// 文件头部的版权声明,声明了版权归属、许可证信息以及使用该文件的法律限制
package net.micode.notes.ui;
// 导入当前Java类所在的包该包名为net.micode.notes.ui
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
// 导入当前Java类所依赖的Android SDK中的类和接口
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
// 导入当前Java类所依赖的项目内部的类和接口这些类和接口位于net.micode.notes包及其子包中
public class NotesPreferenceActivity extends PreferenceActivity {
// 定义一个名为NotesPreferenceActivity的公共类该类继承自PreferenceActivity用于实现应用的设置界面
public static final String PREFERENCE_NAME = "notes_preferences";
// 定义一个公共静态常量PREFERENCE_NAME用于指定设置界面的偏好设置文件名
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
// 定义一个公共静态常量PREFERENCE_SYNC_ACCOUNT_NAME用于指定同步账户名称的偏好设置键名
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
// 定义一个公共静态常量PREFERENCE_LAST_SYNC_TIME用于指定最后同步时间的偏好设置键名
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
// 定义一个公共静态常量PREFERENCE_SET_BG_COLOR_KEY用于指定背景颜色设置的偏好设置键名
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
// 定义一个私有静态常量PREFERENCE_SYNC_ACCOUNT_KEY用于指定同步账户的偏好设置键名
private static final String AUTHORITIES_FILTER_KEY = "authorities";
// 定义一个私有静态常量AUTHORITIES_FILTER_KEY用于指定权限过滤的键名
private PreferenceCategory mAccountCategory;
// 定义一个私有成员变量mAccountCategory类型为PreferenceCategory用于存储账户相关的偏好设置分类
private GTaskReceiver mReceiver;
// 定义一个私有成员变量mReceiver类型为GTaskReceiver用于接收GTaskSyncService的广播
private Account[] mOriAccounts;
// 定义一个私有成员变量mOriAccounts类型为Account数组用于存储原始账户信息
private boolean mHasAddedAccount;
// 定义一个私有成员变量mHasAddedAccount类型为boolean用于标记是否已添加账户
@Override
protected void onCreate(Bundle icicle) {
// 重写onCreate方法用于初始化设置界面
super.onCreate(icicle);
// 调用父类的onCreate方法
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);
// 设置ActionBar的导航按钮为应用图标
addPreferencesFromResource(R.xml.preferences);
// 从资源文件R.xml.preferences中加载偏好设置
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
// 获取同步账户的偏好设置分类
mReceiver = new GTaskReceiver();
// 创建一个新的GTaskReceiver实例
IntentFilter filter = new IntentFilter();
// 创建一个新的IntentFilter实例
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
// 为IntentFilter添加GTaskSyncService的广播名称
registerReceiver(mReceiver, filter);
// 注册GTaskReceiver以接收GTaskSyncService的广播
mOriAccounts = null;
// 初始化mOriAccounts为null
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
// 从资源文件R.layout.settings_header中加载设置界面的头部视图
getListView().addHeaderView(header, null, true);
// 将头部视图添加到ListView中
}
@Override
protected void onResume() {
// 重写onResume方法用于在设置界面恢复时执行操作
super.onResume();
// 调用父类的onResume方法
// need to set sync account automatically if user has added a new
// account
if (mHasAddedAccount) {
// 如果用户已添加新账户,则需要自动设置同步账户
Account[] accounts = getGoogleAccounts();
// 获取当前的Google账户信息
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
// 如果原始账户信息不为空且当前账户数量大于原始账户数量
for (Account accountNew : accounts) {
// 遍历当前账户信息
boolean found = false;
for (Account accountOld : mOriAccounts) {
// 遍历原始账户信息
if (TextUtils.equals(accountOld.name, accountNew.name)) {
// 如果找到相同的账户名称
found = true;
break;
}
}
if (!found) {
// 如果未找到相同的账户名称
setSyncAccount(accountNew.name);
// 设置同步账户为新账户
break;
}
}
}
}
refreshUI();
// 刷新设置界面的UI
}
@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
// 在Activity销毁时如果mReceiver不为空则注销之前注册的广播接收器mReceiver以避免内存泄漏
super.onDestroy();
// 调用父类的onDestroy方法完成Activity销毁的其他必要操作
}
private void loadAccountPreference() {
mAccountCategory.removeAll();
// 清空账户相关的偏好设置分类中的所有偏好设置项
Preference accountPref = new Preference(this);
// 创建一个新的Preference实例用于表示账户偏好设置项
final String defaultAccount = getSyncAccountName(this);
// 获取当前设置的同步账户名称
accountPref.setTitle(getString(R.string.preferences_account_title));
// 设置账户偏好设置项的标题
accountPref.setSummary(getString(R.string.preferences_account_summary));
// 设置账户偏好设置项的摘要
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) {
// 如果当前没有正在进行的同步操作
if (TextUtils.isEmpty(defaultAccount)) {
// 如果当前没有设置同步账户,则显示选择账户的对话框
showSelectAccountAlertDialog();
} else {
// 如果已经设置了同步账户,则显示提示用户更改账户的风险的对话框
showChangeAccountConfirmAlertDialog();
}
} else {
// 如果当前有正在进行的同步操作则显示提示不能更改账户的Toast消息
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
mAccountCategory.addPreference(accountPref);
// 将账户偏好设置项添加到账户相关的偏好设置分类中
}
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
// 获取同步按钮
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// 获取显示最后同步时间的TextView
// set button state
if (GTaskSyncService.isSyncing()) {
// 如果当前有正在进行的同步操作
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
// 设置同步按钮的文本为取消同步
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
// 点击同步按钮时,取消正在进行的同步操作
}
});
} else {
// 如果当前没有正在进行的同步操作
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
// 设置同步按钮的文本为立即同步
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
// 点击同步按钮时,开始同步操作
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// 如果已设置了同步账户,则使同步按钮可用;否则,使同步按钮不可用
// set last sync time
if (GTaskSyncService.isSyncing()) {
// 如果当前有正在进行的同步操作
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
// 设置显示最后同步时间的TextView的文本为同步进度字符串
lastSyncTimeView.setVisibility(View.VISIBLE);
// 使显示最后同步时间的TextView可见
} else {
long lastSyncTime = getLastSyncTime(this);
// 获取最后同步时间
if (lastSyncTime != 0) {
// 如果最后同步时间不为0
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
// 设置显示最后同步时间的TextView的文本为格式化后的最后同步时间字符串
lastSyncTimeView.setVisibility(View.VISIBLE);
// 使显示最后同步时间的TextView可见
} else {
lastSyncTimeView.setVisibility(View.GONE);
// 如果最后同步时间为0则使显示最后同步时间的TextView不可见
}
}
}
private void refreshUI() {
loadAccountPreference();
// 加载账户相关的偏好设置项
loadSyncButton();
// 加载同步按钮和显示最后同步时间的TextView
}
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 创建一个新的AlertDialog.Builder实例用于构建选择账户的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
// 从资源文件R.layout.account_dialog_title中加载对话框的标题视图
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
// 获取对话框标题视图中的标题TextView
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
// 设置对话框标题TextView的文本为选择账户的标题
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
// 获取对话框标题视图中的副标题TextView
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
// 设置对话框副标题TextView的文本为选择账户的提示信息
dialogBuilder.setCustomTitle(titleView);
// 设置对话框的自定义标题视图为加载的标题视图
dialogBuilder.setPositiveButton(null, null);
// 设置对话框的正面按钮为null即不显示正面按钮
Account[] accounts = getGoogleAccounts();
// 获取当前的Google账户信息
String defAccount = getSyncAccountName(this);
// 获取当前设置的同步账户名称
mOriAccounts = accounts;
// 将获取的Google账户信息存储到mOriAccounts中
mHasAddedAccount = false;
// 将mHasAddedAccount设置为false表示没有添加新账户
if (accounts.length > 0) {
// 如果有Google账户信息
CharSequence[] items = new CharSequence[accounts.length];
// 创建一个CharSequence数组用于存储账户名称
final CharSequence[] itemMapping = items;
// 创建一个CharSequence数组的副本用于在点击事件中使用
int checkedItem = -1;
// 初始化选中项的索引为-1表示没有选中项
int index = 0;
for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
// 如果账户名称与当前设置的同步账户名称相同
checkedItem = index;
// 设置选中项的索引为当前账户的索引
}
items[index++] = account.name;
// 将账户名称添加到CharSequence数组中
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString());
// 设置同步账户为选中的账户名称
dialog.dismiss();
// 关闭对话框
refreshUI();
// 刷新设置界面的UI
}
});
// 设置对话框的单选列表项为账户名称数组,选中项为当前设置的同步账户,点击事件为设置同步账户并关闭对话框
}
}
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
});
startActivityForResult(intent, -1);
dialog.dismiss();
}
});
}
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel)
};
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showSelectAccountAlertDialog();
} else if (which == 1) {
removeSyncAccount();
refreshUI();
}
}
});
dialogBuilder.show();
}
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
editor.commit();
// clean up last sync time
setLastSyncTime(this, 0);
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
}
editor.commit();
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
}
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
}
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return false;
}
}
}

@ -0,0 +1,176 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
/**
* NoteWidgetProvider便
*/
public abstract class NoteWidgetProvider extends AppWidgetProvider {
// 数据库查询所需字段
public static final String[] PROJECTION = new String[]{
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
};
// PROJECTION 的索引
public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
private static final String TAG = "NoteWidgetProvider";
/**
*
* WIDGET_ID
*/
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
// 遍历所有被删除的小部件 ID更新数据库
for (int i = 0; i < appWidgetIds.length; i++) {
context.getContentResolver().update(
Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
new String[]{String.valueOf(appWidgetIds[i])});
}
}
/**
* ID 便
*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[]{String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
}
/**
*
*/
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false); // 默认非隐私模式
}
/**
*
*
* @param privacyMode
*/
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {
// 忽略无效小部件 ID
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
int bgId = ResourceParser.getDefaultBgId(context); // 默认背景颜色 ID
String snippet = ""; // 便签内容
// 创建启动 NoteEditActivity 的 Intent
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
// 查询小部件对应的便签信息
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c != null && c.moveToFirst()) {
if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return; // 如果有多个便签对应同一小部件 ID返回错误
}
snippet = c.getString(COLUMN_SNIPPET); // 获取便签内容
bgId = c.getInt(COLUMN_BG_COLOR_ID); // 获取便签背景 ID
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); // 传递便签 ID
intent.setAction(Intent.ACTION_VIEW); // 设置动作为查看
} else {
snippet = context.getResources().getString(R.string.widget_havenot_content); // 无便签内容时的占位文本
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); // 设置动作为插入或编辑
}
if (c != null) {
c.close(); // 关闭游标
}
// 设置小部件的显示内容
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); // 设置背景图像
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
// 根据隐私模式设置小部件显示和点击动作
PendingIntent pendingIntent = null;
if (privacyMode) {
rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode)); // 隐私模式文本
pendingIntent = PendingIntent.getActivity(
context,
appWidgetIds[i],
new Intent(context, NotesListActivity.class),
PendingIntent.FLAG_UPDATE_CURRENT);
} else {
rv.setTextViewText(R.id.widget_text, snippet); // 显示便签内容
pendingIntent = PendingIntent.getActivity(
context,
appWidgetIds[i],
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); // 设置点击事件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); // 更新小部件
}
}
}
/**
* ID
*/
protected abstract int getBgResourceId(int bgId);
/**
* ID
*/
protected abstract int getLayoutId();
/**
*
*/
protected abstract int getWidgetType();
}

@ -0,0 +1,78 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* NoteWidgetProvider_2x 2x 便
* NoteWidgetProvider
*/
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
/**
*
* update
*
* @param context
* @param appWidgetManager AppWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); // 调用父类的更新方法
}
/**
* 2x ID
* 2x
*
* @return ID
*/
@Override
protected int getLayoutId() {
return R.layout.widget_2x; // 指定 2x 小部件的布局资源
}
/**
* 2x ID
* 便 ID
*
* @param bgId ID
* @return ID
*/
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); // 获取 2x 背景资源
}
/**
* 2x
*
*
* @return
*/
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X; // 返回 2x 小部件的类型标识
}
}

@ -0,0 +1,78 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
/**
* NoteWidgetProvider_4x 4x 便
* NoteWidgetProvider
*/
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
/**
*
* update
*
* @param context
* @param appWidgetManager AppWidgetManager
* @param appWidgetIds ID
*/
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); // 调用父类的更新逻辑
}
/**
* 4x ID
* ID
*
* @return ID
*/
@Override
protected int getLayoutId() {
return R.layout.widget_4x; // 使用 4x 大小的小部件布局文件
}
/**
* 4x ID
* 便 ID
*
* @param bgId ID
* @return ID
*/
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); // 获取 4x 背景资源
}
/**
* 4x
*
*
* @return
*/
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; // 返回 4x 小部件的类型标识
}
}
Loading…
Cancel
Save