Compare commits

..

1 Commits

Author SHA1 Message Date
Nihengshan fe88152ff1 注释
1 year ago

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

@ -0,0 +1,147 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
// 用于处理与Google任务GTask同步相关操作的服务类
public class GTaskSyncService extends Service {
// 用于在意图中指定同步操作类型的字符串常量
public final static String ACTION_STRING_NAME = "sync_action_type";
// 开始同步操作的常量
public final static int ACTION_START_SYNC = 0;
// 取消同步操作的常量
public final static int ACTION_CANCEL_SYNC = 1;
// 无效操作的常量
public final static int ACTION_INVALID = 2;
// 用于广播同步服务状态的意图动作常量
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
// 广播中表示是否正在同步的键
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
// 广播中表示同步进度消息的键
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// 用于执行同步任务的异步任务对象
private static GTaskASyncTask mSyncTask = null;
// 用于存储同步进度消息的字符串
private static String mSyncProgress = "";
// 开始同步操作的私有方法
private void startSync() {
if (mSyncTask == null) {
// 创建一个新的GTaskASyncTask实例并传入当前服务实例和完成监听器
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() {
// 当同步任务完成时将mSyncTask设置为null发送广播并停止服务
mSyncTask = null;
sendBroadcast("");
stopSelf();
}
});
sendBroadcast("");
// 执行异步任务
mSyncTask.execute();
}
}
// 取消同步操作的私有方法
private void cancelSync() {
if (mSyncTask!= null) {
mSyncTask.cancelSync();
}
}
// 服务创建时调用初始化mSyncTask为null
@Override
public void onCreate() {
mSyncTask = null;
}
// 服务启动时调用,根据传入的意图执行相应的同步操作
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
if (bundle!= null && bundle.containsKey(ACTION_STRING_NAME)) {
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC:
startSync();
break;
case ACTION_CANCEL_SYNC:
cancelSync();
break;
default:
break;
}
return START_STICKY;
}
return super.onStartCommand(intent, flags, startId);
}
// 当系统内存不足时调用,取消正在进行的同步任务
@Override
public void onLowMemory() {
if (mSyncTask!= null) {
mSyncTask.cancelSync();
}
}
// 服务绑定操作返回null表示不支持绑定
public IBinder onBind(Intent intent) {
return null;
}
// 发送同步服务状态广播的方法
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask!= null);
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
sendBroadcast(intent);
}
// 静态方法,用于在活动中启动同步服务(开始同步操作)
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent);
}
// 静态方法,用于取消同步操作
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
// 静态方法,判断是否正在进行同步操作
public static boolean isSyncing() {
return mSyncTask!= null;
}
// 静态方法,获取同步进度消息
public static String getProgressString() {
return mSyncProgress;
}
}

@ -0,0 +1,143 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
// 抽象类作为笔记小部件的提供者基类继承自AppWidgetProvider
public abstract class NoteWidgetProvider extends AppWidgetProvider {
// 查询笔记小部件信息所需的投影列数组
public static final String[] PROJECTION = new String[]{
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
};
// 投影列中ID列的索引
public static final int COLUMN_ID = 0;
// 投影列中背景颜色ID列的索引
public static final int COLUMN_BG_COLOR_ID = 1;
// 投影列中片段内容列的索引
public static final int COLUMN_SNIPPET = 2;
// 日志标签
private static final String TAG = "NoteWidgetProvider";
// 当小部件被删除时调用,用于清理与小部件相关的笔记数据
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < appWidgetIds.length; i++) {
context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
new String[]{String.valueOf(appWidgetIds[i])});
}
}
// 获取指定小部件ID的笔记小部件信息的游标
private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[]{String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
}
// 更新小部件的方法,可被子类调用
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false);
}
// 实际更新小部件的私有方法
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {
if (appWidgetIds[i]!= AppWidgetManager.INVALID_APPWIDGET_ID) {
int bgId = ResourceParser.getDefaultBgId(context);
String snippet = "";
Intent intent = new Intent(context, NoteEditActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
if (c!= null && c.moveToFirst()) {
if (c.getCount() > 1) {
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return;
}
snippet = c.getString(COLUMN_SNIPPET);
bgId = c.getInt(COLUMN_BG_COLOR_ID);
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW);
} else {
snippet = context.getResources().getString(R.string.widget_havenot_content);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
}
if (c!= null) {
c.close();
}
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
// 根据隐私模式生成不同的PendingIntent
PendingIntent pendingIntent = null;
if (privacyMode) {
rv.setTextViewText(R.id.widget_text,
context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else {
rv.setTextViewText(R.id.widget_text, snippet);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
}
}
}
// 抽象方法用于获取背景资源ID由子类实现
protected abstract int getBgResourceId(int bgId);
// 抽象方法用于获取布局ID由子类实现
protected abstract int getLayoutId();
// 抽象方法,用于获取小部件类型,由子类实现
protected abstract int getWidgetType();
}

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

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

@ -0,0 +1,148 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
// 表示笔记列表中的每一项继承自LinearLayout用于展示笔记的相关信息
public class NotesListItem extends LinearLayout {
// 用于显示提醒图标(如闹钟图标)
private ImageView mAlert;
// 用于显示笔记标题或文件夹名称
private TextView mTitle;
// 用于显示笔记的修改时间或相对时间
private TextView mTime;
// 用于显示通话记录的联系人姓名(如果适用)
private TextView mCallName;
// 存储当前列表项的数据
private NoteItemData mItemData;
// 用于在选择模式下显示的复选框
private CheckBox mCheckBox;
// 构造函数,初始化视图并查找相关子视图
public NotesListItem(Context context) {
super(context);
// 加载布局文件note_item.xml到当前视图
inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
// 绑定数据到视图并根据条件设置视图的显示状态
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 如果处于选择模式且数据类型为笔记类型,则显示复选框并设置其选中状态
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
// 否则隐藏复选框
mCheckBox.setVisibility(View.GONE);
}
mItemData = data;
// 如果数据的ID表示通话记录文件夹
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) {
// 如果数据的父ID是通话记录文件夹即通话记录项
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
// 设置标题的文本样式为次要项目样式
mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem);
// 设置标题文本为格式化后的片段内容
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
} else {
mCallName.setVisibility(View.GONE);
// 设置标题的文本样式为主要项目样式
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
if (data.getType() == Notes.TYPE_FOLDER) {
// 如果是文件夹类型,设置标题文本为文件夹名称加上文件数量
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
} else {
// 如果是普通笔记类型,设置标题文本为格式化后的片段内容
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
// 设置时间文本为相对时间格式
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 根据数据设置背景资源
setBackground(data);
}
// 根据数据设置背景资源
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
if (data.getType() == Notes.TYPE_NOTE) {
// 如果是笔记类型,根据笔记的位置和状态设置不同的背景资源
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
// 如果是文件夹类型,设置文件夹的背景资源
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
// 获取当前列表项的数据
public NoteItemData getItemData() {
return mItemData;
}
}

@ -0,0 +1,433 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
// 用于管理笔记应用的偏好设置的活动类
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;
// 用于接收同步服务广播的接收器
private GTaskReceiver mReceiver;
// 原始账户列表(用于检测账户变化)
private Account[] mOriAccounts;
// 标记是否添加了新账户
private boolean mHasAddedAccount;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
// 使用应用图标作为导航返回按钮
getActionBar().setDisplayHomeAsUpEnabled(true);
// 加载偏好设置资源文件
addPreferencesFromResource(R.xml.preferences);
// 获取同步账户偏好设置类别
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
// 创建并注册同步服务广播接收器
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);
mOriAccounts = null;
// 为列表视图添加头部视图(用于显示额外信息)
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);
}
@Override
protected void onResume() {
super.onResume();
// 如果添加了新账户,自动设置同步账户
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
if (mOriAccounts!= null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) {
boolean found = false;
for (Account accountOld : mOriAccounts) {
if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true;
break;
}
}
if (!found) {
setSyncAccount(accountNew.name);
break;
}
}
}
}
// 刷新用户界面
refreshUI();
}
@Override
protected void onDestroy() {
// 注销广播接收器
if (mReceiver!= null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
}
// 加载同步账户偏好设置
private void loadAccountPreference() {
mAccountCategory.removeAll();
// 创建一个新的偏好设置项
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);
// 设置偏好设置项的标题和摘要
accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary));
// 设置偏好设置项的点击监听器
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// 如果同步服务未在运行
if (!GTaskSyncService.isSyncing()) {
// 如果尚未设置同步账户
if (TextUtils.isEmpty(defaultAccount)) {
// 显示选择账户的对话框
showSelectAccountAlertDialog();
} else {
// 如果已经设置了同步账户,显示更改账户的确认对话框
showChangeAccountConfirmAlertDialog();
}
} else {
// 如果同步服务正在运行,显示提示信息
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
// 将偏好设置项添加到同步账户类别中
mAccountCategory.addPreference(accountPref);
}
// 加载同步按钮相关设置
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// 设置同步按钮的文本和点击监听器
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
}
// 根据是否设置了同步账户来启用或禁用同步按钮
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// 设置最后同步时间的显示
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime!= 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
lastSyncTimeView.setVisibility(View.GONE);
}
}
}
// 刷新用户界面,包括加载账户偏好设置和同步按钮设置
private void refreshUI() {
loadAccountPreference();
loadSyncButton();
}
// 显示选择账户的对话框
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 设置对话框的标题视图
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);
// 先不设置对话框的确定按钮
dialogBuilder.setPositiveButton(null, null);
// 获取谷歌账户列表
Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);
mOriAccounts = accounts;
mHasAddedAccount = false;
if (accounts.length > 0) {
// 创建账户名称的字符序列数组用于显示在对话框中
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
int checkedItem = -1;
int index = 0;
for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
}
items[index++] = account.name;
}
// 设置对话框为单选列表模式,并设置点击监听器
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString());
dialog.dismiss();
refreshUI();
}
});
}
// 设置对话框的视图(包含添加账户的提示)
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
// 显示对话框
final AlertDialog dialog = dialogBuilder.show();
// 设置添加账户视图的点击监听器
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[]{
"gmail-ls"
});
startActivityForResult(intent, -1);
dialog.dismiss();
}
});
}
// 显示更改账户的确认对话框
private void showChangeAccountConfirmAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 设置对话框的标题视图
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this)));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView);
// 设置对话框的菜单项
CharSequence[] menuItemArray = new CharSequence[]{
getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel)
};
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showSelectAccountAlertDialog();
} else if (which == 1) {
removeSyncAccount();
refreshUI();
}
}
});
// 显示对话框
dialogBuilder.show();
}
// 获取谷歌账户列表
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
// 设置同步账户
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (account!= null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
editor.commit();
// 清除最后同步时间
setLastSyncTime(this, 0);
// 清除本地与gtask相关的信息在新线程中执行
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
// 移除同步账户
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
}
editor.commit();
// 清除本地与gtask相关的信息在新线程中执行
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
// 获取同步账户名称
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
// 设置最后同步时间
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
}
// 获取最后同步时间
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
// 内部类,用于接收同步服务的广播并更新界面
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
}
}
}
// 处理选项菜单点击事件
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return false;
}
}
}

@ -0,0 +1,253 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
// NotesListAdapter类继承自CursorAdapter用于在UI组件如ListView中展示笔记列表数据并处理相关交互逻辑
public class NotesListAdapter extends CursorAdapter {
// 用于日志记录的标签,方便在调试时识别日志来源
private static final String TAG = "NotesListAdapter";
// Android上下文对象用于获取系统服务、资源等
private Context mContext;
// 用于存储选中项的位置和选中状态的哈希表键为位置Integer值为是否选中Boolean
private HashMap<Integer, Boolean> mSelectedIndex;
// 记录笔记的数量
private int mNotesCount;
// 表示是否处于选择模式的布尔变量
private boolean mChoiceMode;
// 内部类用于存储小部件的属性包括小部件ID和类型
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
};
// 构造函数初始化NotesListAdapter实例
public NotesListAdapter(Context context) {
// 调用父类CursorAdapter的构造函数传入上下文和初始游标为null
super(context, null);
// 初始化选中项哈希表
mSelectedIndex = new HashMap<Integer, Boolean>();
// 保存上下文对象
mContext = context;
// 初始化笔记数量为0
mNotesCount = 0;
}
// 创建新的视图用于在ListView中显示每个笔记项
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建并返回一个NotesListItem实例作为新的视图
return new NotesListItem(context);
}
// 将数据绑定到视图上,根据视图类型进行相应的设置
@Override
public void bindView(View view, Context context, Cursor cursor) {
// 如果视图是NotesListItem类型
if (view instanceof NotesListItem) {
// 创建NoteItemData实例用于获取笔记数据
NoteItemData itemData = new NoteItemData(context, cursor);
// 调用NotesListItem的bind方法传递上下文、笔记数据、选择模式和当前项的选中状态
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
// 设置指定位置的笔记项的选中状态,并通知数据集已改变
public void setCheckedItem(final int position, final boolean checked) {
// 将指定位置的选中状态存入哈希表
mSelectedIndex.put(position, checked);
// 通知数据集改变以便ListView等UI组件更新显示
notifyDataSetChanged();
}
// 判断是否处于选择模式
public boolean isInChoiceMode() {
return mChoiceMode;
}
// 设置选择模式,清除之前的选中状态
public void setChoiceMode(boolean mode) {
// 清空选中项哈希表
mSelectedIndex.clear();
// 设置选择模式状态
mChoiceMode = mode;
}
// 全选或全不选笔记项根据传入的checked值进行设置
public void selectAll(boolean checked) {
// 获取游标对象
Cursor cursor = getCursor();
// 遍历所有笔记项
for (int i = 0; i < getCount(); i++) {
// 将游标移动到指定位置
if (cursor.moveToPosition(i)) {
// 如果笔记类型为普通笔记Notes.TYPE_NOTE
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
// 设置该项的选中状态
setCheckedItem(i, checked);
}
}
}
}
// 获取选中笔记项的ID集合排除根文件夹ID
public HashSet<Long> getSelectedItemIds() {
// 创建用于存储选中项ID的HashSet
HashSet<Long> itemSet = new HashSet<Long>();
// 遍历选中项哈希表的键(位置)
for (Integer position : mSelectedIndex.keySet()) {
// 如果该项被选中
if (mSelectedIndex.get(position) == true) {
// 获取该项的ID
Long id = getItemId(position);
// 如果ID是根文件夹ID记录错误日志不应该发生
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
// 将ID添加到集合中
itemSet.add(id);
}
}
}
// 返回选中项ID集合
return itemSet;
}
// 获取选中小部件的属性集合
public HashSet<AppWidgetAttribute> getSelectedWidget() {
// 创建用于存储选中小部件属性的HashSet
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实例
AppWidgetAttribute widget = new AppWidgetAttribute();
// 创建NoteItemData实例用于获取小部件相关数据
NoteItemData item = new NoteItemData(mContext, c);
// 设置小部件ID和类型
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
// 将小部件属性添加到集合中
itemSet.add(widget);
// 注意:不要在这里关闭游标,只有适配器可以关闭它
} else {
// 如果游标为空,记录错误日志
Log.e(TAG, "Invalid cursor");
// 返回null表示获取失败
return null;
}
}
}
// 返回选中小部件属性集合
return itemSet;
}
// 获取选中项的数量
public int getSelectedCount() {
// 获取选中项哈希表的值集合(选中状态集合)
Collection<Boolean> values = mSelectedIndex.values();
// 如果值集合为空返回0
if (null == values) {
return 0;
}
// 创建迭代器,用于遍历选中状态集合
Iterator<Boolean> iter = values.iterator();
// 记录选中数量
int count = 0;
// 遍历选中状态集合
while (iter.hasNext()) {
// 如果该项被选中数量加1
if (true == iter.next()) {
count++;
}
}
// 返回选中数量
return count;
}
// 判断是否所有笔记项都被选中
public boolean isAllSelected() {
// 获取选中项数量
int checkedCount = getSelectedCount();
// 如果选中数量不为0且等于笔记总数mNotesCount返回true否则返回false
return (checkedCount!= 0 && checkedCount == mNotesCount);
}
// 判断指定位置的笔记项是否被选中
public boolean isSelectedItem(final int position) {
// 如果指定位置的选中状态为null返回false
if (null == mSelectedIndex.get(position)) {
return 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() {
// 初始化笔记数量为0
mNotesCount = 0;
// 遍历所有笔记项
for (int i = 0; i < getCount(); i++) {
// 获取指定位置的游标
Cursor c = (Cursor) getItem(i);
// 如果游标不为空
if (c!= null) {
// 如果笔记类型为普通笔记Notes.TYPE_NOTE数量加1
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
} else {
// 如果游标为空,记录错误日志并返回
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}
Loading…
Cancel
Save