diff --git a/doc/开源软件的质量分析报告文档-李明阳,刘智龙组(2).docx b/doc/开源软件的质量分析报告文档-李明阳,刘智龙组(2).docx new file mode 100644 index 0000000..83e2bd4 Binary files /dev/null and b/doc/开源软件的质量分析报告文档-李明阳,刘智龙组(2).docx differ diff --git a/doc/文档模板-开源软件泛读、标注和维护报告文档(5).docx b/doc/文档模板-开源软件泛读、标注和维护报告文档(5).docx new file mode 100644 index 0000000..ff88e08 Binary files /dev/null and b/doc/文档模板-开源软件泛读、标注和维护报告文档(5).docx differ diff --git a/src/MainActivity.java b/src/MainActivity.java new file mode 100644 index 0000000..8091753 --- /dev/null +++ b/src/MainActivity.java @@ -0,0 +1,24 @@ +package net.micode.notes; + +import android.os.Bundle; + +import androidx.activity.EdgeToEdge; +import androidx.appcompat.app.AppCompatActivity; +import androidx.core.graphics.Insets; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowInsetsCompat; + +public class MainActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + EdgeToEdge.enable(this); + setContentView(R.layout.activity_main); + ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { + Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); + v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); + return insets; + }); + } +} \ No newline at end of file diff --git a/src/model/Note.java b/src/model/Note.java new file mode 100644 index 0000000..629c9b2 --- /dev/null +++ b/src/model/Note.java @@ -0,0 +1,377 @@ +/* + * 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"; + // 日志标签 + + /** + * Create a new note id for adding a new note to databases + */ + // 创建新笔记ID,用于向数据库添加新笔记 + public static synchronized long getNewNoteId(Context context, long folderId) { + // 同步方法,确保线程安全 + // Create a new note in the database + // 在数据库中创建新笔记 + ContentValues values = new ContentValues(); + // 创建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); + // 设置本地修改标志为1 + values.put(NoteColumns.PARENT_ID, folderId); + // 设置父文件夹ID + Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values); + // 插入数据库并获取URI + + long noteId = 0; + // 笔记ID初始化为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); + // 如果笔记ID为-1,抛出异常 + } + return noteId; + // 返回笔记ID + } + + public Note() { + // 构造方法 + mNoteDiffValues = new ContentValues(); + // 初始化笔记差异值 + mNoteData = new NoteData(); + // 初始化笔记数据对象 + } + + public void setNoteValue(String key, String value) { + // 设置笔记值 + mNoteDiffValues.put(key, value); + // 将键值对存入差异值 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置本地修改标志为1 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + // 设置修改时间为当前时间 + } + + public void setTextData(String key, String value) { + // 设置文本数据 + mNoteData.setTextData(key, value); + // 调用NoteData的setTextData方法 + } + + public void setTextDataId(long id) { + // 设置文本数据ID + mNoteData.setTextDataId(id); + // 调用NoteData的setTextDataId方法 + } + + public long getTextDataId() { + // 获取文本数据ID + return mNoteData.mTextDataId; + // 返回NoteData中的文本数据ID + } + + public void setCallDataId(long id) { + // 设置通话数据ID + mNoteData.setCallDataId(id); + // 调用NoteData的setCallDataId方法 + } + + public void setCallData(String key, String value) { + // 设置通话数据 + mNoteData.setCallData(key, value); + // 调用NoteData的setCallData方法 + } + + public boolean isLocalModified() { + // 检查是否有本地修改 + return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); + // 如果笔记差异值非空或NoteData有修改,返回true + } + + public boolean syncNote(Context context, long noteId) { + // 同步笔记到数据库 + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + // 检查笔记ID是否有效 + } + + if (!isLocalModified()) { + return true; + // 如果没有本地修改,直接返回成功 + } + + /** + * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and + * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the + * note data info + */ + // 理论上,数据改变后应该更新LOCAL_MODIFIED和MODIFIED_DATE字段 + // 为了数据安全,即使笔记更新失败,也更新笔记数据信息 + if (context.getContentResolver().update( + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, + null) == 0) { + // 更新笔记表 + Log.e(TAG, "Update note error, should not happen"); + // 记录错误日志(理论上不应该发生) + // Do not return, fall through + // 不返回,继续执行 + } + mNoteDiffValues.clear(); + // 清空笔记差异值 + + if (mNoteData.isLocalModified() + && (mNoteData.pushIntoContentResolver(context, noteId) == null)) { + // 如果NoteData有修改且推送数据失败 + return false; + // 返回失败 + } + + return true; + // 返回成功 + } + + private class NoteData { + // 内部类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; + // 文本数据ID初始为0 + mCallDataId = 0; + // 通话数据ID初始为0 + } + + boolean isLocalModified() { + // 检查是否有本地修改 + return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; + // 如果文本或通话数据差异值非空,返回true + } + + void setTextDataId(long id) { + // 设置文本数据ID + if(id <= 0) { + throw new IllegalArgumentException("Text data id should larger than 0"); + // 检查ID是否大于0 + } + mTextDataId = id; + // 设置文本数据ID + } + + void setCallDataId(long id) { + // 设置通话数据ID + if (id <= 0) { + throw new IllegalArgumentException("Call data id should larger than 0"); + // 检查ID是否大于0 + } + mCallDataId = id; + // 设置通话数据ID + } + + void setCallData(String key, String value) { + // 设置通话数据 + mCallDataValues.put(key, value); + // 将键值对存入通话数据差异值 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置笔记的本地修改标志 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + // 设置笔记的修改时间 + } + + void setTextData(String key, String value) { + // 设置文本数据 + mTextDataValues.put(key, value); + // 将键值对存入文本数据差异值 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置笔记的本地修改标志 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); + // 设置笔记的修改时间 + } + + Uri pushIntoContentResolver(Context context, long noteId) { + // 将数据推送到内容解析器 + /** + * Check for safety + */ + // 安全检查 + if (noteId <= 0) { + throw new IllegalArgumentException("Wrong note id:" + noteId); + // 检查笔记ID是否有效 + } + + ArrayList operationList = new ArrayList(); + // 创建操作列表 + ContentProviderOperation.Builder builder = null; + // 操作构建器 + + if(mTextDataValues.size() > 0) { + // 如果有文本数据需要更新 + mTextDataValues.put(DataColumns.NOTE_ID, noteId); + // 设置笔记ID + if (mTextDataId == 0) { + // 如果文本数据ID为0,表示是新的文本数据 + mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE); + // 设置MIME类型为文本笔记 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, + mTextDataValues); + // 插入数据并获取URI + 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; + // 返回null表示失败 + } + } else { + // 如果文本数据ID已存在,表示是更新操作 + 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) { + // 如果通话数据ID为0,表示是新的通话数据 + mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); + // 设置MIME类型为通话笔记 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, + mCallDataValues); + // 插入数据并获取URI + 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; + // 返回null表示失败 + } + } else { + // 如果通话数据ID已存在,表示是更新操作 + 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;否则返回null + } 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; + // 如果操作列表为空,返回null + } + } +} +``` \ No newline at end of file diff --git a/src/model/WorkingNote.java b/src/model/WorkingNote.java new file mode 100644 index 0000000..112f90d --- /dev/null +++ b/src/model/WorkingNote.java @@ -0,0 +1,530 @@ +/* + * 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 { +// 工作笔记类,处理笔记的创建、加载和修改 + + // Note for the working note + // 工作笔记的Note对象 + private Note mNote; + + // Note Id + // 笔记ID + private long mNoteId; + + // Note content + // 笔记内容 + private String mContent; + + // Note mode + // 笔记模式(普通模式或清单模式) + private int mMode; + + private long mAlertDate; + // 提醒日期 + + private long mModifiedDate; + // 修改日期 + + 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 // 修改日期 + }; + + // 数据投影列索引 + private static final int DATA_ID_COLUMN = 0; + // 数据ID列索引 + + private static final int DATA_CONTENT_COLUMN = 1; + // 内容列索引 + + private static final int DATA_MIME_TYPE_COLUMN = 2; + // MIME类型列索引 + + private static final int DATA_MODE_COLUMN = 3; + // 模式列索引(对应DATA1字段) + + // 笔记投影列索引 + private static final int NOTE_PARENT_ID_COLUMN = 0; + // 父ID列索引 + + private static final int NOTE_ALERTED_DATE_COLUMN = 1; + // 提醒日期列索引 + + private static final int NOTE_BG_COLOR_ID_COLUMN = 2; + // 背景颜色ID列索引 + + private static final int NOTE_WIDGET_ID_COLUMN = 3; + // 小部件ID列索引 + + private static final int NOTE_WIDGET_TYPE_COLUMN = 4; + // 小部件类型列索引 + + private static final int NOTE_MODIFIED_DATE_COLUMN = 5; + // 修改日期列索引 + + // New note construct + // 新建笔记构造方法 + private WorkingNote(Context context, long folderId) { + mContext = context; + // 保存上下文 + mAlertDate = 0; + // 提醒日期初始为0 + mModifiedDate = System.currentTimeMillis(); + // 修改日期为当前时间 + mFolderId = folderId; + // 设置文件夹ID + mNote = new Note(); + // 创建Note对象 + mNoteId = 0; + // 笔记ID初始为0(表示新笔记) + mIsDeleted = false; + // 未删除 + mMode = 0; + // 默认模式为普通模式 + mWidgetType = Notes.TYPE_WIDGET_INVALIDE; + // 小部件类型为无效 + } + + // Existing note construct + // 加载已存在笔记构造方法 + private WorkingNote(Context context, long noteId, long folderId) { + mContext = context; + // 保存上下文 + mNoteId = noteId; + // 设置笔记ID + mFolderId = folderId; + // 设置文件夹ID + mIsDeleted = false; + // 未删除 + mNote = new Note(); + // 创建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); + // 父文件夹ID + mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); + // 背景颜色ID + mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); + // 小部件ID + 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); + // 获取MIME类型 + if (DataConstants.NOTE.equals(type)) { + // 如果是文本笔记 + mContent = cursor.getString(DATA_CONTENT_COLUMN); + // 获取内容 + mMode = cursor.getInt(DATA_MODE_COLUMN); + // 获取模式 + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); + // 设置文本数据ID + } else if (DataConstants.CALL_NOTE.equals(type)) { + // 如果是通话笔记 + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN)); + // 设置通话数据ID + } 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); + // 抛出异常 + } + } + + 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); + // 设置小部件ID + note.setWidgetType(widgetType); + // 设置小部件类型 + return note; + // 返回工作笔记 + } + + public static WorkingNote load(Context context, long id) { + // 加载已存在笔记的静态方法 + return new WorkingNote(context, id, 0); + // 创建并返回工作笔记 + } + + public synchronized boolean saveNote() { + // 保存笔记(同步方法,线程安全) + if (isWorthSaving()) { + // 如果值得保存 + if (!existInDatabase()) { + // 如果不存在于数据库中(新笔记) + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) { + // 获取新笔记ID失败 + Log.e(TAG, "Create new note fail with id:" + mNoteId); + return false; + } + } + + mNote.syncNote(mContext, mNoteId); + // 同步笔记到数据库 + + /** + * Update widget content if there exist any widget of this note + */ + // 如果存在该笔记的小部件,更新小部件内容 + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE + && mNoteSettingStatusListener != null) { + // 检查小部件是否有效且监听器存在 + mNoteSettingStatusListener.onWidgetChanged(); + // 通知小部件变化 + } + return true; + // 保存成功 + } else { + return false; + // 不需要保存 + } + } + + public boolean existInDatabase() { + // 检查笔记是否已存在于数据库中 + return mNoteId > 0; + // 笔记ID大于0表示已存在 + } + + private boolean isWorthSaving() { + // 检查是否值得保存 + if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent)) + || (existInDatabase() && !mNote.isLocalModified())) { + // 如果已删除,或新笔记但内容为空,或已存在但无本地修改 + return false; + } else { + return true; + } + } + + public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) { + // 设置笔记设置变化监听器 + mNoteSettingStatusListener = l; + } + + 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); + // 通知提醒变化 + } + } + + public void markDeleted(boolean mark) { + // 标记删除 + mIsDeleted = mark; + // 设置删除标记 + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) { + // 检查小部件是否有效且监听器存在 + mNoteSettingStatusListener.onWidgetChanged(); + // 通知小部件变化 + } + } + + public void setBgColorId(int id) { + // 设置背景颜色ID + if (id != mBgColorId) { + // 如果颜色ID发生变化 + mBgColorId = id; + // 更新背景颜色ID + if (mNoteSettingStatusListener != null) { + // 如果监听器存在 + mNoteSettingStatusListener.onBackgroundColorChanged(); + // 通知背景颜色变化 + } + mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); + // 设置笔记值 + } + } + + public void setCheckListMode(int mode) { + // 设置清单模式 + if (mMode != mode) { + // 如果模式发生变化 + if (mNoteSettingStatusListener != null) { + // 如果监听器存在 + mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode); + // 通知清单模式变化 + } + mMode = mode; + // 更新模式 + mNote.setTextData(TextNote.MODE, String.valueOf(mMode)); + // 设置文本数据 + } + } + + public void setWidgetType(int type) { + // 设置小部件类型 + if (type != mWidgetType) { + // 如果类型发生变化 + mWidgetType = type; + // 更新小部件类型 + mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); + // 设置笔记值 + } + } + + public void setWidgetId(int id) { + // 设置小部件ID + if (id != mWidgetId) { + // 如果ID发生变化 + mWidgetId = id; + // 更新小部件ID + mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); + // 设置笔记值 + } + } + + public void setWorkingText(String text) { + // 设置工作文本(笔记内容) + if (!TextUtils.equals(mContent, text)) { + // 如果内容发生变化 + mContent = text; + // 更新内容 + mNote.setTextData(DataColumns.CONTENT, mContent); + // 设置文本数据 + } + } + + 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)); + // 设置父文件夹为通话记录文件夹 + } + + public boolean hasClockAlert() { + // 检查是否有闹钟提醒 + return (mAlertDate > 0 ? true : false); + // 提醒日期大于0表示有提醒 + } + + // 以下为获取属性的方法 + public String getContent() { + // 获取内容 + return mContent; + } + + public long getAlertDate() { + // 获取提醒日期 + return mAlertDate; + } + + public long getModifiedDate() { + // 获取修改日期 + return mModifiedDate; + } + + public int getBgColorResId() { + // 获取背景颜色资源ID + return NoteBgResources.getNoteBgResource(mBgColorId); + // 通过资源工具类获取 + } + + public int getBgColorId() { + // 获取背景颜色ID + return mBgColorId; + } + + public int getTitleBgResId() { + // 获取标题背景颜色资源ID + return NoteBgResources.getNoteTitleBgResource(mBgColorId); + // 通过资源工具类获取 + } + + public int getCheckListMode() { + // 获取清单模式 + return mMode; + } + + public long getNoteId() { + // 获取笔记ID + return mNoteId; + } + + public long getFolderId() { + // 获取文件夹ID + return mFolderId; + } + + public int getWidgetId() { + // 获取小部件ID + return mWidgetId; + } + + public int getWidgetType() { + // 获取小部件类型 + return mWidgetType; + } + + public interface NoteSettingChangedListener { + // 笔记设置变化监听器接口 + /** + * Called when the background color of current note has just changed + */ + // 当前笔记背景颜色变化时调用 + void onBackgroundColorChanged(); + + /** + * Called when user set clock + */ + // 用户设置闹钟时调用 + void onClockAlertChanged(long date, boolean set); + + /** + * Call when user create note from widget + */ + // 用户从小部件创建笔记时调用 + void onWidgetChanged(); + + /** + * Call when switch between check list mode and normal mode + * @param oldMode is previous mode before change + * @param newMode is new mode + */ + // 在清单模式和普通模式之间切换时调用 + // oldMode是变化前的模式 + // newMode是新模式 + void onCheckListModeChanged(int oldMode, int newMode); + } +} \ No newline at end of file diff --git a/src/tool/BackupUtils.java b/src/tool/BackupUtils.java new file mode 100644 index 0000000..91d3850 --- /dev/null +++ b/src/tool/BackupUtils.java @@ -0,0 +1,481 @@ +/* + * 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; + + +public class BackupUtils { +// 备份工具类,提供笔记导出为文本文件的功能 + + private static final String TAG = "BackupUtils"; + // 日志标签 + + // Singleton stuff + // 单例模式相关 + private static BackupUtils sInstance; + // 单例实例 + + public static synchronized BackupUtils getInstance(Context context) { + // 获取单例实例(同步方法) + if (sInstance == null) { + sInstance = new BackupUtils(context); + // 创建新实例 + } + return sInstance; + // 返回实例 + } + + /** + * Following states are signs to represents backup or restore + * status + */ + // 以下状态表示备份或恢复的状态 + // Currently, the sdcard is not mounted + // 当前SD卡未挂载 + public static final int STATE_SD_CARD_UNMOUONTED = 0; + // The backup file not exist + // 备份文件不存在 + public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; + // The data is not well formated, may be changed by other programs + // 数据格式错误,可能被其他程序修改 + public static final int STATE_DATA_DESTROIED = 2; + // Some run-time exception which causes restore or backup fails + // 运行时异常导致备份或恢复失败 + public static final int STATE_SYSTEM_ERROR = 3; + // Backup or restore success + // 备份或恢复成功 + public static final int STATE_SUCCESS = 4; + + private TextExport mTextExport; + // 文本导出对象 + + 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; + } + + private static class TextExport { + // 内部类:文本导出 + + // 笔记表投影列数组 + private static final String[] NOTE_PROJECTION = { + NoteColumns.ID, // 笔记ID + NoteColumns.MODIFIED_DATE, // 修改日期 + NoteColumns.SNIPPET, // 摘要 + NoteColumns.TYPE // 类型 + }; + + // 笔记列索引 + private static final int NOTE_COLUMN_ID = 0; + // ID列索引 + + 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, // MIME类型 + DataColumns.DATA1, // 数据1(用于通话日期) + DataColumns.DATA2, // 数据2 + DataColumns.DATA3, // 数据3(用于电话号码) + DataColumns.DATA4, // 数据4 + }; + + // 数据列索引 + private static final int DATA_COLUMN_CONTENT = 0; + // 内容列索引 + + private static final int DATA_COLUMN_MIME_TYPE = 1; + // MIME类型列索引 + + private static final int DATA_COLUMN_CALL_DATE = 2; + // 通话日期列索引(对应DATA1) + + private static final int DATA_COLUMN_PHONE_NUMBER = 4; + // 电话号码列索引(对应DATA3) + + // 文本格式化数组 + private final String [] TEXT_FORMAT; + // 文本格式数组(从资源文件加载) + + // 格式类型索引 + private static final int FORMAT_FOLDER_NAME = 0; + // 文件夹名称格式索引 + + private static final int FORMAT_NOTE_DATE = 1; + // 笔记日期格式索引 + + private static final int FORMAT_NOTE_CONTENT = 2; + // 笔记内容格式索引 + + // 成员变量 + private Context mContext; + // 上下文 + + private String mFileName; + // 文件名 + + private String mFileDirectory; + // 文件目录 + + public TextExport(Context context) { + // 构造方法 + TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); + // 从资源文件加载文本格式数组 + mContext = context; + // 保存上下文 + mFileName = ""; + // 初始化文件名为空 + mFileDirectory = ""; + // 初始化文件目录为空 + } + + private String getFormat(int id) { + // 获取指定格式的字符串 + return TEXT_FORMAT[id]; + // 返回格式字符串 + } + + /** + * Export the folder identified by folder id to text + */ + // 将指定文件夹导出为文本 + private void exportFolderToText(String folderId, PrintStream ps) { + // Query notes belong to this folder + // 查询属于该文件夹的笔记 + Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { + folderId + }, null); + // 查询父ID为folderId的笔记 + + if (notesCursor != null) { + if (notesCursor.moveToFirst()) { + do { + // Print note's last modified date + // 打印笔记的最后修改日期 + ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( + mContext.getString(R.string.format_datetime_mdhm), + notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); + // 格式化并输出日期 + // Query data belong to this note + // 查询属于该笔记的数据 + String noteId = notesCursor.getString(NOTE_COLUMN_ID); + // 获取笔记ID + exportNoteToText(noteId, ps); + // 导出笔记内容 + } while (notesCursor.moveToNext()); + // 继续处理下一个笔记 + } + notesCursor.close(); + // 关闭游标 + } + } + + /** + * Export note identified by id to a print stream + */ + // 将指定笔记导出到打印流 + 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 { + String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); + // 获取MIME类型 + if (DataConstants.CALL_NOTE.equals(mimeType)) { + // 如果是通话笔记 + // Print phone number + // 打印电话号码 + 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)); + // 输出电话号码 + } + // Print call date + // 打印通话日期 + ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat + .format(mContext.getString(R.string.format_datetime_mdhm), + callDate))); + // 格式化并输出日期 + // Print call attachment location + // 打印通话附件位置 + 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(); + // 关闭游标 + } + // print a line separator between note + // 在笔记之间打印行分隔符 + try { + ps.write(new byte[] { + Character.LINE_SEPARATOR, Character.LETTER_NUMBER + // 写入行分隔符(注意:这里代码有误,应该是换行符) + }); + } catch (IOException e) { + Log.e(TAG, e.toString()); + // 记录异常 + } + } + + /** + * Note will be exported as text which is user readable + */ + // 笔记将被导出为用户可读的文本 + public int exportToText() { + if (!externalStorageAvailable()) { + // 检查外部存储是否可用 + Log.d(TAG, "Media was not mounted"); + return STATE_SD_CARD_UNMOUONTED; + // 返回SD卡未挂载状态 + } + + PrintStream ps = getExportToTextPrintStream(); + // 获取打印流 + if (ps == null) { + Log.e(TAG, "get print stream error"); + return STATE_SYSTEM_ERROR; + // 返回系统错误状态 + } + // First export folder and its notes + // 首先导出文件夹及其笔记 + 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 { + // Print folder's name + // 打印文件夹名称 + String folderName = ""; + if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) { + // 如果是通话记录文件夹 + folderName = mContext.getString(R.string.call_record_folder_name); + // 使用资源文件中的名称 + } 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); + // 获取文件夹ID + exportFolderToText(folderId, ps); + // 导出文件夹内容 + } while (folderCursor.moveToNext()); + // 继续处理下一个文件夹 + } + folderCursor.close(); + // 关闭游标 + } + + // Export notes in root's folder + // 导出根文件夹中的笔记 + Cursor noteCursor = mContext.getContentResolver().query( + Notes.CONTENT_NOTE_URI, + NOTE_PROJECTION, + NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID + + "=0", null, null); + // 查询根文件夹中的笔记(父ID为0) + + 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)))); + // 输出笔记修改日期 + // Query data belong to this note + // 查询属于该笔记的数据 + String noteId = noteCursor.getString(NOTE_COLUMN_ID); + // 获取笔记ID + exportNoteToText(noteId, ps); + // 导出笔记内容 + } while (noteCursor.moveToNext()); + // 继续处理下一个笔记 + } + noteCursor.close(); + // 关闭游标 + } + ps.close(); + // 关闭打印流 + + return STATE_SUCCESS; + // 返回成功状态 + } + + /** + * Get a print stream pointed to the file {@generateExportedTextFile} + */ + // 获取指向文件的打印流 + private PrintStream getExportToTextPrintStream() { + File file = generateFileMountedOnSDcard(mContext, R.string.file_path, + R.string.file_name_txt_format); + // 生成SD卡上的文件 + 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; + // 返回打印流 + } + } + + /** + * Generate the text file to store imported data + */ + // 生成存储导入数据的文本文件 + private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { + StringBuilder sb = new StringBuilder(); + // 使用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(); + // IO异常 + } + + return null; + // 返回null表示创建失败 + } +} \ No newline at end of file diff --git a/src/tool/DataUtils.java b/src/tool/DataUtils.java new file mode 100644 index 0000000..108fb61 --- /dev/null +++ b/src/tool/DataUtils.java @@ -0,0 +1,424 @@ +/* + * 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.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; + +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 +public class DataUtils { +// 数据工具类,提供笔记数据的各种操作方法 + + public static final String TAG = "DataUtils"; + // 日志标签 + + public static boolean batchDeleteNotes(ContentResolver resolver, HashSet ids) { + // 批量删除笔记 + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + // 如果ID集合为空,直接返回true + } + if (ids.size() == 0) { + Log.d(TAG, "no id is in the hashset"); + return true; + // 如果ID集合为空集,直接返回true + } + + ArrayList operationList = new ArrayList(); + // 创建操作列表 + for (long id : ids) { + // 遍历ID集合 + if(id == Notes.ID_ROOT_FOLDER) { + Log.e(TAG, "Don't delete system folder root"); + continue; + // 跳过根文件夹(系统文件夹) + } + ContentProviderOperation.Builder builder = ContentProviderOperation + .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + // 创建删除操作构建器 + operationList.add(builder.build()); + // 添加到操作列表 + } + try { + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + // 批量执行操作 + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + // 执行结果无效,返回false + } + return 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; + // 执行失败 + } + + public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { + // 移动笔记到文件夹(方法名拼写错误) + ContentValues values = new ContentValues(); + // 创建ContentValues + values.put(NoteColumns.PARENT_ID, desFolderId); + // 设置目标父文件夹ID + values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); + // 设置原始父文件夹ID + values.put(NoteColumns.LOCAL_MODIFIED, 1); + // 设置本地修改标志 + resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); + // 更新数据库 + } + + public static boolean batchMoveToFolder(ContentResolver resolver, HashSet ids, + long folderId) { + // 批量移动到文件夹 + if (ids == null) { + Log.d(TAG, "the ids is null"); + return true; + // ID集合为空,返回true + } + + ArrayList operationList = new ArrayList(); + // 创建操作列表 + for (long id : ids) { + // 遍历ID集合 + ContentProviderOperation.Builder builder = ContentProviderOperation + .newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); + // 创建更新操作构建器 + builder.withValue(NoteColumns.PARENT_ID, folderId); + // 设置父文件夹ID + builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); + // 设置本地修改标志 + operationList.add(builder.build()); + // 添加到操作列表 + } + + try { + ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); + // 批量执行操作 + if (results == null || results.length == 0 || results[0] == null) { + Log.d(TAG, "delete notes failed, ids:" + ids.toString()); + return false; + // 执行结果无效,返回false + } + return 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; + // 执行失败 + } + + /** + * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} + */ + // 获取用户文件夹数量(排除系统文件夹) + public static int 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); + // 参数 + + int count = 0; + // 数量初始化为0 + if(cursor != 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) { + // 检查笔记在数据库中是否可见(不在垃圾箱中) + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + // 查询指定笔记ID + null, + NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER, + // 条件:指定类型且不在垃圾箱 + new String [] {String.valueOf(type)}, + null); + + boolean exist = false; + // 存在标志初始化为false + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { + // 检查笔记是否存在于数据库中 + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), + // 查询指定笔记ID + null, null, null, null); + // 无条件查询 + + boolean exist = false; + // 存在标志初始化为false + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { + // 检查数据是否存在于数据表中 + Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), + // 查询指定数据ID + null, null, null, null); + // 无条件查询 + + boolean exist = false; + // 存在标志初始化为false + if (cursor != null) { + if (cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { + // 检查可见文件夹名称是否已存在 + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, + // 查询笔记表 + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + + // 类型为文件夹 + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + + // 不在垃圾箱 + " AND " + NoteColumns.SNIPPET + "=?", + // 摘要等于指定名称 + new String[] { name }, null); + // 参数 + + boolean exist = false; + // 存在标志初始化为false + if(cursor != null) { + if(cursor.getCount() > 0) { + exist = true; + // 如果有数据,设置为true + } + cursor.close(); + // 关闭游标 + } + return exist; + // 返回存在标志 + } + + public static HashSet getFolderNoteWidget(ContentResolver resolver, long folderId) { + // 获取文件夹中笔记的小部件属性 + Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, + // 查询笔记表 + new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE }, + // 查询小部件ID和类型 + NoteColumns.PARENT_ID + "=?", + // 父文件夹ID等于指定ID + new String[] { String.valueOf(folderId) }, + null); + + HashSet set = null; + // 集合初始化为null + if (c != null) { + if (c.moveToFirst()) { + // 移动到第一行 + set = new HashSet(); + // 创建集合 + do { + try { + AppWidgetAttribute widget = new AppWidgetAttribute(); + // 创建小部件属性对象 + widget.widgetId = c.getInt(0); + // 设置小部件ID + widget.widgetType = c.getInt(1); + // 设置小部件类型 + set.add(widget); + // 添加到集合 + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, e.toString()); + // 索引越界异常 + } + } while (c.moveToNext()); + // 继续处理下一行 + } + c.close(); + // 关闭游标 + } + return set; + // 返回集合 + } + + public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { + // 根据笔记ID获取通话号码 + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + // 查询数据表 + new String [] { CallNote.PHONE_NUMBER }, + // 只查询电话号码列 + CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?", + // 条件:笔记ID匹配且MIME类型为通话笔记 + 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 ""; + // 返回空字符串 + } + + public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { + // 根据电话号码和通话日期获取笔记ID + Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, + // 查询数据表 + new String [] { CallNote.NOTE_ID }, + // 只查询笔记ID列 + CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + + CallNote.PHONE_NUMBER + ",?)", + // 条件:通话日期匹配、MIME类型为通话笔记、电话号码相等 + new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, + null); + + if (cursor != null) { + if (cursor.moveToFirst()) { + // 移动到第一行 + try { + return cursor.getLong(0); + // 返回第一列的值(笔记ID) + } catch (IndexOutOfBoundsException e) { + Log.e(TAG, "Get call note id fails " + e.toString()); + // 索引越界异常 + } + } + cursor.close(); + // 关闭游标 + } + return 0; + // 返回0表示未找到 + } + + public static String getSnippetById(ContentResolver resolver, long noteId) { + // 根据笔记ID获取摘要 + Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, + // 查询笔记表 + new String [] { NoteColumns.SNIPPET }, + // 只查询摘要列 + NoteColumns.ID + "=?", + // 笔记ID匹配 + new String [] { String.valueOf(noteId)}, + null); + + if (cursor != null) { + String snippet = ""; + // 摘要初始化为空字符串 + if (cursor.moveToFirst()) { + snippet = cursor.getString(0); + // 获取第一列的值(摘要) + } + cursor.close(); + // 关闭游标 + return snippet; + // 返回摘要 + } + 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; + // 返回格式化后的摘要 + } +} +``` \ No newline at end of file diff --git a/src/tool/GTaskStringUtils.java b/src/tool/GTaskStringUtils.java new file mode 100644 index 0000000..8d4f23d --- /dev/null +++ b/src/tool/GTaskStringUtils.java @@ -0,0 +1,165 @@ +/* + * 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; + +```java +public class GTaskStringUtils { +// Google任务字符串工具类,定义所有与Google Tasks API相关的常量 + + // JSON键名常量 + public final static String GTASK_JSON_ACTION_ID = "action_id"; + // 操作ID键名 + + public final static String GTASK_JSON_ACTION_LIST = "action_list"; + // 操作列表键名 + + public final static String GTASK_JSON_ACTION_TYPE = "action_type"; + // 操作类型键名 + + public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create"; + // 创建操作类型值 + + public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all"; + // 获取所有操作类型值 + + public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move"; + // 移动操作类型值 + + public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; + // 更新操作类型值 + + public final static String GTASK_JSON_CREATOR_ID = "creator_id"; + // 创建者ID键名 + + public final static String GTASK_JSON_CHILD_ENTITY = "child_entity"; + // 子实体键名 + + public final static String GTASK_JSON_CLIENT_VERSION = "client_version"; + // 客户端版本键名 + + public final static String GTASK_JSON_COMPLETED = "completed"; + // 完成状态键名 + + public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id"; + // 当前列表ID键名 + + public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; + // 默认列表ID键名 + + public final static String GTASK_JSON_DELETED = "deleted"; + // 删除状态键名 + + public final static String GTASK_JSON_DEST_LIST = "dest_list"; + // 目标列表键名 + + public final static String GTASK_JSON_DEST_PARENT = "dest_parent"; + // 目标父节点键名 + + public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; + // 目标父节点类型键名 + + public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta"; + // 实体增量键名 + + public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; + // 实体类型键名 + + public final static String GTASK_JSON_GET_DELETED = "get_deleted"; + // 获取删除项键名 + + public final static String GTASK_JSON_ID = "id"; + // ID键名 + + public final static String GTASK_JSON_INDEX = "index"; + // 索引键名 + + public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; + // 最后修改时间键名 + + public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point"; + // 最新同步点键名 + + public final static String GTASK_JSON_LIST_ID = "list_id"; + // 列表ID键名 + + public final static String GTASK_JSON_LISTS = "lists"; + // 列表集合键名 + + public final static String GTASK_JSON_NAME = "name"; + // 名称键名 + + public final static String GTASK_JSON_NEW_ID = "new_id"; + // 新ID键名(创建操作返回) + + public final static String GTASK_JSON_NOTES = "notes"; + // 备注键名 + + public final static String GTASK_JSON_PARENT_ID = "parent_id"; + // 父节点ID键名 + + public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id"; + // 前一个兄弟节点ID键名 + + public final static String GTASK_JSON_RESULTS = "results"; + // 结果集合键名 + + public final static String GTASK_JSON_SOURCE_LIST = "source_list"; + // 源列表键名 + + public final static String GTASK_JSON_TASKS = "tasks"; + // 任务集合键名 + + public final static String GTASK_JSON_TYPE = "type"; + // 类型键名 + + public final static String GTASK_JSON_TYPE_GROUP = "GROUP"; + // 分组类型值 + + public final static String GTASK_JSON_TYPE_TASK = "TASK"; + // 任务类型值 + + public final static String GTASK_JSON_USER = "user"; + // 用户键名 + + // MIUI特定常量 + public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; + // MIUI笔记文件夹前缀(拼写错误:PREFFIX应为PREFIX) + + // 文件夹名称常量 + public final static String FOLDER_DEFAULT = "Default"; + // 默认文件夹名称 + + public final static String FOLDER_CALL_NOTE = "Call_Note"; + // 通话记录文件夹名称 + + public final static String FOLDER_META = "METADATA"; + // 元数据文件夹名称 + + // 元数据相关常量 + public final static String META_HEAD_GTASK_ID = "meta_gid"; + // 元数据Google任务ID键名 + + public final static String META_HEAD_NOTE = "meta_note"; + // 元数据笔记键名 + + public final static String META_HEAD_DATA = "meta_data"; + // 元数据数据键名 + + public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE"; + // 元数据笔记名称(警告不要更新和删除) +} +``` \ No newline at end of file diff --git a/src/tool/ResourceParser.java b/src/tool/ResourceParser.java new file mode 100644 index 0000000..6822705 --- /dev/null +++ b/src/tool/ResourceParser.java @@ -0,0 +1,221 @@ +/* + * 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; + +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; + // 默认字体大小为中等 + + 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 // 红色标题背景 + }; + + public static int getNoteBgResource(int id) { + // 根据ID获取笔记编辑背景资源 + return BG_EDIT_RESOURCES[id]; + // 返回对应ID的资源 + } + + public static int getNoteTitleBgResource(int id) { + // 根据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); + // 随机返回一个背景颜色ID + } else { + return BG_DEFAULT_COLOR; + // 返回默认颜色(黄色) + } + } + + public static class NoteItemBgResources { + // 笔记列表项背景资源类 + private final static int [] BG_FIRST_RESOURCES = new int [] { + R.drawable.list_yellow_up, // 列表第一项黄色背景 + R.drawable.list_blue_up, // 列表第一项蓝色背景 + R.drawable.list_white_up, // 列表第一项白色背景 + R.drawable.list_green_up, // 列表第一项绿色背景 + R.drawable.list_red_up // 列表第一项红色背景 + }; + + 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, // 列表最后一项绿色背景 + R.drawable.list_red_down, // 列表最后一项红色背景 + }; + + private final static int [] BG_SINGLE_RESOURCES = new int [] { + R.drawable.list_yellow_single, // 单一项黄色背景 + R.drawable.list_blue_single, // 单一项蓝色背景 + R.drawable.list_white_single, // 单一项白色背景 + R.drawable.list_green_single, // 单一项绿色背景 + R.drawable.list_red_single // 单一项红色背景 + }; + + 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; + // 返回文件夹专用背景 + } + } + + public static class WidgetBgResources { + // 小部件背景资源类 + private final static int [] BG_2X_RESOURCES = new int [] { + R.drawable.widget_2x_yellow, // 2x2小部件黄色背景 + R.drawable.widget_2x_blue, // 2x2小部件蓝色背景 + R.drawable.widget_2x_white, // 2x2小部件白色背景 + R.drawable.widget_2x_green, // 2x2小部件绿色背景 + R.drawable.widget_2x_red, // 2x2小部件红色背景 + }; + + public static int getWidget2xBgResource(int id) { + // 获取2x2小部件背景资源 + return BG_2X_RESOURCES[id]; + } + + private final static int [] BG_4X_RESOURCES = new int [] { + R.drawable.widget_4x_yellow, // 4x4小部件黄色背景 + R.drawable.widget_4x_blue, // 4x4小部件蓝色背景 + R.drawable.widget_4x_white, // 4x4小部件白色背景 + R.drawable.widget_4x_green, // 4x4小部件绿色背景 + R.drawable.widget_4x_red // 4x4小部件红色背景 + }; + + public static int getWidget4xBgResource(int id) { + // 获取4x4小部件背景资源 + return BG_4X_RESOURCES[id]; + } + } + + public static class TextAppearanceResources { + // 文本外观资源类 + private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] { + R.style.TextAppearanceNormal, // 正常文本样式 + R.style.TextAppearanceMedium, // 中等文本样式 + R.style.TextAppearanceLarge, // 大文本样式 + R.style.TextAppearanceSuper // 超大文本样式 + }; + + public static int getTexAppearanceResource(int id) { + // 获取文本外观资源(方法名拼写错误:Tex应为Text) + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ + // 修复bug:存储在shared preference中的资源ID可能大于资源数组长度 + // 在这种情况下,返回默认字体大小 + if (id >= TEXTAPPEARANCE_RESOURCES.length) { + return BG_DEFAULT_FONT_SIZE; + // 返回默认字体大小 + } + return TEXTAPPEARANCE_RESOURCES[id]; + // 返回对应ID的资源 + } + + public static int getResourcesSize() { + // 获取资源数组大小 + return TEXTAPPEARANCE_RESOURCES.length; + } + } +} \ No newline at end of file diff --git a/src/ui/AlarmAlertActivity.java b/src/ui/AlarmAlertActivity.java new file mode 100644 index 0000000..5cd917e --- /dev/null +++ b/src/ui/AlarmAlertActivity.java @@ -0,0 +1,226 @@ +/* + * 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.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; + +import java.io.IOException; + + +public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { +// 闹钟提醒活动,继承Activity并实现点击和取消监听器接口 + + private long mNoteId; + // 笔记ID + + private String mSnippet; + // 笔记摘要 + + private static final int SNIPPET_PREW_MAX_LEN = 60; + // 摘要预览最大长度(注意:PREW应为PREVIEW) + + MediaPlayer mPlayer; + // 媒体播放器,用于播放闹钟声音 + + @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(); + // 获取启动意图 + + try { + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + // 从URI路径中提取笔记ID(第二个路径段) + mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); + // 根据笔记ID获取摘要 + 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(); + // 创建媒体播放器实例 + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + // 如果笔记在数据库中可见(不在垃圾箱中) + showActionDialog(); + // 显示操作对话框 + playAlarmSound(); + // 播放闹钟声音 + } else { + finish(); + // 否则结束活动 + } + } + + private boolean isScreenOn() { + // 检查屏幕是否亮着 + PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); + // 获取电源管理器服务 + return pm.isScreenOn(); + // 返回屏幕状态 + } + + 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); + // 设置数据源 + mPlayer.prepare(); + // 准备播放器 + mPlayer.setLooping(true); + // 设置循环播放 + mPlayer.start(); + // 开始播放 + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // 参数异常 + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // 安全异常 + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // 非法状态异常 + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + // IO异常 + } + } + + private void showActionDialog() { + // 显示操作对话框 + AlertDialog.Builder dialog = new AlertDialog.Builder(this); + // 创建对话框构建器 + dialog.setTitle(R.string.app_name); + // 设置标题为应用名称 + dialog.setMessage(mSnippet); + // 设置消息为笔记摘要 + dialog.setPositiveButton(R.string.notealert_ok, this); + // 设置确定按钮 + if (isScreenOn()) { + // 如果屏幕亮着 + dialog.setNegativeButton(R.string.notealert_enter, this); + // 设置进入按钮(查看笔记) + } + dialog.show().setOnDismissListener(this); + // 显示对话框并设置取消监听器 + } + + public void onClick(DialogInterface dialog, int which) { + // 对话框按钮点击回调 + switch (which) { + case DialogInterface.BUTTON_NEGATIVE: + // 如果是负按钮(进入按钮) + Intent intent = new Intent(this, NoteEditActivity.class); + // 创建编辑活动意图 + intent.setAction(Intent.ACTION_VIEW); + // 设置操作为查看 + intent.putExtra(Intent.EXTRA_UID, mNoteId); + // 添加笔记ID作为额外数据 + startActivity(intent); + // 启动编辑活动 + break; + default: + break; + } + } + + public void onDismiss(DialogInterface dialog) { + // 对话框取消回调 + stopAlarmSound(); + // 停止闹钟声音 + finish(); + // 结束活动 + } + + private void stopAlarmSound() { + // 停止闹钟声音 + if (mPlayer != null) { + mPlayer.stop(); + // 停止播放 + mPlayer.release(); + // 释放播放器资源 + mPlayer = null; + // 设为null + } + } +} \ No newline at end of file diff --git a/src/ui/AlarmInitReceiver.java b/src/ui/AlarmInitReceiver.java new file mode 100644 index 0000000..f3c38fd --- /dev/null +++ b/src/ui/AlarmInitReceiver.java @@ -0,0 +1,97 @@ +/* + * 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; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +public class AlarmInitReceiver extends BroadcastReceiver { +// 闹钟初始化广播接收器,继承BroadcastReceiver + + // 查询投影列数组 + 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; + // 提醒日期列索引 + + @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 + Intent sender = new Intent(context, AlarmReceiver.class); + // 创建指向AlarmReceiver的Intent + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); + // 设置数据URI为笔记URI + + // 创建延迟Intent + PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); + // 创建广播PendingIntent + + // 获取闹钟管理器 + AlarmManager alermManager = (AlarmManager) context + .getSystemService(Context.ALARM_SERVICE); + // 获取闹钟服务(注意:alermManager应为alarmManager) + + // 设置闹钟 + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + // 设置实时时钟唤醒闹钟 + } while (c.moveToNext()); + // 继续处理下一行 + } + c.close(); + // 关闭游标 + } + } +} \ No newline at end of file diff --git a/src/ui/AlarmReceiver.java b/src/ui/AlarmReceiver.java new file mode 100644 index 0000000..54e503b --- /dev/null +++ b/src/ui/AlarmReceiver.java @@ -0,0 +1,30 @@ +/* + * 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.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +public class AlarmReceiver extends BroadcastReceiver { + @Override + public void onReceive(Context context, Intent intent) { + intent.setClass(context, AlarmAlertActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + } +} diff --git a/src/ui/DateTimePicker.java b/src/ui/DateTimePicker.java new file mode 100644 index 0000000..c712bbb --- /dev/null +++ b/src/ui/DateTimePicker.java @@ -0,0 +1,593 @@ +/* + * 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; +import java.util.Calendar; + +import net.micode.notes.R; + + +import android.content.Context; +import android.text.format.DateFormat; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.NumberPicker; + +public class DateTimePicker extends FrameLayout { +// 日期时间选择器,继承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; + // 分钟选择器最小值(拼写错误:MINUT应为MINUTE) + private static final int MINUT_SPINNER_MAX_VAL = 59; + // 分钟选择器最大值 + private static final int AMPM_SPINNER_MIN_VAL = 0; + // AM/PM选择器最小值 + private static final int AMPM_SPINNER_MAX_VAL = 1; + // AM/PM选择器最大值 + + // 组件 + private final NumberPicker mDateSpinner; + // 日期选择器 + private final NumberPicker mHourSpinner; + // 小时选择器 + private final NumberPicker mMinuteSpinner; + // 分钟选择器 + private final NumberPicker mAmPmSpinner; + // AM/PM选择器 + 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) { + // 下午11点变12点,日期加1天 + 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) { + // 上午12点变11点,日期减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) { + // 12点和11点切换时,改变AM/PM状态 + mIsAm = !mIsAm; + updateAmPmControl(); + } + } else { + // 24小时制处理逻辑 + if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { + // 23点变0点,日期加1天 + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, 1); + isDateChanged = true; + } else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) { + // 0点变23点,日期减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); + // 计算24小时制的小时数 + 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) { + // 59分变0分,小时加1 + offset += 1; + } else if (oldVal == minValue && newVal == maxValue) { + // 0分变59分,小时减1 + 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(); + } + }; + + // AM/PM变化监听器 + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; + if (mIsAm) { + // AM变PM,小时减12 + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + // PM变AM,小时加12 + 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); + } + + // 构造方法 + public DateTimePicker(Context context) { + this(context, System.currentTimeMillis()); + // 使用当前时间 + } + + public DateTimePicker(Context context, long date) { + this(context, date, DateFormat.is24HourFormat(context)); + // 使用系统设置判断是否为24小时制 + } + + public DateTimePicker(Context context, long date, boolean is24HourView) { + super(context); + mDate = Calendar.getInstance(); + // 创建日历实例 + mInitialising = true; + // 标记为初始化中 + mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; + // 根据当前小时判断AM/PM + 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); + // 长按更新间隔100ms + mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + + String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); + // 获取AM/PM字符串(本地化) + mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); + mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); + mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); + mAmPmSpinner.setDisplayedValues(stringsForAmPm); + // 设置显示值为AM/PM字符串 + mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); + + // 更新控件到初始状态 + updateDateControl(); + updateHourControl(); + updateAmPmControl(); + + set24HourView(is24HourView); + // 设置24小时制视图 + + // 设置为当前时间 + setCurrentDate(date); + + setEnabled(isEnabled()); + + // 设置内容描述 + mInitialising = false; + // 初始化完成 + } + + @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; + } + + /** + * Get the current date in millis + * + * @return the current date in millis + */ + // 获取当前时间的毫秒数 + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + } + + /** + * Set the current date + * + * @param date The current date in millis + */ + // 设置当前日期(毫秒数) + 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)); + } + + /** + * Set the current date + * + * @param year The current year + * @param month The current month + * @param dayOfMonth The current dayOfMonth + * @param hourOfDay The current hourOfDay + * @param minute The current minute + */ + // 设置当前日期(具体参数) + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + } + + /** + * Get current year + * + * @return The current year + */ + // 获取当前年 + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * Set current year + * + * @param year The current year + */ + // 设置当前年 + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + // 如果非初始化且年份相同,直接返回 + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current month in the year + * + * @return The current month in the year + */ + // 获取当前月 + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * Set current month in the year + * + * @param month The month in the year + */ + // 设置当前月 + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current day of the month + * + * @return The day of the month + */ + // 获取当前日 + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * Set current day of the month + * + * @param dayOfMonth The day of the month + */ + // 设置当前日 + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current hour in 24 hour mode, in the range (0~23) + * @return The current hour in 24 hour mode + */ + // 获取24小时制的小时(0-23) + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + // 获取当前小时(根据12/24小时制转换) + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + // 24小时制直接返回 + } else { + int hour = getCurrentHourOfDay(); + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + // 下午:13-23转1-11 + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + // 上午:0点转12点,其他不变 + } + } + } + + /** + * Set current hour in 24 hour mode, in the range (0~23) + * + * @param hourOfDay + */ + // 设置24小时制的小时 + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + if (!mIs24HourView) { + // 12小时制额外处理 + if (hourOfDay >= HOURS_IN_HALF_DAY) { + mIsAm = false; + // 下午 + if (hourOfDay > HOURS_IN_HALF_DAY) { + hourOfDay -= HOURS_IN_HALF_DAY; + } + } else { + mIsAm = true; + // 上午 + if (hourOfDay == 0) { + hourOfDay = HOURS_IN_HALF_DAY; + // 0点转12点 + } + } + updateAmPmControl(); + } + mHourSpinner.setValue(hourOfDay); + onDateTimeChanged(); + } + + /** + * Get currentMinute + * + * @return The Current Minute + */ + // 获取当前分钟 + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * Set current minute + */ + // 设置当前分钟 + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } + + /** + * @return true if this is in 24 hour view else false. + */ + // 判断是否为24小时制 + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * Set whether in 24 hour or AM/PM mode. + * + * @param is24HourView True for 24 hour mode. False for AM/PM mode. + */ + // 设置24小时制视图 + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); + // 24小时制隐藏AM/PM选择器 + 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); + // 从当前日期向前推4天 + 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); + // 设置当前为中间值(第4天) + mDateSpinner.invalidate(); + // 重绘 + } + + // 更新AM/PM控件 + private void updateAmPmControl() { + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + // 24小时制隐藏 + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + // AM对应0,PM对应1 + 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); + // 24小时制:0-23 + } else { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); + // 12小时制:1-12 + } + } + + /** + * Set the callback that indicates the 'Set' button has been pressed. + * @param callback the callback, if null will do nothing + */ + // 设置日期时间变化监听器 + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } + + // 触发日期时间变化事件 + private void onDateTimeChanged() { + if (mOnDateTimeChangedListener != null) { + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + } + } +} \ No newline at end of file diff --git a/src/ui/DateTimePickerDialog.java b/src/ui/DateTimePickerDialog.java new file mode 100644 index 0000000..2a195ea --- /dev/null +++ b/src/ui/DateTimePickerDialog.java @@ -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 java.util.Calendar; + +import net.micode.notes.R; +import net.micode.notes.ui.DateTimePicker; +import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +public class DateTimePickerDialog extends AlertDialog implements OnClickListener { +// 日期时间选择器对话框,继承AlertDialog并实现点击监听器 + + private Calendar mDate = Calendar.getInstance(); + // 日期日历对象 + private boolean mIs24HourView; + // 是否为24小时制标志 + private OnDateTimeSetListener mOnDateTimeSetListener; + // 日期时间设置监听器 + private DateTimePicker mDateTimePicker; + // 日期时间选择器组件 + + public interface OnDateTimeSetListener { + // 日期时间设置监听器接口 + void OnDateTimeSet(AlertDialog dialog, long date); + // 日期时间设置回调方法 + } + + public DateTimePickerDialog(Context context, long date) { + // 构造方法 + super(context); + mDateTimePicker = new DateTimePicker(context); + // 创建日期时间选择器 + setView(mDateTimePicker); + // 设置对话框视图 + mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { + // 设置日期时间变化监听器 + public void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + // 当日期时间选择器改变时更新mDate对象 + 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; + } + + public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { + // 设置日期时间设置监听器 + mOnDateTimeSetListener = callBack; + } + + 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; + // 这里有个bug:两边都是DateUtils.FORMAT_24HOUR,应该是三目运算符写错了 + // 应该为:flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR; + + setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); + // 设置格式化后的标题 + } + + public void onClick(DialogInterface arg0, int arg1) { + // 点击按钮回调 + if (mOnDateTimeSetListener != null) { + mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); + // 调用日期时间设置回调 + } + } + +} \ No newline at end of file diff --git a/src/ui/DropdownMenu.java b/src/ui/DropdownMenu.java new file mode 100644 index 0000000..755d073 --- /dev/null +++ b/src/ui/DropdownMenu.java @@ -0,0 +1,74 @@ +/* + * 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.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; + +// 下拉菜单控件封装类 +public class DropdownMenu { + // 触发下拉的按钮控件 + private Button mButton; + // Android原生弹出菜单 + private PopupMenu mPopupMenu; + // 菜单项容器 + private Menu mMenu; + + // 构造方法:传入上下文、按钮和菜单资源ID + public DropdownMenu(Context context, Button button, int menuId) { + mButton = button; + // 设置按钮下拉图标样式 + mButton.setBackgroundResource(R.drawable.dropdown_icon); + // 创建弹出菜单(以按钮为锚点) + mPopupMenu = new PopupMenu(context, mButton); + // 获取菜单对象 + mMenu = mPopupMenu.getMenu(); + // 加载菜单布局 + mPopupMenu.getMenuInflater().inflate(menuId, mMenu); + // 点击按钮显示下拉菜单 + mButton.setOnClickListener(new OnClickListener() { + public void onClick(View v) { + mPopupMenu.show(); + } + }); + } + + // 设置菜单项点击监听器 + public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { + if (mPopupMenu != null) { + mPopupMenu.setOnMenuItemClickListener(listener); + } + } + + // 根据ID查找菜单项 + public MenuItem findItem(int id) { + return mMenu.findItem(id); + } + + // 设置按钮显示文本 + public void setTitle(CharSequence title) { + mButton.setText(title); + } +} \ No newline at end of file diff --git a/src/ui/FoldersListAdapter.java b/src/ui/FoldersListAdapter.java new file mode 100644 index 0000000..785e53b --- /dev/null +++ b/src/ui/FoldersListAdapter.java @@ -0,0 +1,93 @@ +/* + * 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.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +```java +// 文件夹列表适配器,继承CursorAdapter用于数据库游标数据展示 +public class FoldersListAdapter extends CursorAdapter { + // 数据库查询投影字段(需要查询的列) + public static final String [] PROJECTION = { + NoteColumns.ID, // 文件夹ID列 + NoteColumns.SNIPPET // 文件夹名称列(使用SNIPPET字段存储名称) + }; + + // 列索引常量,提高代码可读性 + 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: 待补充初始化代码 + } + + // 创建新视图项(列表项) + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new FolderListItem(context); // 创建自定义列表项视图 + } + + // 绑定数据到视图项 + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof FolderListItem) { + // 判断是否为根文件夹:根文件夹显示特殊名称,否则显示文件夹名称 + String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + ((FolderListItem) view).bind(folderName); // 绑定名称到视图 + } + } + + // 根据位置获取文件夹名称(供外部调用) + 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 { + private TextView mName; // 文件夹名称显示控件 + + // 构造方法:初始化列表项布局 + public FolderListItem(Context context) { + super(context); + inflate(context, R.layout.folder_list_item, this); // 加载布局文件 + mName = (TextView) findViewById(R.id.tv_folder_name); // 获取文本控件引用 + } + + // 绑定文件夹名称到文本控件 + public void bind(String name) { + mName.setText(name); + } + } +} +``` \ No newline at end of file diff --git a/src/ui/NoteEditActivity.java b/src/ui/NoteEditActivity.java new file mode 100644 index 0000000..7bb2e52 --- /dev/null +++ b/src/ui/NoteEditActivity.java @@ -0,0 +1,896 @@ +/* + * 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.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +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.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +```java +// 便签编辑活动,实现多种监听器接口 +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + + // 头部视图持有者,用于缓存视图引用 + private class HeadViewHolder { + public TextView tvModified; // 修改时间显示 + public ImageView ivAlertIcon; // 提醒图标 + public TextView tvAlertDate; // 提醒日期显示 + public ImageView ibSetBgColor; // 设置背景颜色按钮 + } + + // 背景颜色选择器按钮ID与颜色ID的映射 + private static final Map sBgSelectorBtnsMap = new HashMap(); + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW); + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED); + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE); + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN); + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE); + } + + // 背景颜色ID与选中状态视图ID的映射 + private static final Map sBgSelectorSelectionMap = new HashMap(); + static { + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); + } + + // 字体大小选择器视图ID与字体大小ID的映射 + private static final Map sFontSizeBtnsMap = new HashMap(); + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + } + + // 字体大小ID与选中状态视图ID的映射 + private static final Map sFontSelectorSelectionMap = new HashMap(); + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); + } + + private static final String TAG = "NoteEditActivity"; // 日志标签 + + // 视图引用 + private HeadViewHolder mNoteHeaderHolder; // 头部视图持有者 + private View mHeadViewPanel; // 头部面板 + private View mNoteBgColorSelector; // 背景颜色选择器 + private View mFontSizeSelector; // 字体大小选择器 + private EditText mNoteEditor; // 便签编辑框 + private View mNoteEditorPanel; // 编辑面板 + private WorkingNote mWorkingNote; // 当前操作的便签对象 + + // 偏好设置相关 + private SharedPreferences mSharedPrefs; // 共享偏好设置 + private int mFontSizeId; // 当前字体大小ID + private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; // 字体大小偏好键 + + // 常量定义 + private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; // 快捷方式标题最大长度 + public static final String TAG_CHECKED = String.valueOf('\u221A'); // 复选框选中符号(√) + public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); // 复选框未选中符号(□) + + // 列表模式相关 + private LinearLayout mEditTextList; // 列表模式编辑容器 + private String mUserQuery; // 用户搜索查询词 + private Pattern mPattern; // 搜索高亮模式 + + // 创建活动 + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + this.setContentView(R.layout.note_edit); // 设置布局 + + // 初始化活动状态,失败则结束 + if (savedInstanceState == null && !initActivityState(getIntent())) { + finish(); + return; + } + initResources(); // 初始化资源 + } + + // 恢复实例状态(内存不足时可能被杀死) + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + // 从保存的状态中恢复便签ID + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + // 初始化活动状态 + private boolean initActivityState(Intent intent) { + mWorkingNote = null; + + // 处理查看便签的请求 + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) { + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + // 处理从搜索结果进入的情况 + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) { + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); + } + + // 检查便签是否存在 + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) { + Intent jump = new Intent(this, NotesListActivity.class); + startActivity(jump); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + mWorkingNote = WorkingNote.load(this, noteId); // 加载便签 + if (mWorkingNote == null) { + Log.e(TAG, "load note failed with note id" + noteId); + finish(); + return false; + } + } + // 隐藏软键盘 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); + + } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) { + // 新建或编辑便签 + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this)); + + // 解析通话记录便签 + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0); + if (callDate != 0 && phoneNumber != null) { + if (TextUtils.isEmpty(phoneNumber)) { + Log.w(TAG, "The call record number is null"); + } + long noteId = 0; + // 查找已存在的通话记录便签 + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(), + phoneNumber, callDate)) > 0) { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else { + // 创建新的通话记录便签 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + // 创建普通便签 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + + // 显示软键盘 + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support"); + finish(); + return false; + } + mWorkingNote.setOnSettingStatusChangedListener(this); // 设置监听器 + return true; + } + + // 活动恢复时调用 + @Override + protected void onResume() { + super.onResume(); + initNoteScreen(); // 初始化便签界面 + } + + // 初始化便签界面显示 + private void initNoteScreen() { + // 设置字体大小 + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId)); + + // 根据模式初始化界面 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + switchToListMode(mWorkingNote.getContent()); // 切换到列表模式 + } else { + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mNoteEditor.setSelection(mNoteEditor.getText().length()); // 光标移至末尾 + } + + // 隐藏所有背景选择器选中状态 + for (Integer id : sBgSelectorSelectionMap.keySet()) { + findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); + } + + // 设置背景 + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + + // 设置修改时间 + mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, + mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE + | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME + | DateUtils.FORMAT_SHOW_YEAR)); + + showAlertHeader(); // 显示提醒头部 + } + + // 显示提醒头部信息 + private void showAlertHeader() { + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis(); + if (time > mWorkingNote.getAlertDate()) { + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); // 提醒已过期 + } else { + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS)); // 相对时间 + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE); + } else { + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE); + }; + } + + // 处理新Intent(例如从搜索进入) + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + initActivityState(intent); // 重新初始化活动状态 + } + + // 保存实例状态 + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + // 新便签需要先保存以生成ID + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); // 保存便签ID + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + // 分发触摸事件,用于隐藏选择器 + @Override + public boolean dispatchTouchEvent(MotionEvent ev) { + // 点击背景颜色选择器外部时隐藏 + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mNoteBgColorSelector, ev)) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } + + // 点击字体大小选择器外部时隐藏 + if (mFontSizeSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mFontSizeSelector, ev)) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return super.dispatchTouchEvent(ev); + } + + // 判断触摸点是否在视图范围内 + private boolean inRangeOfView(View view, MotionEvent ev) { + int []location = new int[2]; + view.getLocationOnScreen(location); + int x = location[0]; + int y = location[1]; + if (ev.getX() < x + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + } + return true; + } + + // 初始化资源(视图绑定等) + private void initResources() { + // 绑定头部视图 + mHeadViewPanel = findViewById(R.id.note_title); + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); // 设置点击监听 + + // 绑定编辑相关视图 + mNoteEditor = (EditText) findViewById(R.id.note_edit_view); + mNoteEditorPanel = findViewById(R.id.sv_note_edit); + + // 绑定背景颜色选择器并设置点击监听 + mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); + for (int id : sBgSelectorBtnsMap.keySet()) { + ImageView iv = (ImageView) findViewById(id); + iv.setOnClickListener(this); + } + + // 绑定字体大小选择器并设置点击监听 + mFontSizeSelector = findViewById(R.id.font_size_selector); + for (int id : sFontSizeBtnsMap.keySet()) { + View view = findViewById(id); + view.setOnClickListener(this); + }; + + // 初始化偏好设置 + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + // 修复字体大小ID超出范围的bug + if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) { + mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; + } + + mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); // 列表模式容器 + } + + // 活动暂停时保存便签 + @Override + protected void onPause() { + super.onPause(); + if(saveNote()) { + Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length()); + } + clearSettingState(); // 清理设置状态 + } + + // 更新桌面小部件 + private void updateWidget() { + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + // 根据小部件类型设置对应的接收器 + if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class); + } else if (mWorkingNote.getWidgetType() == 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[] { + mWorkingNote.getWidgetId() // 小部件ID + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); + } + + // 点击事件处理 + public void onClick(View v) { + int id = v.getId(); + if (id == R.id.btn_set_bg_color) { + // 显示背景颜色选择器 + mNoteBgColorSelector.setVisibility(View.VISIBLE); + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + } else if (sBgSelectorBtnsMap.containsKey(id)) { + // 背景颜色选择 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.GONE); + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); // 设置新背景颜色 + mNoteBgColorSelector.setVisibility(View.GONE); // 隐藏选择器 + } else if (sFontSizeBtnsMap.containsKey(id)) { + // 字体大小选择 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); + mFontSizeId = sFontSizeBtnsMap.get(id); // 设置新字体大小 + mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); // 保存偏好 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + // 根据模式更新字体显示 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + getWorkingText(); + switchToListMode(mWorkingNote.getContent()); + } else { + mNoteEditor.setTextAppearance(this, + TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + } + mFontSizeSelector.setVisibility(View.GONE); // 隐藏选择器 + } + } + + // 返回键处理 + @Override + public void onBackPressed() { + if(clearSettingState()) { // 如果隐藏了选择器,则不退出 + return; + } + + saveNote(); // 保存便签 + super.onBackPressed(); // 执行默认返回 + } + + // 清理设置状态(隐藏选择器) + private boolean clearSettingState() { + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return false; + } + + // 背景颜色改变回调 + public void onBackgroundColorChanged() { + // 显示新背景颜色的选中状态 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE); + // 更新背景 + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + } + + // 准备选项菜单 + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + if (isFinishing()) { + return true; + } + clearSettingState(); // 清理设置状态 + menu.clear(); // 清除旧菜单 + + // 根据便签类型加载不同菜单 + if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) { + getMenuInflater().inflate(R.menu.call_note_edit, menu); // 通话记录菜单 + } else { + getMenuInflater().inflate(R.menu.note_edit, menu); // 普通便签菜单 + } + + // 根据列表模式设置菜单项文本 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); + } else { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); + } + + // 根据是否有提醒显示/隐藏菜单项 + if (mWorkingNote.hasClockAlert()) { + menu.findItem(R.id.menu_alert).setVisible(false); + } else { + menu.findItem(R.id.menu_delete_remind).setVisible(false); + } + return true; + } + + // 菜单项选择处理 + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case R.id.menu_new_note: + createNewNote(); // 新建便签 + break; + case R.id.menu_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_note)); + builder.setPositiveButton(android.R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + deleteCurrentNote(); // 删除当前便签 + finish(); + } + }); + builder.setNegativeButton(android.R.string.cancel, null); + builder.show(); + break; + case R.id.menu_font_size: + // 显示字体大小选择器 + mFontSizeSelector.setVisibility(View.VISIBLE); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + break; + case R.id.menu_list_mode: + // 切换列表模式 + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ? + TextNote.MODE_CHECK_LIST : 0); + break; + case R.id.menu_share: + // 分享便签 + getWorkingText(); + sendTo(this, mWorkingNote.getContent()); + break; + case R.id.menu_send_to_desktop: + // 发送到桌面快捷方式 + sendToDesktop(); + break; + case R.id.menu_alert: + // 设置提醒 + setReminder(); + break; + case R.id.menu_delete_remind: + // 删除提醒 + mWorkingNote.setAlertDate(0, false); + break; + default: + break; + } + return true; + } + + // 设置提醒时间 + private void setReminder() { + DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis()); + d.setOnDateTimeSetListener(new OnDateTimeSetListener() { + public void OnDateTimeSet(AlertDialog dialog, long date) { + mWorkingNote.setAlertDate(date, true); // 设置提醒日期 + } + }); + d.show(); + } + + // 分享便签内容 + private void sendTo(Context context, String info) { + Intent intent = new Intent(Intent.ACTION_SEND); + intent.putExtra(Intent.EXTRA_TEXT, info); + intent.setType("text/plain"); // 纯文本类型 + context.startActivity(intent); + } + + // 创建新便签 + private void createNewNote() { + saveNote(); // 先保存当前便签 + finish(); // 结束当前活动 + // 启动新的便签编辑活动 + Intent intent = new Intent(this, NoteEditActivity.class); + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); + startActivity(intent); + } + + // 删除当前便签 + private void deleteCurrentNote() { + if (mWorkingNote.existInDatabase()) { + HashSet ids = new HashSet(); + long id = mWorkingNote.getNoteId(); + if (id != Notes.ID_ROOT_FOLDER) { + ids.add(id); + } else { + Log.d(TAG, "Wrong note id, should not happen"); + } + // 根据同步模式选择删除方式 + if (!isSyncMode()) { + if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { + Log.e(TAG, "Delete Note error"); + } + } else { + if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + } + mWorkingNote.markDeleted(true); // 标记为已删除 + } + + // 检查是否为同步模式 + private boolean isSyncMode() { + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + } + + // 提醒时间改变回调 + public void onClockAlertChanged(long date, boolean set) { + // 未保存的便签需要先保存 + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + if (mWorkingNote.getNoteId() > 0) { + // 设置闹钟提醒 + Intent intent = new Intent(this, AlarmReceiver.class); + intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); + showAlertHeader(); // 更新提醒显示 + if(!set) { + alarmManager.cancel(pendingIntent); // 取消提醒 + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); // 设置提醒 + } + } else { + // 空便签不能设置提醒 + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + // 小部件改变回调 + public void onWidgetChanged() { + updateWidget(); // 更新小部件 + } + + // 列表模式:删除文本项回调 + public void onEditTextDelete(int index, String text) { + int childCount = mEditTextList.getChildCount(); + if (childCount == 1) { // 至少保留一项 + return; + } + + // 更新后续项的索引 + for (int i = index + 1; i < childCount; i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i - 1); + } + + mEditTextList.removeViewAt(index); // 删除视图 + NoteEditText edit = null; + // 确定焦点位置 + if(index == 0) { + edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( + R.id.et_edit_text); + } else { + edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( + R.id.et_edit_text); + } + int length = edit.length(); + edit.append(text); // 将删除的文本追加到前一项 + edit.requestFocus(); + edit.setSelection(length); + } + + // 列表模式:回车换行回调 + public void onEditTextEnter(int index, String text) { + if(index > mEditTextList.getChildCount()) { + Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); + } + + View view = getListItem(text, index); // 创建新列表项 + mEditTextList.addView(view, index); // 插入视图 + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.requestFocus(); + edit.setSelection(0); + // 更新后续项的索引 + for (int i = index + 1; i < mEditTextList.getChildCount(); i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + // 切换到列表模式 + private void switchToListMode(String text) { + mEditTextList.removeAllViews(); // 清除旧视图 + String[] items = text.split("\n"); // 按换行符分割 + int index = 0; + for (String item : items) { + if(!TextUtils.isEmpty(item)) { + mEditTextList.addView(getListItem(item, index)); // 添加列表项 + index++; + } + } + mEditTextList.addView(getListItem("", index)); // 添加空项用于输入 + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); // 聚焦 + + mNoteEditor.setVisibility(View.GONE); // 隐藏普通编辑器 + mEditTextList.setVisibility(View.VISIBLE); // 显示列表容器 + } + + // 获取搜索高亮结果 + private Spannable getHighlightQueryResult(String fullText, String userQuery) { + SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); + if (!TextUtils.isEmpty(userQuery)) { + mPattern = Pattern.compile(userQuery); // 编译搜索模式 + Matcher m = mPattern.matcher(fullText); + int start = 0; + // 为所有匹配项添加高亮背景 + while (m.find(start)) { + spannable.setSpan( + new BackgroundColorSpan(this.getResources().getColor( + R.color.user_query_highlight)), m.start(), m.end(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + start = m.end(); + } + } + return spannable; + } + + // 获取列表项视图 + private View getListItem(String item, int index) { + View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); + final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); + // 复选框状态改变监听 + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + if (isChecked) { + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); // 添加删除线 + } else { + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); // 恢复正常 + } + } + }); + + // 解析复选框状态标记 + if (item.startsWith(TAG_CHECKED)) { + cb.setChecked(true); + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + item = item.substring(TAG_CHECKED.length(), item.length()).trim(); // 移除标记 + } else if (item.startsWith(TAG_UNCHECKED)) { + cb.setChecked(false); + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); // 移除标记 + } + + edit.setOnTextViewChangeListener(this); // 设置文本变化监听 + edit.setIndex(index); // 设置索引 + edit.setText(getHighlightQueryResult(item, mUserQuery)); // 设置文本(带高亮) + return view; + } + + // 文本变化回调(列表模式) + public void onTextChange(int index, boolean hasText) { + if (index >= mEditTextList.getChildCount()) { + Log.e(TAG, "Wrong index, should not happen"); + return; + } + // 根据是否有文本显示/隐藏复选框 + if(hasText) { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); + } else { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); + } + } + + // 列表模式改变回调 + public void onCheckListModeChanged(int oldMode, int newMode) { + if (newMode == TextNote.MODE_CHECK_LIST) { + // 切换到列表模式 + switchToListMode(mNoteEditor.getText().toString()); + } else { + // 切换到普通模式 + if (!getWorkingText()) { + // 移除未选中标记 + mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", + "")); + } + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mEditTextList.setVisibility(View.GONE); // 隐藏列表 + mNoteEditor.setVisibility(View.VISIBLE); // 显示编辑器 + } + } + + // 获取工作文本(当前编辑内容) + private boolean getWorkingText() { + boolean hasChecked = false; + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + // 列表模式:拼接所有项 + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mEditTextList.getChildCount(); i++) { + View view = mEditTextList.getChildAt(i); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + if (!TextUtils.isEmpty(edit.getText())) { + if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { + sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); + hasChecked = true; + } else { + sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); + } + } + } + mWorkingNote.setWorkingText(sb.toString()); + } else { + // 普通模式:直接获取编辑器文本 + mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); + } + return hasChecked; + } + + // 保存便签 + private boolean saveNote() { + getWorkingText(); // 获取当前文本 + boolean saved = mWorkingNote.saveNote(); // 保存到数据库 + if (saved) { + setResult(RESULT_OK); // 设置返回结果 + } + return saved; + } + + // 发送到桌面快捷方式 + private void sendToDesktop() { + // 确保便签已保存 + if (!mWorkingNote.existInDatabase()) { + saveNote(); + } + + if (mWorkingNote.getNoteId() > 0) { + // 创建快捷方式Intent + Intent sender = new Intent(); + Intent shortcutIntent = new Intent(this, NoteEditActivity.class); + shortcutIntent.setAction(Intent.ACTION_VIEW); + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); // 快捷方式名称 + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); // 图标 + sender.putExtra("duplicate", true); // 允许 \ No newline at end of file diff --git a/src/ui/NoteEditText.java b/src/ui/NoteEditText.java new file mode 100644 index 0000000..c880f99 --- /dev/null +++ b/src/ui/NoteEditText.java @@ -0,0 +1,235 @@ +/* + * 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.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; + +import java.util.HashMap; +import java.util.Map; + +```java +// 自定义便签编辑文本控件,扩展EditText功能 +public class NoteEditText extends EditText { + private static final String TAG = "NoteEditText"; // 日志标签 + + private int mIndex; // 当前编辑框在列表中的索引 + private int mSelectionStartBeforeDelete; // 删除前的光标起始位置 + + // URL协议常量 + private static final String SCHEME_TEL = "tel:" ; // 电话协议 + private static final String SCHEME_HTTP = "http:" ; // HTTP协议 + private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议 + + // 协议与操作字符串资源的映射 + private static final Map sSchemaActionResMap = new HashMap(); + static { + sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话链接 + sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网页链接 + sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮件链接 + } + + // 文本变化监听器接口,由NoteEditActivity实现 + public interface OnTextViewChangeListener { + /** + * 删除当前编辑框(当按删除键且文本为空时) + */ + void onEditTextDelete(int index, String text); + + /** + * 在当前编辑框后添加新编辑框(当按回车键时) + */ + void onEditTextEnter(int index, String text); + + /** + * 文本变化时显示/隐藏选项 + */ + void onTextChange(int index, boolean hasText); + } + + private OnTextViewChangeListener mOnTextViewChangeListener; // 监听器引用 + + // 构造方法1:简单构造 + public NoteEditText(Context context) { + super(context, null); + mIndex = 0; // 默认索引为0 + } + + // 设置当前索引 + public void setIndex(int index) { + mIndex = index; + } + + // 设置文本变化监听器 + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + // 构造方法2:带属性集 + public NoteEditText(Context context, AttributeSet attrs) { + super(context, attrs, android.R.attr.editTextStyle); + } + + // 构造方法3:带属性集和样式 + public NoteEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO: 待补充初始化代码 + } + + // 触摸事件处理:实现精确点击定位 + @Override + public boolean onTouchEvent(MotionEvent event) { + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: // 按下事件 + // 计算触摸点对应的文本偏移量 + int x = (int) event.getX(); + int y = (int) event.getY(); + x -= getTotalPaddingLeft(); // 减去内边距 + y -= getTotalPaddingTop(); + x += getScrollX(); // 加上滚动偏移 + y += getScrollY(); + + Layout layout = getLayout(); + int line = layout.getLineForVertical(y); // 获取垂直方向行号 + int off = layout.getOffsetForHorizontal(line, x); // 获取水平方向偏移 + Selection.setSelection(getText(), off); // 设置选中位置 + break; + } + + return super.onTouchEvent(event); // 调用父类处理 + } + + // 按键按下事件 + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEYCODE_ENTER: // 回车键 + if (mOnTextViewChangeListener != null) { + return false; // 由监听器处理 + } + break; + case KeyEvent.KEYCODE_DEL: // 删除键 + mSelectionStartBeforeDelete = getSelectionStart(); // 保存删除前位置 + break; + default: + break; + } + return super.onKeyDown(keyCode, event); + } + + // 按键释放事件 + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + switch(keyCode) { + case KeyEvent.KEYCODE_DEL: // 删除键释放 + if (mOnTextViewChangeListener != null) { + // 如果在开头删除且不是第一个编辑框,则删除整个编辑框 + if (0 == mSelectionStartBeforeDelete && mIndex != 0) { + mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); + return true; // 已处理 + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + case KeyEvent.KEYCODE_ENTER: // 回车键释放 + if (mOnTextViewChangeListener != null) { + int selectionStart = getSelectionStart(); // 获取光标位置 + // 分割文本:光标后部分作为新编辑框内容 + String text = getText().subSequence(selectionStart, length()).toString(); + setText(getText().subSequence(0, selectionStart)); // 保留光标前部分 + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 插入新编辑框 + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted"); + } + break; + default: + break; + } + return super.onKeyUp(keyCode, event); + } + + // 焦点变化回调 + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + if (mOnTextViewChangeListener != null) { + // 失去焦点且文本为空时隐藏选项,否则显示选项 + if (!focused && TextUtils.isEmpty(getText())) { + mOnTextViewChangeListener.onTextChange(mIndex, false); + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true); + } + } + super.onFocusChanged(focused, direction, previouslyFocusedRect); + } + + // 创建上下文菜单(长按菜单) + @Override + protected void onCreateContextMenu(ContextMenu menu) { + if (getText() instanceof Spanned) { // 检查是否为富文本 + int selStart = getSelectionStart(); // 选择起始位置 + int selEnd = getSelectionEnd(); // 选择结束位置 + + int min = Math.min(selStart, selEnd); // 获取较小值 + int max = Math.max(selStart, selEnd); // 获取较大值 + + // 获取选中范围内的URL链接 + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); + if (urls.length == 1) { // 只有一个链接时 + int defaultResId = 0; + // 根据URL协议类型确定菜单项文本 + for(String schema: sSchemaActionResMap.keySet()) { + if(urls[0].getURL().indexOf(schema) >= 0) { + defaultResId = sSchemaActionResMap.get(schema); + break; + } + } + + if (defaultResId == 0) { + defaultResId = R.string.note_link_other; // 其他类型链接 + } + + // 添加上下文菜单项 + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + // 点击后打开链接 + urls[0].onClick(NoteEditText.this); + return true; + } + }); + } + } + super.onCreateContextMenu(menu); // 调用父类创建默认菜单 + } +} +``` \ No newline at end of file diff --git a/src/ui/NoteItemData.java b/src/ui/NoteItemData.java new file mode 100644 index 0000000..4f65dd1 --- /dev/null +++ b/src/ui/NoteItemData.java @@ -0,0 +1,259 @@ +/* + * 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; + + +```java +// 便签项数据类,封装便签的数据库记录信息 +public class NoteItemData { + // 数据库查询投影字段(需要查询的列) + static final String [] PROJECTION = new String [] { + NoteColumns.ID, // 便签ID + NoteColumns.ALERTED_DATE, // 提醒日期 + NoteColumns.BG_COLOR_ID, // 背景颜色ID + NoteColumns.CREATED_DATE, // 创建日期 + NoteColumns.HAS_ATTACHMENT, // 是否有附件 + NoteColumns.MODIFIED_DATE, // 修改日期 + NoteColumns.NOTES_COUNT, // 子项数量(针对文件夹) + NoteColumns.PARENT_ID, // 父文件夹ID + NoteColumns.SNIPPET, // 便签内容摘要 + NoteColumns.TYPE, // 类型(便签/文件夹) + NoteColumns.WIDGET_ID, // 桌面小部件ID + NoteColumns.WIDGET_TYPE, // 桌面小部件类型 + }; + + // 列索引常量,提高代码可读性 + private static final int ID_COLUMN = 0; // ID列索引 + private static final int ALERTED_DATE_COLUMN = 1; // 提醒日期列索引 + private static final int BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引 + private static final int CREATED_DATE_COLUMN = 3; // 创建日期列索引 + private static final int HAS_ATTACHMENT_COLUMN = 4; // 附件标志列索引 + private static final int MODIFIED_DATE_COLUMN = 5; // 修改日期列索引 + private static final int NOTES_COUNT_COLUMN = 6; // 便签数量列索引 + private static final int PARENT_ID_COLUMN = 7; // 父ID列索引 + private static final int SNIPPET_COLUMN = 8; // 摘要列索引 + private static final int TYPE_COLUMN = 9; // 类型列索引 + private static final int WIDGET_ID_COLUMN = 10; // 小部件ID列索引 + private static final int WIDGET_TYPE_COLUMN = 11; // 小部件类型列索引 + + // 数据字段 + private long mId; // 便签ID + private long mAlertDate; // 提醒日期 + private int mBgColorId; // 背景颜色ID + private long mCreatedDate; // 创建日期 + private boolean mHasAttachment; // 是否有附件 + private long mModifiedDate; // 修改日期 + private int mNotesCount; // 子便签数量(文件夹用) + private long mParentId; // 父文件夹ID + private String mSnippet; // 内容摘要 + private int mType; // 类型:便签/文件夹 + private int mWidgetId; // 桌面小部件ID + private int mWidgetType; // 桌面小部件类型 + private String mName; // 联系人姓名(通话记录用) + private String mPhoneNumber; // 电话号码(通话记录用) + + // 位置状态标志 + private boolean mIsLastItem; // 是否为最后一项 + private boolean mIsFirstItem; // 是否为第一项 + private boolean mIsOnlyOneItem; // 是否只有一项 + private boolean mIsOneNoteFollowingFolder; // 是否是一个便签跟在文件夹后面 + private boolean mIsMultiNotesFollowingFolder;// 是否是多个便签跟在文件夹后面 + + // 构造方法:从Cursor解析数据 + public NoteItemData(Context context, Cursor cursor) { + // 从游标中读取各字段数据 + mId = cursor.getLong(ID_COLUMN); + mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); + mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); + 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; + + // 检查是否是一个/多个便签跟在文件夹后面(用于UI分隔线显示) + 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; // 是否只有一项 + } + + // Getter方法:获取便签ID + public long getId() { + return mId; + } + + // Getter方法:获取提醒日期 + public long getAlertDate() { + return mAlertDate; + } + + // Getter方法:获取创建日期 + public long getCreatedDate() { + return mCreatedDate; + } + + // Getter方法:检查是否有附件 + public boolean hasAttachment() { + return mHasAttachment; + } + + // Getter方法:获取修改日期 + public long getModifiedDate() { + return mModifiedDate; + } + + // Getter方法:获取背景颜色ID + public int getBgColorId() { + return mBgColorId; + } + + // Getter方法:获取父文件夹ID + public long getParentId() { + return mParentId; + } + + // Getter方法:获取子便签数量 + public int getNotesCount() { + return mNotesCount; + } + + // Getter方法:获取文件夹ID(与getParentId相同) + public long getFolderId () { + return mParentId; + } + + // Getter方法:获取类型(便签/文件夹) + public int getType() { + return mType; + } + + // Getter方法:获取桌面小部件类型 + public int getWidgetType() { + return mWidgetType; + } + + // Getter方法:获取桌面小部件ID + public int getWidgetId() { + return mWidgetId; + } + + // Getter方法:获取内容摘要 + 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); + } +} +``` \ No newline at end of file diff --git a/src/ui/NotesListActivity.java b/src/ui/NotesListActivity.java new file mode 100644 index 0000000..d1ff8ab --- /dev/null +++ b/src/ui/NotesListActivity.java @@ -0,0 +1,982 @@ +/* + * 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; + +```java +// 便签列表活动,负责显示和管理便签/文件夹列表 +// 便签列表活动,负责显示和管理便签/文件夹列表 +public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { + // 查询令牌常量 + private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; // 文件夹便签列表查询 + private static final int FOLDER_LIST_QUERY_TOKEN = 1; // 文件夹列表查询 + + // 上下文菜单项ID + private static final int MENU_FOLDER_DELETE = 0; // 删除文件夹 + 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; // 触摸起始Y坐标 + private int mDispatchY; // 分发事件的Y坐标 + private TextView mTitleBar; // 标题栏 + private long mCurrentFolderId; // 当前文件夹ID + private ContentResolver mContentResolver; // 内容解析器 + private ModeCallback mModeCallBack; // 多选模式回调 + private static final String TAG = "NotesListActivity"; // 日志标签 + public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; // 列表滚动速率 + + private NoteItemData mFocusNoteDataItem; // 当前焦点便签数据项 + + // SQL查询条件 + 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(); // 初始化资源 + + // 首次使用时添加介绍便签 + 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) { + 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; // 初始化分发Y坐标 + mOriginY = 0; // 初始化原始Y坐标 + 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(); // 获取选中数量 + // 更新下拉菜单标题 + 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) { + return false; // 不准备菜单 + } + + public boolean onActionItemClicked(ActionMode mode, MenuItem item) { + 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; // 按钮起始Y坐标 + int eventY = start + (int) event.getY(); // 事件绝对Y坐标 + + // 减去标题栏高度(子文件夹状态) + if (mState == ListEditState.SUB_FOLDER) { + eventY -= mTitleBar.getHeight(); + start -= mTitleBar.getHeight(); + } + + /** + * 特殊处理:点击按钮透明区域时将事件分发给底层列表视图 + * 透明区域由公式 y=-0.12x+94 定义(单位:像素) + * 这是一个UI设计的特殊需求 + */ + 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(); // 保存原始Y坐标 + mDispatchY = eventY; // 设置分发Y坐标 + event.setLocation(event.getX(), mDispatchY); // 修改事件位置 + mDispatch = true; // 标记为分发状态 + return mNotesListView.dispatchTouchEvent(event); // 分发给列表视图 + } + } + break; + } + case MotionEvent.ACTION_MOVE: { // 移动事件 + if (mDispatch) { + mDispatchY += (int) event.getY() - mOriginY; // 更新分发Y坐标 + 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; // 根据文件夹ID选择查询条件 + mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, + Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { + String.valueOf(mCurrentFolderId) // 参数:文件夹ID + }, 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); // 传递当前文件夹ID + this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); // 启动便签编辑活动 + } + + // 批量删除选中的便签 + private void batchDelete() { + new AsyncTask>() { + protected HashSet doInBackground(Void... unused) { + HashSet widgets = mNotesListAdapter.getSelectedWidget(); // 获取关联的小部件 + if (!isSyncMode()) { // 非同步模式:直接删除 + if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter + .getSelectedItemIds())) { + } else { + Log.e(TAG, "Delete notes error, should not happens"); + } + } else { // 同步模式:移动到回收站 + 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 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 ids = new HashSet(); + ids.add(folderId); // 添加文件夹ID + HashSet widgets = DataUtils.getFolderNoteWidget(mContentResolver, + folderId); // 获取文件夹下便签的小部件 + if (!isSyncMode()) { // 非同步模式:直接删除 + DataUtils.batchDeleteNotes(mContentResolver, ids); + } else { // 同步模式:移动到回收站 + 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()); // 传递便签ID + this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); // 启动便签编辑活动 + } + + // 打开文件夹(进入子文件夹) + private void openFolder(NoteItemData data) { + mCurrentFolderId = data.getId(); // 更新当前文件夹ID + 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); + } + // 添加文本变化监听,动态启用/禁用确定按钮 + etName.addTextChangedListener(new TextWatcher() { + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + 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) { + } + }); + } + + // 返回键处理 + @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 // 小部件ID + }); + + 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); + // 根据同步状态设置同步菜单项标题 + 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() { + @Override + protected Integer doInBackground(Void... unused) { + return backup.exportToText(); // 执行导出 + } + + @Override + protected void onPostExecute(Integer result) { + // 根据导出结果显示不同提示 + if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { // SD卡未挂载 + 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; + } +} \ No newline at end of file diff --git a/src/ui/NotesListAdapter.java b/src/ui/NotesListAdapter.java new file mode 100644 index 0000000..10776f0 --- /dev/null +++ b/src/ui/NotesListAdapter.java @@ -0,0 +1,206 @@ +/* + * 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.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; + + +// 便签列表适配器,继承CursorAdapter用于显示数据库中的便签和文件夹列表 +public class NotesListAdapter extends CursorAdapter { + private static final String TAG = "NotesListAdapter"; // 日志标签 + private Context mContext; // 上下文 + private HashMap mSelectedIndex; // 选中项索引映射(位置 -> 是否选中) + private int mNotesCount; // 便签(非文件夹)总数 + private boolean mChoiceMode; // 是否处于多选模式 + + // 小部件属性类(用于批量操作时获取关联的小部件信息) + public static class AppWidgetAttribute { + public int widgetId; // 小部件ID + public int widgetType; // 小部件类型 + }; + + // 构造方法 + public NotesListAdapter(Context context) { + super(context, null); // 初始游标为null + mSelectedIndex = new HashMap(); // 初始化选中项映射 + mContext = context; // 保存上下文引用 + mNotesCount = 0; // 初始便签数为0 + } + + // 创建新列表项视图 + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new NotesListItem(context); // 创建自定义列表项视图 + } + + // 绑定数据到列表项视图 + @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())); + } + } + + // 设置列表项选中状态 + public void setCheckedItem(final int position, final boolean checked) { + mSelectedIndex.put(position, checked); // 更新选中状态映射 + notifyDataSetChanged(); // 通知数据变化,刷新界面 + } + + // 检查是否处于多选模式 + public boolean isInChoiceMode() { + return mChoiceMode; + } + + // 设置选择模式 + public void setChoiceMode(boolean mode) { + mSelectedIndex.clear(); // 清空选中状态 + mChoiceMode = mode; // 更新模式标志 + } + + // 全选/取消全选所有便签项 + 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集合 + public HashSet getSelectedItemIds() { + HashSet itemSet = new HashSet(); + // 遍历选中项映射 + for (Integer position : mSelectedIndex.keySet()) { + if (mSelectedIndex.get(position) == true) { + Long id = getItemId(position); // 获取该项的ID + if (id == Notes.ID_ROOT_FOLDER) { + Log.d(TAG, "Wrong item id, should not happen"); // 根文件夹不应被选中 + } else { + itemSet.add(id); // 添加到集合 + } + } + } + return itemSet; + } + + // 获取选中项关联的小部件属性集合 + public HashSet getSelectedWidget() { + HashSet itemSet = new HashSet(); + // 遍历选中项映射 + 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); // 添加到集合 + // 注意:这里不关闭游标,只有适配器可以关闭游标 + } else { + Log.e(TAG, "Invalid cursor"); + return null; + } + } + } + return itemSet; + } + + // 获取选中项数量 + public int getSelectedCount() { + Collection values = mSelectedIndex.values(); + if (null == values) { + return 0; + } + Iterator iter = values.iterator(); + int count = 0; + // 统计值为true的项数 + while (iter.hasNext()) { + if (true == iter.next()) { + count++; + } + } + return count; + } + + // 检查是否全部便签项都被选中 + public boolean isAllSelected() { + int checkedCount = getSelectedCount(); // 选中数量 + return (checkedCount != 0 && checkedCount == mNotesCount); // 不为0且等于便签总数 + } + + // 检查指定位置项是否被选中 + public boolean isSelectedItem(final int position) { + if (null == mSelectedIndex.get(position)) { + return false; // 映射中不存在则返回false + } + return mSelectedIndex.get(position); // 返回选中状态 + } + + // 内容变化时回调 + @Override + protected void onContentChanged() { + super.onContentChanged(); + calcNotesCount(); // 重新计算便签数量 + } + + // 游标变化时回调 + @Override + public void changeCursor(Cursor cursor) { + super.changeCursor(cursor); // 调用父类方法 + calcNotesCount(); // 重新计算便签数量 + } + + // 计算便签(非文件夹)数量 + private void calcNotesCount() { + mNotesCount = 0; + // 遍历所有项 + for (int i = 0; i < getCount(); i++) { + Cursor c = (Cursor) getItem(i); + if (c != null) { + // 只统计便签类型(TYPE_NOTE) + if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { + mNotesCount++; // 便签计数加1 + } + } else { + Log.e(TAG, "Invalid cursor"); + return; + } + } + } +} \ No newline at end of file diff --git a/src/ui/NotesListItem.java b/src/ui/NotesListItem.java new file mode 100644 index 0000000..2a1434f --- /dev/null +++ b/src/ui/NotesListItem.java @@ -0,0 +1,149 @@ +/* + * 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; + + +// 便签列表项自定义视图,继承LinearLayout,用于显示单个便签/文件夹项 +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); // 使用Android标准ID + } + + // 绑定数据到视图 + 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); // 隐藏图标 + } + } + } + // 设置相对时间(如"2分钟前") + mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); + + setBackground(data); // 设置背景(根据位置和类型) + } + + // 设置列表项背景(根据位置和类型) + private void setBackground(NoteItemData data) { + int id = data.getBgColorId(); // 获取背景颜色ID + 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; + } +} \ No newline at end of file diff --git a/src/ui/NotesPreferenceActivity.java b/src/ui/NotesPreferenceActivity.java new file mode 100644 index 0000000..00b8746 --- /dev/null +++ b/src/ui/NotesPreferenceActivity.java @@ -0,0 +1,413 @@ +/* + * 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.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; + +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 +// 便签偏好设置活动,管理同步账户和应用程序设置 +public class NotesPreferenceActivity extends PreferenceActivity { + // 偏好设置文件名 + public static final String PREFERENCE_NAME = "notes_preferences"; + // 同步账户名偏好键 + public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name"; + // 上次同步时间偏好键 + public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; + // 背景颜色设置偏好键 + public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear"; + // 同步账户分类键(UI中的分类) + private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key"; + // 账户权限过滤器键(用于添加账户) + private static final String AUTHORITIES_FILTER_KEY = "authorities"; + + private PreferenceCategory mAccountCategory; // 账户偏好分类 + private GTaskReceiver mReceiver; // 同步服务广播接收器 + private Account[] mOriAccounts; // 原始账户数组(用于检测新账户) + private boolean mHasAddedAccount; // 是否添加了新账户标志 + + // 创建活动 + @Override + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + // 启用ActionBar返回按钮 + getActionBar().setDisplayHomeAsUpEnabled(true); + + addPreferencesFromResource(R.xml.preferences); // 加载偏好设置XML + mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); // 获取账户分类 + mReceiver = new GTaskReceiver(); // 创建广播接收器 + IntentFilter filter = new IntentFilter(); + filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); // 过滤同步服务广播 + registerReceiver(mReceiver, filter); // 注册接收器 + + mOriAccounts = null; + // 添加自定义头部视图 + View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); + getListView().addHeaderView(header, null, true); + } + + // 活动恢复时检查新账户 + @Override + protected void onResume() { + super.onResume(); + + // 用户添加新账户后自动设置同步账户 + 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(); // 刷新界面 + } + + // 销毁活动时注销广播接收器 + @Override + protected void onDestroy() { + if (mReceiver != null) { + unregisterReceiver(mReceiver); + } + super.onDestroy(); + } + + // 加载账户偏好设置项 + private void loadAccountPreference() { + mAccountCategory.removeAll(); // 清除现有偏好项 + + Preference accountPref = new Preference(this); + 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.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); // 同步状态文本 + + // 设置按钮状态:根据是否正在同步显示不同文本和点击行为 + 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))); // 有账户时才启用 + + // 设置上次同步时间显示 + if (GTaskSyncService.isSyncing()) { + lastSyncTimeView.setText(GTaskSyncService.getProgressString()); // 显示同步进度 + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + long lastSyncTime = getLastSyncTime(this); // 获取上次同步时间 + if (lastSyncTime != 0) { + lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, + DateFormat.format(getString(R.string.preferences_last_sync_time_format), + lastSyncTime))); // 格式化时间显示 + lastSyncTimeView.setVisibility(View.VISIBLE); + } else { + lastSyncTimeView.setVisibility(View.GONE); // 从未同步则隐藏 + } + } + } + + // 刷新界面:重新加载账户偏好和同步按钮 + private void refreshUI() { + loadAccountPreference(); + loadSyncButton(); + } + + // 显示选择账户对话框 + private void showSelectAccountAlertDialog() { + AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); + + // 自定义标题视图 + View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); + TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); + titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); + TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); + subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); + + dialogBuilder.setCustomTitle(titleView); + dialogBuilder.setPositiveButton(null, null); // 无确定按钮 + + Account[] accounts = getGoogleAccounts(); // 获取Google账户 + String defAccount = getSyncAccountName(this); // 当前同步账户 + + mOriAccounts = accounts; // 保存原始账户列表 + mHasAddedAccount = false; // 重置添加标志 + + if (accounts.length > 0) { + CharSequence[] items = new CharSequence[accounts.length]; + final CharSequence[] itemMapping = items; + int checkedItem = -1; + int index = 0; + // 构建账户列表 + for (Account account : accounts) { + if (TextUtils.equals(account.name, defAccount)) { + checkedItem = index; // 标记当前账户 + } + items[index++] = account.name; + } + // 单选框列表 + dialogBuilder.setSingleChoiceItems(items, checkedItem, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + setSyncAccount(itemMapping[which].toString()); // 设置选中账户 + dialog.dismiss(); + refreshUI(); // 刷新界面 + } + }); + } + + // 添加"添加账户"选项 + 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" // 过滤Gmail账户 + }); + 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(); // 刷新界面 + } + // which == 2 取消,不做任何操作 + } + }); + dialogBuilder.show(); + } + + // 获取Google账户列表 + private Account[] getGoogleAccounts() { + AccountManager accountManager = AccountManager.get(this); + return accountManager.getAccountsByType("com.google"); // 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(); + + // 清空上次同步时间 + setLastSyncTime(this, 0); + + // 在新线程中清空本地同步信息 + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); // 清空Google任务ID + values.put(NoteColumns.SYNC_ID, 0); // 重置同步ID + 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(); + + // 在新线程中清空本地同步信息 + new Thread(new Runnable() { + public void run() { + ContentValues values = new ContentValues(); + values.put(NoteColumns.GTASK_ID, ""); // 清空Google任务ID + values.put(NoteColumns.SYNC_ID, 0); // 重置同步ID + 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); // 默认返回0 + } + + // 同步服务广播接收器(用于更新UI状态) + 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; + } + } +} +``` \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider.java b/src/widget/NoteWidgetProvider.java new file mode 100644 index 0000000..5884f64 --- /dev/null +++ b/src/widget/NoteWidgetProvider.java @@ -0,0 +1,156 @@ +/* + * 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; + +```java +// 便签桌面小部件提供器抽象类,继承AppWidgetProvider +public abstract class NoteWidgetProvider extends AppWidgetProvider { + // 数据库查询投影字段 + public static final String [] PROJECTION = new String [] { + NoteColumns.ID, // 便签ID + NoteColumns.BG_COLOR_ID, // 背景颜色ID + NoteColumns.SNIPPET // 便签内容摘要 + }; + + // 列索引常量 + public static final int COLUMN_ID = 0; // ID列索引 + public static final int COLUMN_BG_COLOR_ID = 1; // 背景颜色ID列索引 + public static final int COLUMN_SNIPPET = 2; // 摘要列索引 + + private static final String TAG = "NoteWidgetProvider"; // 日志标签 + + // 小部件被删除时的回调 + @Override + public void onDeleted(Context context, int[] appWidgetIds) { + ContentValues values = new ContentValues(); + // 将被删除的小部件ID设置为无效值 + values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); + for (int i = 0; i < appWidgetIds.length; i++) { + // 更新数据库,清空关联便签的小部件ID + context.getContentResolver().update(Notes.CONTENT_NOTE_URI, + values, + NoteColumns.WIDGET_ID + "=?", + new String[] { String.valueOf(appWidgetIds[i])}); + } + } + + // 获取关联小部件的便签信息 + private Cursor getNoteWidgetInfo(Context context, int widgetId) { + return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + // 查询条件:指定小部件ID且不在回收站中 + NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", + new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) }, + null); + } + + // 更新小部件(公开方法) + protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + update(context, appWidgetManager, appWidgetIds, false); // 默认非隐私模式 + } + + // 更新小部件(私有方法,支持隐私模式) + private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, + boolean privacyMode) { + for (int i = 0; i < appWidgetIds.length; i++) { + if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { + int bgId = ResourceParser.getDefaultBgId(context); // 默认背景ID + String snippet = ""; // 便签内容摘要 + + // 创建点击小部件后启动的Intent + Intent intent = new Intent(context, NoteEditActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // 单例模式 + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); // 传递小部件ID + intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); // 传递小部件类型 + + // 查询关联的便签信息 + Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); + if (c != null && c.moveToFirst()) { + if (c.getCount() > 1) { + // 错误情况:多个便签关联到同一个widget ID + Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]); + c.close(); + return; + } + snippet = c.getString(COLUMN_SNIPPET); // 获取便签内容 + bgId = c.getInt(COLUMN_BG_COLOR_ID); // 获取背景颜色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对象 + RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); + rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); // 设置背景图片 + intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId); // 传递背景ID给编辑活动 + + /** + * 生成待定Intent(点击小部件后启动) + */ + 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获取对应的资源ID(由子类实现) + protected abstract int getBgResourceId(int bgId); + + // 抽象方法:获取小部件布局ID(由子类实现) + protected abstract int getLayoutId(); + + // 抽象方法:获取小部件类型(由子类实现) + protected abstract int getWidgetType(); +} +``` \ No newline at end of file diff --git a/src/widget/NoteWidgetProvider_2x.java b/src/widget/NoteWidgetProvider_2x.java new file mode 100644 index 0000000..adcb2f7 --- /dev/null +++ b/src/widget/NoteWidgetProvider_2x.java @@ -0,0 +1,47 @@ +/* + * 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; + + +public class NoteWidgetProvider_2x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + @Override + protected int getLayoutId() { + return R.layout.widget_2x; + } + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); + } + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_2X; + } +} diff --git a/src/widget/NoteWidgetProvider_4x.java b/src/widget/NoteWidgetProvider_4x.java new file mode 100644 index 0000000..c12a02e --- /dev/null +++ b/src/widget/NoteWidgetProvider_4x.java @@ -0,0 +1,46 @@ +/* + * 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; + + +public class NoteWidgetProvider_4x extends NoteWidgetProvider { + @Override + public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { + super.update(context, appWidgetManager, appWidgetIds); + } + + protected int getLayoutId() { + return R.layout.widget_4x; + } + + @Override + protected int getBgResourceId(int bgId) { + return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); + } + + @Override + protected int getWidgetType() { + return Notes.TYPE_WIDGET_4X; + } +}