合并代码 #5

Merged
pogt39wa7 merged 12 commits from 赵西林 into main 1 year ago

@ -1,3 +1,21 @@
/*
* 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;
// 导入必要的Android框架类和自定义的Notes数据类
import android.content.Context;
import android.database.Cursor;

@ -0,0 +1,408 @@
/*
* 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;
public class DataUtils {
public static final String TAG = "DataUtils";
/**
*
*
* @param resolver ContentResolver
* @param ids ID
* @return truefalse
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查传入的ID集合是否为null或为空
if (ids == null || ids.size() == 0) {
Log.d(TAG, "the ids is null or empty");
return true;
}
// 创建操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
// 不允许删除系统文件夹根目录
if (id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
// 构建删除操作
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;
}
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;
}
/**
*
*
* @param resolver ContentResolver
* @param id ID
* @param srcFolderId ID
* @param desFolderId ID
*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
// 创建更新操作的值集
ContentValues values = new ContentValues();
// 设置新的父文件夹ID
values.put(NoteColumns.PARENT_ID, desFolderId);
// 记录原始父文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
// 标记笔记为已修改
values.put(NoteColumns.LOCAL_MODIFIED, 1);
// 执行更新操作
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
/**
*
*
* @param resolver ContentResolver
* @param ids ID
* @param folderId ID
* @return truefalse
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, long folderId) {
// 检查传入的ID集合是否为null
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
// 创建操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
// 构建更新操作
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 设置新的父文件夹ID
builder.withValue(NoteColumns.PARENT_ID, folderId);
// 标记笔记为已修改
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, "move notes failed, ids:" + ids.toString());
return 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;
}
/**
*
*
* @param resolver ContentResolver
* @return
*/
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;
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;
}
/**
*
*
* @param resolver ContentResolver
* @param noteId ID
* @param type
* @return truefalse
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 执行查询操作,检查指定类型的笔记是否存在且不在回收站中
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
null);
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
/**
*
*
* @param resolver ContentResolver
* @param noteId ID
* @return truefalse
*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 执行查询操作,检查笔记是否存在
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
/**
*
*
* @param resolver ContentResolver
* @param dataId ID
* @return truefalse
*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 执行查询操作,检查数据是否存在
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
/**
*
*
* @param resolver ContentResolver
* @param name
* @return truefalse
*/
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;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
/**
*
*
* @param resolver ContentResolver
* @param folderId ID
* @return HashSet
*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 执行查询操作,获取文件夹中笔记的小部件属性
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },
null);
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
set.add(widget);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
}
c.close();
}
return set;
}
/**
* ID
*
* @param resolver ContentResolver
* @param noteId ID
* @return
*/
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 + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);
if (cursor != null && cursor.moveToFirst()) {
try {
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
}
}
return "";
}
/**
* ID
*
* @param resolver ContentResolver
* @param phoneNumber
* @param callDate
* @return ID
*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 执行查询操作获取与电话号码和通话日期关联的笔记ID
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL(" + CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
cursor.close();
}
return 0;
}
/**
* ID
*
* @param resolver ContentResolver
* @param noteId ID
* @return
*/
public static String getSnippetById(ContentResolver resolver, long noteId) {
// 执行查询操作,获取笔记摘要
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
}
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
/**
*
*
* @param snippet
* @return
*/
public static String getFormattedSnippet(String snippet) {
// 去除摘要两端的空白字符,并去除换行符
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);
}
}
return snippet;
}
}

@ -0,0 +1,152 @@
/*
* 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;
public class GTaskStringUtils {
// JSON键值用于标识动作的唯一ID
public final static String GTASK_JSON_ACTION_ID = "action_id";
// JSON键值用于标识动作列表
public final static String GTASK_JSON_ACTION_LIST = "action_list";
// JSON键值用于标识动作类型
public final static String GTASK_JSON_ACTION_TYPE = "action_type";
// JSON键值创建任务的动作类型
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
// JSON键值获取所有任务的动作类型
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
// JSON键值移动任务的动作类型
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
// JSON键值更新任务的动作类型
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
// JSON键值标识创建者的ID
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// JSON键值子实体标识
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// JSON键值客户端版本标识
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// JSON键值标识任务是否已完成
public final static String GTASK_JSON_COMPLETED = "completed";
// JSON键值当前列表的ID
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// JSON键值默认列表的ID
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// JSON键值标识任务是否已被删除
public final static String GTASK_JSON_DELETED = "deleted";
// JSON键值目标列表标识
public final static String GTASK_JSON_DEST_LIST = "dest_list";
// JSON键值目标父项标识
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// JSON键值目标父项类型标识
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// JSON键值实体变化标识
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// JSON键值实体类型标识包括任务和分组
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// JSON键值获取已删除任务的标识
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// JSON键值通用的ID标识
public final static String GTASK_JSON_ID = "id";
// JSON键值索引标识
public final static String GTASK_JSON_INDEX = "index";
// JSON键值最后修改时间标识
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// JSON键值最新同步点标识
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// JSON键值列表的ID标识
public final static String GTASK_JSON_LIST_ID = "list_id";
// JSON键值列表标识
public final static String GTASK_JSON_LISTS = "lists";
// JSON键值名称标识
public final static String GTASK_JSON_NAME = "name";
// JSON键值新的ID标识
public final static String GTASK_JSON_NEW_ID = "new_id";
// JSON键值注释或笔记标识
public final static String GTASK_JSON_NOTES = "notes";
// JSON键值父项的ID标识
public final static String GTASK_JSON_PARENT_ID = "parent_id";
// JSON键值前一个同级项的ID标识
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// JSON键值结果标识
public final static String GTASK_JSON_RESULTS = "results";
// JSON键值源列表标识
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// JSON键值任务标识
public final static String GTASK_JSON_TASKS = "tasks";
// JSON键值类型标识
public final static String GTASK_JSON_TYPE = "type";
// JSON键值用户标识
public final static String GTASK_JSON_USER = "user";
// 文件夹前缀标识用于MIUI笔记
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
// 默认文件夹名称
public final static String FOLDER_DEFAULT = "Default";
// 通话笔记文件夹名称
public final static String FOLDER_CALL_NOTE = "Call_Note";
// 元数据文件夹名称
public final static String FOLDER_META = "METADATA";
// 元数据头标识表示Google任务ID
public final static String META_HEAD_GTASK_ID = "meta_gid";
// 元数据头标识,表示笔记
public final static String META_HEAD_NOTE = "meta_note";
// 元数据头标识,表示数据
public final static String META_HEAD_DATA = "meta_data";
// 元数据笔记名称,提示不要更新和删除
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}

@ -0,0 +1,204 @@
/*
* 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;
// 导入Android框架中用于访问偏好设置和资源的类
import android.content.Context;
import android.preference.PreferenceManager;
// 导入资源文件和偏好设置活动类
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
// ResourceParser类用于解析和管理应用中的资源
public class ResourceParser {
// 定义颜色资源的静态常量
public static final int YELLOW = 0;
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
// 默认背景颜色设置为黄色
public static final int BG_DEFAULT_COLOR = YELLOW;
// 定义文本大小资源的静态常量
public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
// 默认文本大小设置为中等
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// NoteBgResources内部类用于获取编辑界面的背景资源
public static class NoteBgResources {
// 定义编辑界面背景和标题背景的资源ID数组
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
};
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
};
// 根据ID获取编辑界面背景资源
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
// 根据ID获取编辑界面标题背景资源
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
// 获取默认背景ID的方法考虑用户偏好设置
public static int getDefaultBgId(Context context) {
// 从偏好设置中获取背景颜色设置,如果用户已设置,则随机选择一个背景颜色
// 否则返回默认颜色BG_DEFAULT_COLOR
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
return BG_DEFAULT_COLOR;
}
}
// NoteItemBgResources内部类用于获取列表项的背景资源
public static class NoteItemBgResources {
// 定义列表项不同位置的背景资源ID数组
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
};
// 根据ID获取不同位置的背景资源
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
// 获取文件夹背景资源的方法
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
// WidgetBgResources内部类用于获取小部件的背景资源
public static class WidgetBgResources {
// 定义小部件背景资源ID数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
// 根据ID获取2倍尺寸小部件背景资源
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 定义4倍尺寸小部件背景资源ID数组
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
// 根据ID获取4倍尺寸小部件背景资源
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
// TextAppearanceResources内部类用于获取文本外观样式资源
public static class TextAppearanceResources {
// 定义文本外观样式资源ID数组
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
// 根据ID获取文本外观样式资源如果ID超出范围则返回默认文本大小
public static int getTexAppearanceResource(int id) {
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
}
// 获取文本外观样式资源数组的长度
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}

@ -0,0 +1,190 @@
/*
* 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;
// 导入Android框架中用于对话框、音频、媒体播放等相关功能的类
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;
// 导入Java的IO功能用于处理可能的输入输出异常
import java.io.IOException;
// 定义AlarmAlertActivity类它是一个Activity用于显示闹钟提醒
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
// 定义成员变量用于存储笔记的ID和预览文本
private long mNoteId;
private String mSnippet;
// 定义一个常量,用于限制预览文本的最大长度
private static final int SNIPPET_PREW_MAX_LEN = 60;
// 定义MediaPlayer对象用于播放闹钟声音
MediaPlayer mPlayer;
// onCreate方法当Activity创建时被调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 请求无标题的窗口特性
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);
}
// 获取启动Activity的Intent
Intent intent = getIntent();
try {
// 从Intent中获取笔记ID
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 根据笔记ID获取笔记的预览文本
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 如果预览文本超过最大长度,则截断并添加省略号
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
// 创建MediaPlayer对象
mPlayer = new MediaPlayer();
// 如果笔记存在于数据库中,则显示操作对话框并播放闹钟声音
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
} else {
// 如果笔记不存在则结束Activity
finish();
}
}
// 检查屏幕是否开启
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
// 播放闹钟声音
private void playAlarmSound() {
// 获取默认闹钟铃声的Uri
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取受影响的音频流类型
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 如果闹钟铃声被静音模式影响则设置MediaPlayer的音频流类型
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
// 设置MediaPlayer的数据源为闹钟铃声并准备播放
mPlayer.setDataSource(this, url);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 显示操作对话框
private void showActionDialog() {
// 创建AlertDialog.Builder对象
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:
// 如果用户点击否定按钮则启动NoteEditActivity
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
break;
default:
// 默认不做任何操作
break;
}
}
// 对话框消失事件处理方法
public void onDismiss(DialogInterface dialog) {
// 停止闹钟声音并结束Activity
stopAlarmSound();
finish();
}
// 停止闹钟声音
private void stopAlarmSound() {
// 如果MediaPlayer对象不为空则停止播放并释放资源
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
}

@ -0,0 +1,89 @@
/*
* 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.
*/
// 这里是文件的版权声明说明代码版权归属于MiCode开源社区并在Apache License 2.0下授权。
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;
// 导入所需的Android类和接口以及应用内部的数据访问类。
public class AlarmInitReceiver extends BroadcastReceiver {
// 定义一个继承自BroadcastReceiver的类用于处理广播事件。
private static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
};
// 定义查询数据库时需要的列。
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;
// 定义列索引常量。
@Override
public void onReceive(Context context, Intent intent) {
// 实现onReceive方法这是BroadcastReceiver的核心方法用于处理接收到的广播。
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 sender = new Intent(context, AlarmReceiver.class);
// 创建一个新的Intent用于触发AlarmReceiver。
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 设置Intent的数据以便AlarmReceiver知道要处理哪个笔记。
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 创建一个PendingIntent用于AlarmManager设置闹钟。
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 获取AlarmManager服务。
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
// 设置闹钟当到达提醒日期时AlarmManager将触发AlarmReceiver。
} while (c.moveToNext());
// 遍历查询结果,为每条记录设置闹钟。
}
c.close();
// 关闭Cursor。
}
}
}

@ -0,0 +1,39 @@
/*
* 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;
// 导入Android框架中用于接收广播和启动Activity的类
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
// 定义AlarmReceiver类继承自BroadcastReceiver
public class AlarmReceiver extends BroadcastReceiver {
// onReceive方法是BroadcastReceiver的核心方法当接收到广播时被调用
@Override
public void onReceive(Context context, Intent intent) {
// 将接收到的Intent的类设置为AlarmAlertActivity即当接收到广播时启动AlarmAlertActivity
intent.setClass(context, AlarmAlertActivity.class);
// 为Intent添加FLAG_ACTIVITY_NEW_TASK标志使得即使应用程序不在前台也能启动Activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 使用context启动AlarmAlertActivity
context.startActivity(intent);
}
}

@ -0,0 +1,541 @@
/**
* MiCodeApache License 2.0使
*/
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import java.text.DateFormatSymbols;
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;
/**
* DateTimePicker
*/
public class DateTimePicker extends FrameLayout {
// 默认启用状态
private static final boolean DEFAULT_ENABLE_STATE = true;
// 时间和日期的常量
private static final int HOURS_IN_HALF_DAY = 12;
private static final int HOURS_IN_ALL_DAY = 24;
private static final int DAYS_IN_ALL_WEEK = 7;
private static final int DATE_SPINNER_MIN_VAL = 0;
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
private static final int MINUT_SPINNER_MIN_VAL = 0;
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
// 日期时间选择器的组件
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
private Calendar mDate;
// 日期显示值
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// AM/PM状态
private boolean mIsAm;
// 24小时制状态
private boolean mIs24HourView;
// 启用状态
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();
// 处理12小时制和24小时制的切换
if (!mIs24HourView) {
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}
} else {
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
}
};
// 分钟改变的监听器
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
}
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
}
};
// AM/PM改变的监听器
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
}
updateAmPmControl();
onDateTimeChanged();
}
};
// 日期时间改变的回调接口
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
// DateTimePicker的构造函数
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); // 调用 FrameLayout 的构造函数,因为 DateTimePicker 继承自 FrameLayout
mDate = Calendar.getInstance(); // 获取当前日期和时间的 Calendar 实例
mInitialising = true; // 设置初始化标志为 true表示正在初始化控件
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; // 根据当前时间判断是 AM 还是 PM
// 将 datetime_picker.xml 布局文件加载到 DateTimePicker 中
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); // 设置长按选择器更新间隔为 100 毫秒
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化 AM/PM 选择器,并设置其最小值和最大值,以及显示值和值改变监听器
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);
// 更新日期、小时和 AM/PM 控件的状态
updateDateControl();
updateHourControl();
updateAmPmControl();
// 设置是否为24小时制视图
set24HourView(is24HourView);
// 设置当前时间
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;
}
/**
*
*
* @return
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
*
*
* @param date
*/
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));
}
/**
*
*
* @param year
* @param month
* @param dayOfMonth
* @param hourOfDay 24
* @param minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}
/**
*
*
* @return
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
/**
*
*
* @param year
*/
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
return;
}
mDate.set(Calendar.YEAR, year);
updateDateControl();
onDateTimeChanged();
}
/**
*
*
* @return
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
/**
*
*
* @param month 0-11
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
return;
}
mDate.set(Calendar.MONTH, month);
updateDateControl();
onDateTimeChanged();
}
/**
*
*
* @return
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
/**
*
*
* @param dayOfMonth
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
return;
}
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateControl();
onDateTimeChanged();
}
/**
* 24
*
* @return
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
/**
* 12
*
* @return
*/
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
} else {
int hour = getCurrentHourOfDay();
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
}
}
}
/**
* 24
*
* @param hourOfDay
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY;
}
} else {
mIsAm = true;
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
}
}
updateAmPmControl();
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
}
/**
*
*
* @return
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
/**
*
*
* @param minute
*/
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged();
}
/**
* 24
*
* @return 24truefalse
*/
public boolean is24HourView() {
return mIs24HourView;
}
/**
* 24AM/PM
*
* @param is24HourView true24AM/PM
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
setCurrentHour(hour);
updateAmPmControl();
}
/**
*
*/
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}
/**
* AM/PM
*/
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
/**
*
*/
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
}
/**
*
*
* @param callback null
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
/**
*
*/
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}

@ -0,0 +1,135 @@
/*
* MiCodeApache License 2.0使
*/
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import java.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;
/**
* DateTimePickerDialog AlertDialog
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 当前日期时间的 Calendar 对象
private Calendar mDate = Calendar.getInstance();
// 是否使用24小时制的布尔值
private boolean mIs24HourView;
// 日期时间设置监听器
private OnDateTimeSetListener mOnDateTimeSetListener;
// DateTimePicker 对象
private DateTimePicker mDateTimePicker;
/**
* OnDateTimeSetListener OnDateTimeSet
*/
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
* DateTimePickerDialog
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
// 设置 DateTimePicker 的日期时间改变监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
updateTitle(mDate.getTimeInMillis());
}
});
mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0);
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置对话框的按钮
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 设置是否使用24小时制
set24HourView(DateFormat.is24HourFormat(this.getContext()));
updateTitle(mDate.getTimeInMillis());
}
/**
* 使24
*
* @param is24HourView 使24
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
if (mDateTimePicker != null) {
mDateTimePicker.set24HourView(is24HourView);
}
}
/**
*
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
*
* @param date
*/
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_12HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
*
*
* @param arg0 DialogInterface
* @param arg1
*/
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -0,0 +1,98 @@
/*
* MiCodeApache License 2.0使
*/
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
* DropdownMenu Dropdown Menu
*/
public class DropdownMenu {
// 按钮,用于触发下拉菜单的显示
private Button mButton;
// 弹出菜单对象
private PopupMenu mPopupMenu;
// 菜单对象,用于操作菜单项
private Menu mMenu;
/**
* DropdownMenu
*
* @param context
* @param button
* @param menuId ID
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置按钮的背景资源为下拉图标
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建PopupMenu对象并传入按钮作为锚点
mPopupMenu = new PopupMenu(context, mButton);
// 获取PopupMenu的Menu对象
mMenu = mPopupMenu.getMenu();
// 通过menuId加载菜单项
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮的点击事件监听器点击时显示PopupMenu
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
});
}
/**
*
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
/**
* ID
*
* @param id ID
* @return
*/
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
/**
*
*
* @param title
*/
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}

@ -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;
// 定义一个继承自CursorAdapter的类用于适配文件夹列表的数据
public class FoldersListAdapter extends CursorAdapter {
// 定义查询数据库时需要的列
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
};
// 定义列索引常量
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
// 构造函数,初始化上下文和游标
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
// 新建视图的方法返回一个FolderListItem对象
@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);
}
// 定义一个内部类FolderListItem继承自LinearLayout
private class FolderListItem extends LinearLayout {
// 定义一个TextView用于显示文件夹名称
private TextView mName;
// FolderListItem的构造函数初始化布局和TextView
public FolderListItem(Context context) {
super(context);
inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name);
}
// 绑定文件夹名称到TextView的方法
public void bind(String name) {
mName.setText(name);
}
}
}

@ -0,0 +1,979 @@
/*
* 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;
// 导入所需的Android类和接口
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;
// NoteEditActivity类继承自Activity类用于编辑笔记
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
// 内部类HeadViewHolder用于持有笔记头部视图的引用
private class HeadViewHolder {
public TextView tvModified; // 显示最后修改时间的TextView
public ImageView ivAlertIcon; // 闹钟提醒图标的ImageView
public TextView tvAlertDate; // 显示闹钟提醒日期的TextView
public ImageView ibSetBgColor; // 设置背景颜色的ImageView
}
// 定义了一些静态的Map用于存储背景颜色选择器按钮和字体大小选择器按钮的ID与它们对应的值之间的映射关系
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();
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);
}
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();
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);
}
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();
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);
}
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();
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"; // 用于日志输出的TAG
private HeadViewHolder mNoteHeaderHolder; // 持有笔记头部视图的引用
private View mHeadViewPanel; // 笔记头部视图面板
private View mNoteBgColorSelector; // 笔记背景颜色选择器
private View mFontSizeSelector; // 字体大小选择器
private EditText mNoteEditor; // 笔记编辑器
private View mNoteEditorPanel; // 笔记编辑器面板
private WorkingNote mWorkingNote; // 正在编辑的笔记
private SharedPreferences mSharedPrefs; // SharedPreferences对象用于存储设置
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);
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; // 初始化WorkingNote对象为null
// 如果Intent的Action是VIEW但是没有提供ID则跳转到笔记列表活动
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); // 获取笔记ID
mUserQuery = "";
// 如果是从搜索结果开始的
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); // 从搜索结果中获取笔记ID
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); // 获取用户查询字符串
}
// 如果笔记ID在数据库中不可见则跳转到笔记列表活动并显示错误信息
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); // 获取文件夹ID
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID); // 获取小部件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)); // 获取背景资源ID
// 解析通话记录笔记
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; // 返回true表示成功初始化
}
@Override
protected void onResume() {
super.onResume(); // 调用父类的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));
}
/**
*
* DateTimePicker
*/
showAlertHeader();
private void showAlertHeader() {
// 如果笔记有设置闹钟提醒
if (mWorkingNote.hasClockAlert()) {
long time = System.currentTimeMillis(); // 获取当前时间
// 如果当前时间超过了提醒时间
if (time > mWorkingNote.getAlertDate()) {
mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); // 显示提醒已过期
} else {
// 显示相对时间例如“1小时后”
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); // 隐藏提醒图标
};
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent); // 调用父类的onNewIntent方法
initActivityState(intent); // 重新初始化活动状态
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState); // 调用父类的onSaveInstanceState方法
// 对于没有笔记ID的新笔记我们首先需要保存它以生成ID
if (!mWorkingNote.existInDatabase()) {
saveNote(); // 保存笔记
}
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); // 将笔记ID保存到Bundle中
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); // 日志输出保存的笔记ID
}
@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); // 继续传递事件
}
/**
*
* @param view
* @param ev
* @return truefalse
*/
private boolean inRangeOfView(View view, MotionEvent ev) {
int []location = new int[2];
view.getLocationOnScreen(location); // 获取视图在屏幕上的位置
int x = location[0];
int y = location[1];
// 如果触摸事件的x或y坐标超出视图的范围
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); // 获取修改日期TextView
mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); // 获取提醒图标ImageView
mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); // 获取提醒日期TextView
mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); // 获取设置背景颜色的ImageView
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); // 获取SharedPreferences对象
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); // 获取字体大小ID
// 如果字体大小ID超出范围则设置为默认值
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
}
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list); // 获取编辑文本列表
}
@Override
protected void onPause() {
super.onPause(); // 调用父类的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); // 创建更新小部件的Intent
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[] { // 添加小部件ID
mWorkingNote.getWidgetId()
});
sendBroadcast(intent); // 发送广播
setResult(RESULT_OK, intent); // 设置结果
}
@Override
public void onClick(View v) {
int id = v.getId(); // 获取点击的视图ID
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)); // 设置新的背景颜色ID
mNoteBgColorSelector.setVisibility(View.GONE); // 隐藏背景颜色选择器
} else if (sFontSizeBtnsMap.containsKey(id)) {
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); // 隐藏当前选中的字体大小
mFontSizeId = sFontSizeBtnsMap.get(id); // 设置新的字体大小ID
mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); // 保存字体大小ID到SharedPreferences
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() {
// 当用户按下返回键时如果设置了清除设置状态并返回true则直接返回
if (clearSettingState()) {
return;
}
// 保存笔记
saveNote();
// 调用父类的onBackPressed方法完成返回操作
super.onBackPressed();
}
/**
*
* @return true
*/
private boolean clearSettingState() {
// 如果背景颜色选择器可见则隐藏并返回true
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE);
return true;
} else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {
// 如果字体大小选择器可见则隐藏并返回true
mFontSizeSelector.setVisibility(View.GONE);
return true;
}
return false; // 没有设置可见状态为不可见返回false
}
/**
*
*/
public void onBackgroundColorChanged() {
// 显示当前选中的背景颜色
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(View.VISIBLE);
// 设置笔记编辑器面板的背景资源ID
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
// 设置笔记标题面板的背景资源ID
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// 如果活动正在结束则返回true
if (isFinishing()) {
return true;
}
// 清除设置状态
clearSettingState();
// 清除菜单项
menu.clear();
// 根据笔记所在的文件夹ID决定加载哪个菜单
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) {
// 根据点击的菜单项ID执行相应的操作
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();
}
/**
*
* @param context
* @param info
*/
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();
// 安全起见结束当前活动并启动一个新的NoteEditActivity
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<Long> ids = new HashSet<Long>();
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);
}
/**
*
* @return true
*/
private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
}
/**
*
* @param date
* @param set
*/
public void onClockAlertChanged(long date, boolean set) {
// 如果笔记尚未保存,则先保存笔记
if (!mWorkingNote.existInDatabase()) {
saveNote();
}
// 如果笔记有有效的ID则继续设置提醒
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 {
// 如果笔记没有有效的ID说明用户没有输入任何内容提醒用户输入内容
Log.e(TAG, "Clock alert setting error");
showToast(R.string.error_note_empty_for_clock);
}
}
/**
*
*/
public void onWidgetChanged() {
updateWidget(); // 更新小部件
}
/**
*
* @param index
* @param text
*/
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);
}
/**
*
* @param index
* @param text
*/
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);
}
}
/**
*
* @param text
*/
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); // 显示编辑文本列表
}
/**
* Spannable
* @param fullText
* @param userQuery
* @return Spannable
*/
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;
}
/**
*
* @param item
* @param index
* @return
*/
private View getListItem(String item, int index) {
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);
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;
}
/**
*
* @param index
* @param hasText
*/
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);
}
}
/**
*
* @param oldMode
* @param newMode
*/
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);
}
}
/**
*
* @return true
*/
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;
}
/**
*
* @return truefalse
*/
private boolean saveNote() {
// 获取工作文本,可能是从列表模式转换来的文本
getWorkingText();
// 调用mWorkingNote对象的saveNote方法保存笔记并接收返回值
boolean saved = mWorkingNote.saveNote();
// 如果保存成功设置activity的结果码为RESULT_OK用于标识创建或编辑状态
if (saved) {
setResult(RESULT_OK);
}
return saved; // 返回保存结果
}
/**
*
*/
private void sendToDesktop() {
// 如果当前笔记不在数据库中(即新笔记),则先保存笔记
if (!mWorkingNote.existInDatabase()) {
saveNote();
}
// 如果笔记有有效的ID说明笔记已保存可以创建快捷方式
if (mWorkingNote.getNoteId() > 0) {
Intent sender = new Intent(); // 创建Intent对象
Intent shortcutIntent = new Intent(this, NoteEditActivity.class); // 创建快捷方式的Intent
shortcutIntent.setAction(Intent.ACTION_VIEW); // 设置动作为查看
shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); // 附加笔记ID
sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); // 附加快捷方式Intent
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); // 允许重复创建快捷方式
sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); // 设置动作为安装快捷方式
showToast(R.string.info_note_enter_desktop); // 显示提示信息
sendBroadcast(sender); // 发送广播创建快捷方式
} else {
// 如果笔记没有有效的ID说明笔记未保存记录错误日志并提示用户输入内容
Log.e(TAG, "Send to desktop error");
showToast(R.string.error_note_empty_for_send_to_desktop);
}
}
/**
* 使
* @param content
* @return
*/
private String makeShortcutIconTitle(String content) {
content = content.replace(TAG_CHECKED, ""); // 移除TAG_CHECKED标记
content = content.replace(TAG_UNCHECKED, ""); // 移除TAG_UNCHECKED标记
// 如果内容长度超过最大长度,截取前一部分作为标题
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, SHORTCUT_ICON_TITLE_MAX_LEN) : content;
}
/**
*
* @param resId ID
*/
private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT); // 调用重载方法显示提示信息
}
/**
*
* @param resId ID
* @param duration
*/
private void showToast(int resId, int duration) {
Toast.makeText(this, resId, duration).show(); // 显示提示信息
}

@ -0,0 +1,236 @@
/*
* 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;
// 定义了一个名为NoteEditText的类它继承自Android SDK中的EditText类用于自定义笔记编辑文本框。
public class NoteEditText extends EditText {
// 类的成员变量,用于日志标记。
private static final String TAG = "NoteEditText";
// 索引变量,用于跟踪当前编辑的文本位置。
private int mIndex;
// 记录删除操作前光标的位置,用于处理删除操作。
private int mSelectionStartBeforeDelete;
// 定义几种常见的URL协议用于识别电话、http链接和邮件。
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
// 一个映射将不同的URL协议映射到对应的字符串资源用于上下文菜单中显示。
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
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);
}
// 定义一个内部接口,用于监听文本编辑的变化。
public interface OnTextViewChangeListener {
// 当删除键被按下且文本为空时调用。
void onEditTextDelete(int index, String text);
// 当回车键被按下时调用。
void onEditTextEnter(int index, String text);
// 当文本发生变化时调用。
void onTextChange(int index, boolean hasText);
}
// 接口的实例,用于回调文本编辑的变化。
private OnTextViewChangeListener mOnTextViewChangeListener;
// NoteEditText的构造函数只接收一个Context参数。
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
}
// 设置当前编辑文本的索引。
public void setIndex(int index) {
mIndex = index;
}
// 设置文本编辑变化的监听器。
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
// NoteEditText的构造函数接收Context和AttributeSet参数。
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
// NoteEditText的构造函数接收Context、AttributeSet和defStyle参数。
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// 这里有一个TODO注释提示这里是一个自动生成的构造函数体可能需要根据需要进行修改。
// TODO Auto-generated constructor stub
}
// 重写onTouchEvent方法处理触摸事件主要用于移动光标位置。
@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);
}
// 重写onKeyDown方法处理按键按下事件特别是回车和删除键。
@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);
}
// 重写onKeyUp方法处理按键释放事件特别是删除和回车键。
@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);
}
// 重写onFocusChanged方法处理焦点变化事件用于更新文本变化。
@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);
}
// 重写onCreateContextMenu方法创建上下文菜单特别是处理URL链接。
@Override
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 获取选中的URLSpan对象。
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) {
// 根据URL协议找到对应的字符串资源。
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) {
// 点击时执行URLSpan的onClick事件。
urls[0].onClick(NoteEditText.this);
return true;
}
});
}
}
super.onCreateContextMenu(menu);
}
}

@ -0,0 +1,346 @@
/**
* MiCodeApache License 2.0
* 使
*/
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.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;
/**
* NoteItemData
*/
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, // 笔记项关联的Widget ID
NoteColumns.WIDGET_TYPE, // 笔记项关联的Widget类型
};
// 列索引,用于快速访问游标中的数据
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
// 笔记项的属性与PROJECTION数组中的列对应
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; // 笔记项关联的Widget ID
private int mWidgetType; // 笔记项关联的Widget类型
private String mName; // 与笔记项关联的联系人姓名
private String mPhoneNumber; // 与笔记项关联的电话号码
// 用于标记笔记项在列表中的位置
private boolean mIsLastItem; // 是否是最后一项
private boolean mIsFirstItem; // 是否是第一项
private boolean mIsOnlyOneItem; // 是否仅有一个笔记项
private boolean mIsOneNoteFollowingFolder; // 是否有一个笔记项跟在文件夹后面
private boolean mIsMultiNotesFollowingFolder; // 是否有多个笔记项跟在文件夹后面
/**
* CursorNoteItemData
* @param context 访
* @param 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的值
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);
// 如果笔记项的父ID是通话记录文件夹的ID则尝试获取关联的电话号码和联系人姓名
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);
}
/**
*
* @param cursor
*/
private void checkPostion(Cursor cursor) {
// 设置是否是最后一项、第一项和仅有一个笔记项的标记
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
// 如果笔记项类型是笔记并且不是第一项,则检查是否有笔记项跟在文件夹后面
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
// 如果前一项是文件夹或系统项,则检查后面是否有多个笔记项
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
} else {
mIsOneNoteFollowingFolder = true;
}
}
// 将游标移回原来的位置
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
// 下面是一系列getter方法用于获取笔记项的属性值。
/**
*
* @return truefalse
*/
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
/**
*
* @return truefalse
*/
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
/**
*
* @return truefalse
*/
public boolean isLast() {
return mIsLastItem;
}
/**
*
* @return
*/
public String getCallName() {
return mName;
}
/**
*
* @return truefalse
*/
public boolean isFirst() {
return mIsFirstItem;
}
/**
*
* @return truefalse
*/
public boolean isSingle() {
return mIsOnlyOneItem;
}
/**
* ID
* @return ID
*/
public long getId() {
return mId;
}
/**
*
* @return
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
* @return
*/
public long getCreatedDate() {
return mCreatedDate;
}
/**
*
* @return truefalse
*/
public boolean hasAttachment() {
return mHasAttachment;
}
/**
*
* @return
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
* @return ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
* @return ID
*/
public long getParentId() {
return mParentId;
}
/**
*
* @return
*/
public int getNotesCount() {
return mNotesCount;
}
/**
* ID
* IDID
* @return ID
*/
public long getFolderId() {
return mParentId;
}
/**
*
* @return
*/
public int getType() {
return mType;
}
/**
* Widget
* @return Widget
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* Widget ID
* @return Widget ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
*
* @return
*/
public String getSnippet() {
return mSnippet;
}
/**
*
* @return truefalse
*/
public boolean hasAlert() {
return (mAlertDate > 0);
}
/**
*
* @return truefalse
*/
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
*
* @param cursor
* @return
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,198 @@
/*
* 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;
// 导入所需的Android SDK类和包
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
// 导入Notes应用特有的数据类
import net.micode.notes.data.Notes;
// 导入Java的集合框架
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
// NotesListAdapter类继承自CursorAdapter用于显示和管理笔记列表
public class NotesListAdapter extends CursorAdapter {
// 类的成员变量
private static final String TAG = "NotesListAdapter"; // 用于日志标记
private Context mContext; // 上下文对象,用于访问应用程序的资源和类
private HashMap<Integer, Boolean> mSelectedIndex; // 存储每个列表项的选中状态
private int mNotesCount; // 笔记数量
private boolean mChoiceMode; // 是否处于选择模式
// AppWidgetAttribute内部类用于存储应用小部件的属性
public static class AppWidgetAttribute {
public int widgetId; // 小部件ID
public int widgetType; // 小部件类型
};
// 构造函数,初始化适配器
public NotesListAdapter(Context context) {
super(context, null); // 调用父类的构造函数
mSelectedIndex = new HashMap<Integer, Boolean>(); // 初始化选中状态的HashMap
mContext = context; // 保存上下文对象
mNotesCount = 0; // 初始化笔记数量为0
}
// 新建视图的方法,用于创建新的列表项视图
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); // 返回一个新的NotesListItem视图
}
// 绑定视图的方法,用于将数据绑定到视图上
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { // 检查视图是否是NotesListItem的实例
NoteItemData itemData = new NoteItemData(context, cursor); // 创建NoteItemData对象包含笔记数据
((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition())); // 绑定数据到视图
}
}
// 设置列表项的选中状态
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); // 在HashMap中设置选中状态
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<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); // 存储选中的笔记ID
for (Integer position : mSelectedIndex.keySet()) { // 遍历所有选中状态
if (mSelectedIndex.get(position) == true) { // 如果是选中的
Long id = getItemId(position); // 获取笔记ID
if (id != Notes.ID_ROOT_FOLDER) { // 如果ID不是根文件夹ID
itemSet.add(id); // 添加到集合中
}
}
}
return itemSet; // 返回集合
}
// 获取所有选中的应用小部件属性
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); // 存储选中的小部件属性
for (Integer position : mSelectedIndex.keySet()) { // 遍历所有选中状态
if (mSelectedIndex.get(position) == true) { // 如果是选中的
Cursor c = (Cursor) getItem(position); // 获取游标
if (c != null) { // 如果游标不为空
AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建小部件属性对象
NoteItemData item = new NoteItemData(mContext, c); // 创建NoteItemData对象
widget.widgetId = item.getWidgetId(); // 获取小部件ID
widget.widgetType = item.getWidgetType(); // 获取小部件类型
itemSet.add(widget); // 添加到集合中
} else {
Log.e(TAG, "Invalid cursor"); // 日志错误
return null; // 返回null
}
}
}
return itemSet; // 返回集合
}
// 获取选中的数量
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); // 获取所有选中状态的值
if (null == values) {
return 0; // 如果为空返回0
}
Iterator<Boolean> iter = values.iterator(); // 创建迭代器
int count = 0; // 初始化计数器
while (iter.hasNext()) { // 遍历所有值
if (true == iter.next()) { // 如果是选中的
count++; // 计数器加1
}
}
return count; // 返回计数
}
// 检查是否全部选中
public boolean isAllSelected() {
int checkedCount = getSelectedCount(); // 获取选中的数量
return (checkedCount != 0 && checkedCount == mNotesCount); // 如果选中数量不为0且等于笔记数量则返回true
}
// 检查某个位置的项是否被选中
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { // 如果HashMap中没有这个位置的值
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; // 初始化笔记数量为0
for (int i = 0; i < getCount(); i++) { // 遍历所有项
Cursor c = (Cursor) getItem(i); // 获取游标
if (c != null) { // 如果游标不为空
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { // 如果是笔记类型
mNotesCount++; // 笔记数量加1
}
} else {
Log.e(TAG, "Invalid cursor"); // 日志错误
return; // 返回
}
}
}
}

@ -0,0 +1,138 @@
/*
* 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;
// 导入所需的Android SDK类和包
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;
// 导入Notes应用特有的资源和数据类
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
// NotesListItem类继承自LinearLayout用于显示单个笔记列表项的视图
public class NotesListItem extends LinearLayout {
// 类的成员变量
private ImageView mAlert; // 用于显示提醒图标的ImageView
private TextView mTitle; // 显示标题的TextView
private TextView mTime; // 显示时间的TextView
private TextView mCallName; // 显示来电姓名的TextView
private NoteItemData mItemData; // 包含笔记数据的NoteItemData对象
private CheckBox mCheckBox; // 用于选择模式的CheckBox
// 构造函数,初始化视图
public NotesListItem(Context context) {
super(context); // 调用父类的构造函数
inflate(context, R.layout.note_item, this); // 将布局文件inflate到当前视图中
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); // 获取布局中的ImageView
mTitle = (TextView) findViewById(R.id.tv_title); // 获取布局中的TextView
mTime = (TextView) findViewById(R.id.tv_time); // 获取布局中的TextView
mCallName = (TextView) findViewById(R.id.tv_name); // 获取布局中的TextView
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); // 获取布局中的CheckBox
}
// bind方法用于将数据绑定到视图上
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 根据是否处于选择模式和笔记类型设置CheckBox的可见性和选中状态
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
mCheckBox.setVisibility(View.GONE);
}
mItemData = data; // 保存NoteItemData对象
// 根据笔记数据的不同类型,设置不同的视图显示
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
// 如果是通话记录文件夹
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
// 如果是通话记录文件夹下的笔记
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
} else {
// 其他类型的笔记
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) {
// 如果是文件夹
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
} else {
// 普通笔记
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
// 设置时间显示
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 设置背景
setBackground(data);
}
// setBackground方法用于设置视图的背景
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());
}
}
// getItemData方法用于获取当前项的NoteItemData对象
public NoteItemData getItemData() {
return mItemData;
}
}

@ -0,0 +1,397 @@
/*
* 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;
// 导入所需的Android SDK类和包
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;
// 导入Notes应用特有的资源和数据类
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;
// NotesPreferenceActivity类继承自PreferenceActivity用于显示和处理应用的设置界面
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";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities";
// 类的成员变量
private PreferenceCategory mAccountCategory; // 账户设置的PreferenceCategory
private GTaskReceiver mReceiver; // 用于接收同步状态广播的BroadcastReceiver
private Account[] mOriAccounts; // 原始账户数组
private boolean mHasAddedAccount; // 是否添加了账户
// onCreate方法Activity创建时调用
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// 设置ActionBar的返回键
getActionBar().setDisplayHomeAsUpEnabled(true);
// 从XML资源文件中添加偏好设置
addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
mReceiver = new GTaskReceiver(); // 创建BroadcastReceiver
IntentFilter filter = new IntentFilter(); // 创建IntentFilter
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); // 添加过滤的Action
registerReceiver(mReceiver, filter); // 注册BroadcastReceiver
mOriAccounts = null; // 初始化原始账户数组
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); // 从XML布局文件中inflate头部视图
getListView().addHeaderView(header, null, true); // 将头部视图添加到ListView中
}
// onResume方法Activity回到前台时调用
@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(); // 刷新用户界面
}
// onDestroy方法Activity销毁时调用
@Override
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver); // 注销BroadcastReceiver
}
super.onDestroy();
}
// loadAccountPreference方法加载账户偏好设置
private void loadAccountPreference() {
mAccountCategory.removeAll(); // 移除所有账户偏好设置
Preference accountPref = new Preference(this); // 创建新的Preference
final String defaultAccount = getSyncAccountName(this); // 获取默认同步账户名
accountPref.setTitle(getString(R.string.preferences_account_title)); // 设置标题
accountPref.setSummary(getString(R.string.preferences_account_summary)); // 设置摘要
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { // 设置Preference点击事件监听器
public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) { // 如果没有正在同步
if (TextUtils.isEmpty(defaultAccount)) { // 如果默认账户名为空
// 第一次设置账户
showSelectAccountAlertDialog(); // 显示选择账户的AlertDialog
} else {
// 如果账户已经设置,提示用户风险
showChangeAccountConfirmAlertDialog(); // 显示确认更改账户的AlertDialog
}
} else {
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); // 显示不能更改账户的Toast
}
return true; // 返回true表示已经处理了点击事件
}
});
mAccountCategory.addPreference(accountPref); // 将新的Preference添加到账户设置中
}
// loadSyncButton方法加载同步按钮
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button); // 获取同步按钮
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); // 获取最后同步时间的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); // 设置TextView可见
} else { // 如果没有正在同步
long lastSyncTime = getLastSyncTime(this); // 获取最后同步时间
if (lastSyncTime != 0) { // 如果最后同步时间不为0
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime))); // 设置最后同步时间字符串
lastSyncTimeView.setVisibility(View.VISIBLE); // 设置TextView可见
} else {
lastSyncTimeView.setVisibility(View.GONE); // 设置TextView不可见
}
}
}
// refreshUI方法用于刷新设置界面的用户界面
private void refreshUI() {
loadAccountPreference(); // 加载账户偏好设置
loadSyncButton(); // 加载同步按钮状态
}
// showSelectAccountAlertDialog方法显示选择账户的AlertDialog
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 创建AlertDialog.Builder对象
// inflate对话框标题布局
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); // 设置PositiveButton这里没有文本和监听器
Account[] accounts = getGoogleAccounts(); // 获取Google账户数组
String defAccount = getSyncAccountName(this); // 获取当前同步账户名
mOriAccounts = accounts; // 保存原始账户数组
mHasAddedAccount = false; // 初始化是否添加账户标志为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(); // 刷新用户界面
}
});
}
// inflate添加账户的布局
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; // 设置添加账户标志为true
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); // 创建添加账户的Intent
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { // 设置Authorities过滤
"gmail-ls"
});
startActivityForResult(intent, -1); // 启动结果Activity
dialog.dismiss(); // 关闭对话框
}
});
}
// showChangeAccountConfirmAlertDialog方法显示更改账户的确认AlertDialog
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); // 创建AlertDialog.Builder对象
// inflate对话框标题布局
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, // 设置标题文本
getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); // 设置副标题文本
dialogBuilder.setCustomTitle(titleView); // 设置自定义标题
CharSequence[] menuItemArray = new CharSequence[] { // 创建菜单项数组
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel)
};
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { // 设置点击事件监听器
public void onClick(DialogInterface dialog, int which) {
if (which == 0) { // 如果点击更改账户
showSelectAccountAlertDialog(); // 显示选择账户对话框
} else if (which == 1) { // 如果点击移除账户
removeSyncAccount(); // 移除同步账户
refreshUI(); // 刷新用户界面
}
}
});
dialogBuilder.show(); // 显示对话框
}
// getGoogleAccounts方法获取Google账户数组
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); // 获取AccountManager对象
return accountManager.getAccountsByType("com.google"); // 获取类型为"com.google"的账户数组
}
// setSyncAccount方法设置同步账户
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { // 如果当前同步账户名不等于传入账户名
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取SharedPreferences对象
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);
// 清除本地gtask相关信息
new Thread(new Runnable() { // 创建新线程
public void run() {
ContentValues values = new ContentValues(); // 创建ContentValues对象
values.put(NoteColumns.GTASK_ID, ""); // 清除GTASK_ID
values.put(NoteColumns.SYNC_ID, 0); // 清除SYNC_ID
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 更新笔记数据
}
}).start();
Toast.makeText(NotesPreferenceActivity.this, // 显示设置账户成功的Toast
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
// removeSyncAccount方法移除同步账户
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取SharedPreferences对象
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(); // 提交更改
// 清除本地gtask相关信息
new Thread(new Runnable() { // 创建新线程
public void run() {
ContentValues values = new ContentValues(); // 创建ContentValues对象
values.put(NoteColumns.GTASK_ID, ""); // 清除GTASK_ID
values.put(NoteColumns.SYNC_ID, 0); // 清除SYNC_ID
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 更新笔记数据
}
}).start();
}
// getSyncAccountName方法获取同步账户名
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取SharedPreferences对象
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); // 获取同步账户名,如果没有则返回空字符串
}
// setLastSyncTime方法设置最后同步时间
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取SharedPreferences对象
SharedPreferences.Editor editor = settings.edit(); // 获取编辑器
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); // 设置最后同步时间
editor.commit(); // 提交更改
}
// getLastSyncTime方法获取最后同步时间
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取SharedPreferences对象
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); // 获取最后同步时间如果没有则返回0
}
// GTaskReceiver类继承自BroadcastReceiver用于接收同步状态广播
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); // 获取同步状态TextView
syncStatus.setText(intent.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG)); // 设置同步进度文本
}
}
}
// onOptionsItemSelected方法处理选项菜单项的点击事件
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: // 如果点击的是home键
Intent intent = new Intent(this, NotesListActivity.class); // 创建Intent跳转到NotesListActivity
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 添加标记清除之前的Activity
startActivity(intent); // 启动新的Activity
return true; // 返回true表示已经处理了点击事件
default: // 默认情况
return false; // 返回false表示没有处理点击事件
}
}
}
Loading…
Cancel
Save