Compare commits

..

No commits in common. 'main' and 'shenyifei' have entirely different histories.

@ -1,377 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId;
private String mSnippet;
private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
@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);
}
Intent intent = getIntent();
try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
mPlayer = new MediaPlayer();
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
} else {
finish();
}
}
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
private void playAlarmSound() {
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
mPlayer.setDataSource(this, url);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet);
dialog.setPositiveButton(R.string.notealert_ok, this);
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
dialog.show().setOnDismissListener(this);
}
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
break;
default:
break;
}
}
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
}
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
}
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
// AlarmAlertActivity类继承自Activity用于处理闹钟提醒相关的界面展示、声音播放以及用户交互操作
// 同时实现了OnClickListener和OnDismissListener接口分别处理对话框的点击事件和消失事件
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
// 用于存储便签的唯一标识符,后续通过此标识符来获取对应的便签相关信息
private long mNoteId;
// 用于存储便签内容的片段,会按照一定规则进行截取展示
private String mSnippet;
// 定义便签内容片段展示的最大长度为60个字符
private static final int SNIPPET_PREW_MAX_LEN = 60;
// MediaPlayer对象用于播放闹钟提醒的声音
MediaPlayer mPlayer;
// onCreate方法是在Activity创建时调用的生命周期方法进行一系列初始化操作
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 请求去除Activity的标题栏使界面更加简洁专注于展示提醒相关内容
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 获取当前Activity的窗口对象后续用于设置窗口的相关属性
final Window win = getWindow();
// 添加FLAG_SHOW_WHEN_LOCKED标志使得Activity窗口在屏幕锁定时也能够显示出来方便用户看到提醒信息
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 intent = getIntent();
try {
// 尝试从Intent携带的数据中解析出便签的唯一标识符mNoteId
// 通过获取Intent中数据的路径片段假设数据的格式符合一定规范此处取路径中的第二个片段并转换为long类型
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 使用DataUtils工具类的方法根据mNoteId从内容解析器中获取便签内容的片段并赋值给mSnippet
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 如果获取到的便签内容片段长度大于预设的最大长度SNIPPET_PREW_MAX_LEN
if (mSnippet.length() > SNIPPET_PREW_MAX_LEN) {
// 则对内容进行截取取前SNIPPET_PREW_MAX_LEN个字符并拼接上特定的提示字符串从资源文件中获取
mSnippet = mSnippet.substring(0, SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info);
}
} catch (IllegalArgumentException e) {
// 如果在解析过程中出现IllegalArgumentException异常例如数据格式不正确等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
// 直接返回,不再进行后续的初始化操作
return;
}
// 创建MediaPlayer对象用于后续播放闹钟提醒的声音
mPlayer = new MediaPlayer();
// 通过DataUtils工具类判断该便签在数据库中是否可见根据便签的唯一标识符mNoteId和便签类型Notes.TYPE_NOTE来判断
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 如果便签可见则调用showActionDialog方法弹出操作对话框向用户展示相关信息并提供操作按钮
showActionDialog();
// 同时调用playAlarmSound方法开始播放闹钟提醒的声音
playAlarmSound();
} else {
// 如果便签不可见直接调用finish方法结束当前的Activity无需进行其他展示和操作
finish();
}
}
// isScreenOn方法用于判断屏幕当前是否处于开启状态
private boolean isScreenOn() {
// 获取系统的PowerManager服务PowerManager用于管理电源相关的操作和获取电源状态信息
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// 调用PowerManager的isScreenOn方法来获取屏幕的开启状态返回true表示屏幕开启false表示屏幕关闭
return pm.isScreenOn();
}
// playAlarmSound方法用于播放闹钟提醒的声音
private void playAlarmSound() {
// 通过RingtoneManager获取系统默认的闹钟铃声的Uri以便后续设置为MediaPlayer的数据源
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 从系统设置中获取受静音模式影响的音频流相关设置值,用于判断闹钟声音的播放设置情况
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 判断获取到的设置值中是否包含闹钟音频流对应的标志位(通过位运算进行判断)
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM))!= 0) {
// 如果包含则将MediaPlayer的音频流类型设置为获取到的这个设置值按照系统的静音相关设置来播放声音
mPlayer.setAudioStreamType(silentModeStreams);
} else {
// 如果不包含则将MediaPlayer的音频流类型设置为正常的闹钟音频流类型AudioManager.STREAM_ALARM
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
// 使用获取到的Uri为MediaPlayer设置数据源指定要播放的音频资源
mPlayer.setDataSource(this, url);
// 调用prepare方法准备播放声音进行必要的缓冲和初始化操作
mPlayer.prepare();
// 设置MediaPlayer为循环播放模式使得闹钟声音会一直循环播放直到被停止
mPlayer.setLooping(true);
// 调用start方法开始播放声音触发闹钟提醒的音频播放功能
mPlayer.start();
} catch (IllegalArgumentException e) {
// 如果在设置数据源、准备播放等过程中出现IllegalArgumentException异常例如参数不合法等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
} catch (SecurityException e) {
// 如果出现SecurityException异常例如没有权限访问音频资源等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
} catch (IllegalStateException e) {
// 如果出现IllegalStateException异常例如MediaPlayer状态不正确等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
} catch (IOException e) {
// 如果出现IOException异常例如读取音频数据源出错等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
}
}
// showActionDialog方法用于创建并显示一个包含便签信息和操作按钮的对话框方便用户进行相关操作
private void showActionDialog() {
// 创建一个AlertDialog的构建器对象传入当前Activity的Context用于构建对话框
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
// 设置对话框的标题为应用的名称,从资源文件中获取对应的字符串作为标题内容
dialog.setTitle(R.string.app_name);
// 设置对话框的消息内容为前面获取并处理后的便签内容片段mSnippet展示给用户查看
dialog.setMessage(mSnippet);
// 设置对话框的确定按钮PositiveButton按钮文本为R.string.notealert_ok同时将当前类实现了OnClickListener接口作为点击事件的监听器传入
// 点击确定按钮后会触发onClick方法中对应的逻辑处理
dialog.setPositiveButton(R.string.notealert_ok, this);
// 根据屏幕是否开启通过isScreenOn方法判断来决定是否添加“进入”按钮NegativeButton
if (isScreenOn()) {
// 如果屏幕开启则添加“进入”按钮按钮文本为R.string.notealert_enter同样将当前类作为点击事件监听器传入
dialog.setNegativeButton(R.string.notealert_enter, this);
}
// 调用dialog.show()方法显示对话框并为对话框设置消失监听器通过setOnDismissListener方法传入实现了OnDismissListener接口的当前类
// 这样在对话框消失时会触发onDismiss方法中的逻辑处理
dialog.show().setOnDismissListener(this);
}
// 实现OnClickListener接口的点击事件处理方法根据用户点击对话框中不同按钮来执行相应的操作
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 如果用户点击的是NegativeButton即前面设置的“进入”按钮如果屏幕开启时显示
case DialogInterface.BUTTON_NEGATIVE:
// 创建一个Intent用于启动NoteEditActivity通常用于进入便签的编辑界面
Intent intent = new Intent(this, NoteEditActivity.class);
// 设置Intent的动作Action为Intent.ACTION_VIEW表示查看相关内容的操作
intent.setAction(Intent.ACTION_VIEW);
// 通过putExtra方法将便签的唯一标识符mNoteId作为额外数据传递给要启动的NoteEditActivity
intent.putExtra(Intent.EXTRA_UID, mNoteId);
// 调用startActivity方法启动NoteEditActivity实现界面跳转进入便签编辑界面
startActivity(intent);
break;
default:
// 如果点击的是其他按钮这里目前只有PositiveButton情况暂时不做额外处理
break;
}
}
// 实现OnDismissListener接口的对话框消失事件处理方法在对话框消失时进行相关资源清理和Activity结束操作
@Override
public void onDismiss(DialogInterface dialog) {
// 调用stopAlarmSound方法停止正在播放的闹钟声音释放相关音频资源
stopAlarmSound();
// 调用finish方法结束当前的AlarmAlertActivity关闭该提醒界面
finish();
}
// stopAlarmSound方法用于停止并释放MediaPlayer资源避免资源浪费和内存泄漏等问题
private void stopAlarmSound() {
// 判断MediaPlayer对象是否为空如果不为空说明之前已经创建并正在使用
if (mPlayer!= null) {
// 调用stop方法停止正在播放的音频立即停止声音播放
mPlayer.stop();
// 调用release方法释放MediaPlayer占用的系统资源如音频播放相关的内存等
mPlayer.release();
// 将mPlayer对象赋值为null表示资源已经释放避免后续误操作
mPlayer = null;
}
}
}

@ -1,377 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId;
private String mSnippet;
private static final int SNIPPET_PREW_MAX_LEN = 60;
MediaPlayer mPlayer;
@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);
}
Intent intent = getIntent();
try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
mPlayer = new MediaPlayer();
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
showActionDialog();
playAlarmSound();
} else {
finish();
}
}
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
private void playAlarmSound() {
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
mPlayer.setDataSource(this, url);
mPlayer.prepare();
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name);
dialog.setMessage(mSnippet);
dialog.setPositiveButton(R.string.notealert_ok, this);
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
dialog.show().setOnDismissListener(this);
}
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, mNoteId);
startActivity(intent);
break;
default:
break;
}
}
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
}
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
}
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
// AlarmAlertActivity类继承自Activity用于处理闹钟提醒相关的界面展示、声音播放以及用户交互操作
// 同时实现了OnClickListener和OnDismissListener接口分别处理对话框的点击事件和消失事件
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
// 用于存储便签的唯一标识符,后续通过此标识符来获取对应的便签相关信息
private long mNoteId;
// 用于存储便签内容的片段,会按照一定规则进行截取展示
private String mSnippet;
// 定义便签内容片段展示的最大长度为60个字符
private static final int SNIPPET_PREW_MAX_LEN = 60;
// MediaPlayer对象用于播放闹钟提醒的声音
MediaPlayer mPlayer;
// onCreate方法是在Activity创建时调用的生命周期方法进行一系列初始化操作
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 请求去除Activity的标题栏使界面更加简洁专注于展示提醒相关内容
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 获取当前Activity的窗口对象后续用于设置窗口的相关属性
final Window win = getWindow();
// 添加FLAG_SHOW_WHEN_LOCKED标志使得Activity窗口在屏幕锁定时也能够显示出来方便用户看到提醒信息
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 intent = getIntent();
try {
// 尝试从Intent携带的数据中解析出便签的唯一标识符mNoteId
// 通过获取Intent中数据的路径片段假设数据的格式符合一定规范此处取路径中的第二个片段并转换为long类型
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 使用DataUtils工具类的方法根据mNoteId从内容解析器中获取便签内容的片段并赋值给mSnippet
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 如果获取到的便签内容片段长度大于预设的最大长度SNIPPET_PREW_MAX_LEN
if (mSnippet.length() > SNIPPET_PREW_MAX_LEN) {
// 则对内容进行截取取前SNIPPET_PREW_MAX_LEN个字符并拼接上特定的提示字符串从资源文件中获取
mSnippet = mSnippet.substring(0, SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info);
}
} catch (IllegalArgumentException e) {
// 如果在解析过程中出现IllegalArgumentException异常例如数据格式不正确等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
// 直接返回,不再进行后续的初始化操作
return;
}
// 创建MediaPlayer对象用于后续播放闹钟提醒的声音
mPlayer = new MediaPlayer();
// 通过DataUtils工具类判断该便签在数据库中是否可见根据便签的唯一标识符mNoteId和便签类型Notes.TYPE_NOTE来判断
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 如果便签可见则调用showActionDialog方法弹出操作对话框向用户展示相关信息并提供操作按钮
showActionDialog();
// 同时调用playAlarmSound方法开始播放闹钟提醒的声音
playAlarmSound();
} else {
// 如果便签不可见直接调用finish方法结束当前的Activity无需进行其他展示和操作
finish();
}
}
// isScreenOn方法用于判断屏幕当前是否处于开启状态
private boolean isScreenOn() {
// 获取系统的PowerManager服务PowerManager用于管理电源相关的操作和获取电源状态信息
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// 调用PowerManager的isScreenOn方法来获取屏幕的开启状态返回true表示屏幕开启false表示屏幕关闭
return pm.isScreenOn();
}
// playAlarmSound方法用于播放闹钟提醒的声音
private void playAlarmSound() {
// 通过RingtoneManager获取系统默认的闹钟铃声的Uri以便后续设置为MediaPlayer的数据源
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 从系统设置中获取受静音模式影响的音频流相关设置值,用于判断闹钟声音的播放设置情况
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 判断获取到的设置值中是否包含闹钟音频流对应的标志位(通过位运算进行判断)
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM))!= 0) {
// 如果包含则将MediaPlayer的音频流类型设置为获取到的这个设置值按照系统的静音相关设置来播放声音
mPlayer.setAudioStreamType(silentModeStreams);
} else {
// 如果不包含则将MediaPlayer的音频流类型设置为正常的闹钟音频流类型AudioManager.STREAM_ALARM
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
// 使用获取到的Uri为MediaPlayer设置数据源指定要播放的音频资源
mPlayer.setDataSource(this, url);
// 调用prepare方法准备播放声音进行必要的缓冲和初始化操作
mPlayer.prepare();
// 设置MediaPlayer为循环播放模式使得闹钟声音会一直循环播放直到被停止
mPlayer.setLooping(true);
// 调用start方法开始播放声音触发闹钟提醒的音频播放功能
mPlayer.start();
} catch (IllegalArgumentException e) {
// 如果在设置数据源、准备播放等过程中出现IllegalArgumentException异常例如参数不合法等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
} catch (SecurityException e) {
// 如果出现SecurityException异常例如没有权限访问音频资源等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
} catch (IllegalStateException e) {
// 如果出现IllegalStateException异常例如MediaPlayer状态不正确等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
} catch (IOException e) {
// 如果出现IOException异常例如读取音频数据源出错等情况
// 打印异常的栈信息,方便调试查找问题
e.printStackTrace();
}
}
// showActionDialog方法用于创建并显示一个包含便签信息和操作按钮的对话框方便用户进行相关操作
private void showActionDialog() {
// 创建一个AlertDialog的构建器对象传入当前Activity的Context用于构建对话框
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
// 设置对话框的标题为应用的名称,从资源文件中获取对应的字符串作为标题内容
dialog.setTitle(R.string.app_name);
// 设置对话框的消息内容为前面获取并处理后的便签内容片段mSnippet展示给用户查看
dialog.setMessage(mSnippet);
// 设置对话框的确定按钮PositiveButton按钮文本为R.string.notealert_ok同时将当前类实现了OnClickListener接口作为点击事件的监听器传入
// 点击确定按钮后会触发onClick方法中对应的逻辑处理
dialog.setPositiveButton(R.string.notealert_ok, this);
// 根据屏幕是否开启通过isScreenOn方法判断来决定是否添加“进入”按钮NegativeButton
if (isScreenOn()) {
// 如果屏幕开启则添加“进入”按钮按钮文本为R.string.notealert_enter同样将当前类作为点击事件监听器传入
dialog.setNegativeButton(R.string.notealert_enter, this);
}
// 调用dialog.show()方法显示对话框并为对话框设置消失监听器通过setOnDismissListener方法传入实现了OnDismissListener接口的当前类
// 这样在对话框消失时会触发onDismiss方法中的逻辑处理
dialog.show().setOnDismissListener(this);
}
// 实现OnClickListener接口的点击事件处理方法根据用户点击对话框中不同按钮来执行相应的操作
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 如果用户点击的是NegativeButton即前面设置的“进入”按钮如果屏幕开启时显示
case DialogInterface.BUTTON_NEGATIVE:
// 创建一个Intent用于启动NoteEditActivity通常用于进入便签的编辑界面
Intent intent = new Intent(this, NoteEditActivity.class);
// 设置Intent的动作Action为Intent.ACTION_VIEW表示查看相关内容的操作
intent.setAction(Intent.ACTION_VIEW);
// 通过putExtra方法将便签的唯一标识符mNoteId作为额外数据传递给要启动的NoteEditActivity
intent.putExtra(Intent.EXTRA_UID, mNoteId);
// 调用startActivity方法启动NoteEditActivity实现界面跳转进入便签编辑界面
startActivity(intent);
break;
default:
// 如果点击的是其他按钮这里目前只有PositiveButton情况暂时不做额外处理
break;
}
}
// 实现OnDismissListener接口的对话框消失事件处理方法在对话框消失时进行相关资源清理和Activity结束操作
@Override
public void onDismiss(DialogInterface dialog) {
// 调用stopAlarmSound方法停止正在播放的闹钟声音释放相关音频资源
stopAlarmSound();
// 调用finish方法结束当前的AlarmAlertActivity关闭该提醒界面
finish();
}
// stopAlarmSound方法用于停止并释放MediaPlayer资源避免资源浪费和内存泄漏等问题
private void stopAlarmSound() {
// 判断MediaPlayer对象是否为空如果不为空说明之前已经创建并正在使用
if (mPlayer!= null) {
// 调用stop方法停止正在播放的音频立即停止声音播放
mPlayer.stop();
// 调用release方法释放MediaPlayer占用的系统资源如音频播放相关的内存等
mPlayer.release();
// 将mPlayer对象赋值为null表示资源已经释放避免后续误操作
mPlayer = null;
}
}
}

@ -1,152 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
public class AlarmInitReceiver extends BroadcastReceiver {
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) {
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);
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
}
c.close();
}
}
}
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;
// AlarmInitReceiver类继承自BroadcastReceiver用于接收系统广播并处理与闹钟初始化相关的操作
// 其主要功能是从数据库中查询满足条件的便签记录,并为这些便签设置对应的闹钟提醒
public class AlarmInitReceiver extends BroadcastReceiver {
// 定义一个字符串数组,用于指定从数据库中查询时需要获取的列名
// 这里获取的是便签的唯一标识符ID和提醒日期ALERTED_DATE两列
private static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE
};
// 定义常量表示查询结果中ID列对应的索引位置方便后续从Cursor中获取数据
private static final int COLUMN_ID = 0;
// 定义常量表示查询结果中ALERTED_DATE列对应的索引位置方便后续从Cursor中获取数据
private static final int COLUMN_ALERTED_DATE = 1;
// onReceive方法是BroadcastReceiver的核心方法当接收到相应广播时会被调用
@Override
public void onReceive(Context context, Intent intent) {
// 获取当前系统的时间戳(以毫秒为单位),用于后续在数据库查询中作为比较条件,筛选出需要设置闹钟提醒的便签
long currentDate = System.currentTimeMillis();
// 通过ContentResolver查询数据库获取满足条件的便签记录信息
// 参数说明:
// 1. Notes.CONTENT_NOTE_URI指定查询的内容提供器的Uri指向便签相关的数据表
// 2. PROJECTION前面定义的要查询的列名数组即获取便签的ID和提醒日期两列数据
// 3. NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE查询条件筛选出提醒日期大于当前日期且类型为普通便签假设Notes.TYPE_NOTE代表普通便签类型的记录
// 4. new String[] { String.valueOf(currentDate) }:为查询条件中的占位符(?)提供实际的值,即当前日期
// 5. null表示按照默认的排序方式进行排序如果有需要也可以指定具体的排序规则
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);
// 判断查询结果的Cursor是否为空如果不为空说明有满足条件的便签记录
if (c!= null) {
// 将游标移动到查询结果的第一条记录位置如果有记录则返回true否则返回false
if (c.moveToFirst()) {
// 使用do-while循环遍历查询结果集处理每条满足条件的便签记录
do {
// 从Cursor中获取提醒日期这一列的值以长整型表示对应之前定义的COLUMN_ALERTED_DATE索引位置
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建一个Intent对象用于启动AlarmReceiver可能是处理闹钟提醒触发逻辑的广播接收器
Intent sender = new Intent(context, AlarmReceiver.class);
// 为Intent设置数据部分通过ContentUris工具类将便签的唯一标识符ID附加到便签内容提供器的Uri上
// 这样接收方可以根据这个Uri获取到具体是哪个便签的闹钟提醒触发了
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建一个PendingIntent对象用于包装前面创建的Intent使得它可以在稍后被触发例如作为闹钟触发时启动的目标意图
// 参数说明:
// 1. context当前的应用上下文环境
// 2. 0请求码这里暂时设置为0一般如果有多个不同用途的PendingIntent可以设置不同的请求码来区分
// 3. sender要包装的Intent对象即前面创建的启动AlarmReceiver的Intent
// 4. 0标志位这里暂时设置为0根据不同需求可以设置不同的标志来控制PendingIntent的行为
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
// 获取系统的AlarmManager服务AlarmManager用于管理和设置闹钟相关的操作
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 使用AlarmManager设置闹钟提醒具体参数含义如下
// 1. AlarmManager.RTC_WAKEUP闹钟类型表示在指定的时间alertDate唤醒设备并触发闹钟如果设备处于睡眠状态
// 2. alertDate设置闹钟触发的时间即从数据库中获取的该便签的提醒日期对应的时间戳以毫秒为单位
// 3. pendingIntent前面创建的PendingIntent对象当闹钟触发时会启动对应的Intent这里是启动AlarmReceiver
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext());
}
// 关闭游标,释放相关的系统资源,避免内存泄漏等问题,查询操作完成后需要及时关闭游标
c.close();
}
}
}

@ -1,60 +0,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.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent.setClass(context, AlarmAlertActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
package net.micode.notes.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
// AlarmReceiver类继承自BroadcastReceiver是一个广播接收器用于接收特定的广播消息并做出相应的响应。
// 在这个场景下大概率是接收与闹钟提醒相关的广播然后启动对应的闹钟提醒界面Activity。
public class AlarmReceiver extends BroadcastReceiver {
// onReceive方法是BroadcastReceiver类中最重要的方法当该广播接收器接收到与之匹配的广播时此方法会被调用。
// 它接收两个参数:
// 1. context表示当前应用的上下文环境通过它可以访问应用的各种资源、服务等内容。
// 2. intent包含了发送广播时所携带的信息例如额外的数据、动作Action在这里它可能携带了与闹钟提醒相关的一些标识信息等。
@Override
public void onReceive(Context context, Intent intent) {
// 通过intent.setClass方法重新设置该Intent要启动的目标Activity类为AlarmAlertActivity.class。
// 这意味着当这个Intent被启动时将会启动AlarmAlertActivity这个界面通常AlarmAlertActivity就是用于展示闹钟提醒具体内容如提醒的便签信息、播放提醒声音等的界面。
intent.setClass(context, AlarmAlertActivity.class);
// 为Intent添加FLAG_ACTIVITY_NEW_TASK标志。
// 这个标志的作用是如果当前应用处于后台或者没有任何任务栈存在的情况下添加此标志可以确保新启动的Activity能够在一个新的任务栈中被启动
// 避免出现因任务栈相关问题而导致Activity启动失败等异常情况保证闹钟提醒界面能够正常展示给用户。
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 使用传入的context上下文对象调用startActivity方法来启动经过上述设置后的Intent。
// 这样就会触发启动AlarmAlertActivity使得用户可以看到闹钟提醒的相关界面完成从接收到闹钟提醒广播到展示提醒界面的整个流程。
context.startActivity(intent);
}
}

@ -1,376 +0,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.tool;
// 导入必要的Android和Java类
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; // 导入Notes数据访问类
import net.micode.notes.data.Notes.DataColumns; // 导入Notes数据表的列定义
import net.micode.notes.data.Notes.DataConstants; // 导入Notes数据表的常量定义
import net.micode.notes.data.Notes.NoteColumns; // 导入Notes数据表的列定义
import java.io.File; // 提供文件和目录路径名的抽象表示形式
import java.io.FileNotFoundException; // 当试图打开文件失败时抛出的异常
import java.io.FileOutputStream; // 文件输出流,用于将数据写入文件
import java.io.IOException; // 当发生某种I/O异常时抛出的异常
import java.io.PrintStream; // 打印流,提供便利的打印方法
// 声明一个用于备份的工具类
public class BackupUtils {
// 定义日志标签
private static final String TAG = "BackupUtils";
// 单例模式相关变量
private static BackupUtils sInstance;
// 获取BackupUtils实例的静态方法使用同步关键字确保线程安全
public static synchronized BackupUtils getInstance(Context context) {
if (sInstance == null) {
sInstance = new BackupUtils(context);
}
return sInstance;
}
// 定义表示备份或恢复状态的常量
public static final int STATE_SD_CARD_UNMOUONTED = 0; // SD卡未挂载
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; // 备份文件不存在
public static final int STATE_DATA_DESTROIED = 2; // 数据格式不正确,可能被其他程序修改
public static final int STATE_SYSTEM_ERROR = 3; // 系统错误导致备份或恢复失败
public static final int STATE_SUCCESS = 4; // 备份或恢复成功
// TextExport成员变量用于文本导出
private TextExport mTextExport;
// 私有构造函数,用于单例模式
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
// 检查外部存储是否可用的方法
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 导出数据到文本文件的方法
public int exportToText() {
return mTextExport.exportToText();
}
// 获取导出的文本文件名的方法
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
// 获取导出的文本文件目录的方法
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
// 定义一个内部类TextExport用于处理文本导出逻辑
private static class TextExport {
// 定义查询笔记所需的列
private static final String[] NOTE_PROJECTION = {
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
};
// 定义列索引
private static final int NOTE_COLUMN_ID = 0;
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
private static final int NOTE_COLUMN_SNIPPET = 2;
// 定义查询笔记数据所需的列
private static final String[] DATA_PROJECTION = {
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
// 定义列索引
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
// 注意DATA_COLUMN_CALL_DATE是错误的索引应该是DATA_COLUMN_DATA1或其他
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 = "";
}
// 根据索引获取文本格式的方法
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();
}
}
// ... 省略了exportNoteToText方法的实现该方法应该负责将指定笔记的内容导出到文本
}
}
//定义一个方法,用于将笔记内容导出为文本格式
private void exportNoteToText(String noteId, PrintStream ps) {
// 使用内容解析器查询特定笔记ID的笔记数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { noteId }, null);
// 检查游标是否非空
if (dataCursor != null) {
// 移动游标到第一行数据
if (dataCursor.moveToFirst()) {
// 遍历游标中的所有数据
do {
// 获取笔记的MIME类型
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
// 如果是电话笔记
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// 打印电话号码
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
// 如果电话号码非空,则打印电话号码
if (!TextUtils.isEmpty(phoneNumber)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), phoneNumber));
}
// 打印通话日期
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm), callDate)));
// 如果位置信息非空,则打印位置信息
if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), location));
}
} else if (DataConstants.NOTE.equals(mimeType)) { // 如果是普通笔记
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
// 如果笔记内容非空,则打印笔记内容
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), content));
}
}
} while (dataCursor.moveToNext());
}
// 关闭游标
dataCursor.close();
}
// 在笔记之间打印一个分隔符
try {
ps.write(new byte[] { Character.LINE_SEPARATOR, Character.LETTER_NUMBER });
} catch (IOException e) {
Log.e(TAG, e.toString());
}
}
//定义一个方法,用于将整个笔记系统导出为文本格式
public int exportToText() {
// 检查外部存储是否可用
if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
// 获取指向导出文件的打印流
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// 首先导出文件夹及其笔记
Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
// 检查文件夹游标是否非空
if (folderCursor != null) {
if (folderCursor.moveToFirst()) {
do {
// 打印文件夹名称
String folderName = "";
if (folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
}
if (!TextUtils.isEmpty(folderName)) {
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
// 导出文件夹下的笔记
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());
}
folderCursor.close();
}
// 导出根文件夹下的笔记
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
// 检查笔记游标是否非空
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
do {
// 打印笔记的修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// 查询并导出该笔记的内容
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
}
noteCursor.close();
}
ps.close();
return STATE_SUCCESS;
}
/**
*
*
* PrintStream
*/
//定义一个私有方法用于获取一个指向导出文本文件的PrintStream对象
private PrintStream getExportToTextPrintStream() {
// 调用generateFileMountedOnSDcard方法生成文件该方法需要上下文、文件路径资源ID和文件名格式资源ID
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
// 如果文件创建失败即file为null
if (file == null) {
// 打印错误日志
Log.e(TAG, "create file to exported failed");
// 返回null表示无法获取PrintStream
return null;
}
// 保存文件名
mFileName = file.getName();
// 保存文件目录路径
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
// 创建一个指向文件的FileOutputStream
FileOutputStream fos = new FileOutputStream(file);
// 使用FileOutputStream创建一个PrintStream对象
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
// 如果文件未找到打印堆栈跟踪并返回null
e.printStackTrace();
return null;
} catch (NullPointerException e) {
// 如果发生空指针异常打印堆栈跟踪并返回null
e.printStackTrace();
return null;
}
// 返回创建的PrintStream对象
return ps;
}
/**
* SD
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 创建一个StringBuilder对象用于拼接文件路径
StringBuilder sb = new StringBuilder();
// 追加SD卡根目录路径
sb.append(Environment.getExternalStorageDirectory());
// 追加从资源文件中获取的文件路径
sb.append(context.getString(filePathResId));
// 创建文件目录的File对象
File filedir = new File(sb.toString());
// 追加从资源文件中获取的文件名格式,并格式化当前日期作为文件名的一部分
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
// 创建文件的File对象
File file = new File(sb.toString());
try {
// 如果文件目录不存在,则创建它
if (!filedir.exists()) {
filedir.mkdir();
}
// 如果文件不存在,则创建它
if (!file.exists()) {
file.createNewFile();
}
// 返回创建的文件对象
return file;
} catch (SecurityException e) {
// 如果发生安全异常如没有SD卡写入权限打印堆栈跟踪
e.printStackTrace();
} catch (IOException e) {
// 如果发生IO异常打印堆栈跟踪
e.printStackTrace();
}
// 如果发生异常返回null
return null;
}

@ -0,0 +1,73 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
public class Contact {
private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact";
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
if (cursor != null && cursor.moveToFirst()) {
try {
String name = cursor.getString(0);
sContactCache.put(phoneNumber, name);
return name;
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close();
}
} else {
Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null;
}
}
}

@ -1,380 +0,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.tool;
// 导入所需的Android和内容提供者操作的类
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;
// 导入Notes应用中的相关类
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;
// 导入Java工具类
import java.util.ArrayList;
import java.util.HashSet;
// 声明DataUtils工具类
public class DataUtils {
// 定义日志标签
public static final String TAG = "DataUtils";
/**
*
* @param resolver
* @param ids ID
* @return
*/
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查ID集合是否为空
if (ids == null) {
Log.d(TAG, "the ids is null");
return true; // 如果为空则认为操作成功可能是一个设计选择但通常应返回false或抛出异常
}
// 检查ID集合是否不包含任何元素
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true; // 同上通常应返回false
}
// 创建操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<>();
// 遍历ID集合
for (long id : ids) {
// 检查是否为系统根文件夹ID不应删除
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue; // 跳过系统根文件夹
}
// 创建删除操作并添加到操作列表
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
operationList.add(builder.build());
}
try {
// 批量执行操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; // 如果操作失败则返回false
}
return true; // 操作成功
} catch (RemoteException e) {
// 捕获远程异常并记录
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
// 捕获操作应用异常并记录
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false; // 如果发生异常则返回false
}
/**
*
* @param resolver
* @param id ID
* @param srcFolderId ID
* @param desFolderId ID
*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
// 创建要更新的内容值
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId); // 设置目标文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); // 设置源文件夹ID可能用于记录或恢复
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记笔记为已修改
// 执行更新操作
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
/**
*
* @param resolver
* @param ids ID
* @param folderId ID
* @return
*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
// 检查ID集合是否为空
if (ids == null) {
Log.d(TAG, "the ids is null");
return true; // 同上通常应返回false
}
// 创建操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<>();
// 遍历ID集合
for (long id : ids) {
// 创建更新操作并添加到操作列表
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId); // 设置目标文件夹ID
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1); // 标记笔记为已修改
operationList.add(builder.build());
}
try {
// 批量执行操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查操作结果
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "move notes failed, ids:" + ids.toString());
return false; // 如果操作失败则返回false
}
return true; // 操作成功
} catch (RemoteException e) {
// 捕获远程异常并记录
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
// 捕获操作应用异常并记录
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false; // 如果发生异常则返回false
}
/**
*
* @param resolver
* @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; // 返回用户文件夹数量
}
}
//判断指定类型的笔记是否在笔记数据库中可见(不在回收站中)
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 使用ContentResolver查询指定ID的笔记过滤条件为类型匹配且父ID不等于回收站ID
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(); // 关闭Cursor
}
return exist; // 返回笔记是否存在的布尔值
}
//判断指定ID的笔记是否存在于笔记数据库中
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 使用ContentResolver查询指定ID的笔记没有过滤条件
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(); // 关闭Cursor
}
return exist; // 返回笔记是否存在的布尔值
}
//判断指定ID的数据项是否存在于数据数据库中
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 使用ContentResolver查询指定ID的数据项没有过滤条件
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(); // 关闭Cursor
}
return exist; // 返回数据项是否存在的布尔值
}
//判断指定名称的文件夹是否存在于笔记数据库中且不在回收站中
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 使用ContentResolver查询文件夹过滤条件为类型为文件夹且父ID不等于回收站ID且摘要名称匹配
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
// 如果查询结果不为空,表示文件夹存在
if(cursor.getCount() > 0) {
exist = true;
}
cursor.close(); // 关闭Cursor
}
return exist; // 返回文件夹是否存在的布尔值
}
//获取指定文件夹ID下的所有笔记小部件属性
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 使用ContentResolver查询指定文件夹ID下的笔记小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },
null);
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
if (c.moveToFirst()) { // 移动到Cursor的第一行
set = new HashSet<AppWidgetAttribute>(); // 初始化HashSet
do {
try {
AppWidgetAttribute widget = new AppWidgetAttribute(); // 创建小部件属性对象
widget.widgetId = c.getInt(0); // 获取小部件ID
widget.widgetType = c.getInt(1); // 获取小部件类型
set.add(widget); // 将小部件属性添加到HashSet中
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, e.toString()); // 捕获并打印索引越界异常
}
} while (c.moveToNext()); // 移动到Cursor的下一行
}
c.close(); // 关闭Cursor
}
return set; // 返回包含所有笔记小部件属性的HashSet
}
//根据笔记ID获取关联的电话号码
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
// 使用ContentResolver查询指定笔记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()) { // 如果Cursor不为空且移动到第一行
try {
return cursor.getString(0); // 返回电话号码
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString()); // 捕获并打印索引越界异常
} finally {
cursor.close(); // 关闭Cursor
}
}
return ""; // 如果没有找到电话号码,返回空字符串
}
//根据电话号码和通话日期获取笔记ID
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
// 使用ContentResolver查询指定电话号码和通话日期下的笔记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()) { // 如果Cursor不为空且移动到第一行
try {
return cursor.getLong(0); // 返回笔记ID
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString()); // 捕获并打印索引越界异常
}
}
cursor.close(); // 关闭Cursor
}
return 0; // 如果没有找到笔记ID返回0
}
//定义一个静态方法用于通过笔记ID从内容提供者中获取笔记摘要
public static String getSnippetById(ContentResolver resolver, long noteId) {
// 使用ContentResolver查询特定URI下的数据
// Notes.CONTENT_NOTE_URI 是笔记内容的URI
// 查询的列只有 NoteColumns.SNIPPET即笔记摘要
// 查询条件是 NoteColumns.ID 等于传入的 noteId
// 最后一个参数为null表示不需要对结果进行排序
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
// 检查返回的Cursor是否不为null
if (cursor != null) {
String snippet = ""; // 初始化摘要字符串为空
// 如果Cursor移动到第一行即存在查询结果
if (cursor.moveToFirst()) {
// 从Cursor中获取第一列的数据即SNIPPET列并赋值给snippet变量
snippet = cursor.getString(0);
}
// 关闭Cursor以释放资源
cursor.close();
// 返回查询到的摘要字符串
return snippet;
}
// 如果Cursor为null则抛出异常表示未找到指定ID的笔记
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
//定义一个静态方法,用于格式化笔记摘要字符串
public static String getFormattedSnippet(String snippet) {
// 如果传入的摘要字符串不为null
if (snippet != null) {
// 去除字符串两端的空白字符
snippet = snippet.trim();
// 查找字符串中第一次出现换行符的位置
int index = snippet.indexOf('\n');
// 如果找到了换行符
if (index != -1) {
// 将字符串截取到换行符之前的位置,即只保留第一行
snippet = snippet.substring(0, index);
}
}
// 返回格式化后的摘要字符串
return snippet;
}

@ -1,321 +0,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类继承自FrameLayout它是一个自定义的视图组件用于展示日期和时间选择的交互界面
// 支持24小时制和12小时制含AM/PM标识用户可以通过该组件方便地选择具体的日期和时间并能响应相应的变化事件。
public class DateTimePicker extends FrameLayout {
// 定义默认的启用状态,默认为启用,即组件默认是可以交互操作的
private static final boolean DEFAULT_ENABLE_STATE = true;
// 一天中半天12小时制包含的小时数
private static final int HOURS_IN_HALF_DAY = 12;
// 一天24小时制包含的小时数
private static final int HOURS_IN_ALL_DAY = 24;
// 一周包含的天数
private static final int DAYS_IN_ALL_WEEK = 7;
// 日期选择器NumberPicker的最小值通常对应一周的第一天索引从0开始
private static final int DATE_SPINNER_MIN_VAL = 0;
// 日期选择器NumberPicker的最大值对应一周的最后一天一周共7天索引从0到6
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
// 24小时制视图下小时选择器NumberPicker的最小值即0时
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
// 24小时制视图下小时选择器NumberPicker的最大值即23时
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
// 12小时制视图下小时选择器NumberPicker的最小值通常为1时习惯上12小时制从1开始计数
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
// 12小时制视图下小时选择器NumberPicker的最大值即12时
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
// 分钟选择器NumberPicker的最小值即0分
private static final int MINUT_SPINNER_MIN_VAL = 0;
// 分钟选择器NumberPicker的最大值即59分
private static final int MINUT_SPINNER_MAX_VAL = 59;
// AM/PM选择器NumberPicker的最小值对应AM通常用0表示
private static final int AMPM_SPINNER_MIN_VAL = 0;
// AM/PM选择器NumberPicker的最大值对应PM通常用1表示
private static final int AMPM_SPINNER_MAX_VAL = 1;
// 用于显示日期的NumberPicker组件用户可通过它选择具体的日期以周为范围展示
private final NumberPicker mDateSpinner;
// 用于显示小时的NumberPicker组件根据设置的视图模式24小时制或12小时制展示不同范围的小时值
private final NumberPicker mHourSpinner;
// 用于显示分钟的NumberPicker组件可选择0到59分钟
private final NumberPicker mMinuteSpinner;
// 用于显示AM/PM的NumberPicker组件仅在12小时制下可见且用于切换上午或下午标识
private final NumberPicker mAmPmSpinner;
// 用于存储和操作当前选择的日期和时间信息基于Calendar类实现方便进行日期和时间的计算与设置
private Calendar mDate;
// 用于存储一周内各天要展示给用户的显示值(例如格式化后的"MM.dd EEEE"格式的字符串)
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 用于标识当前时间是上午true还是下午false在12小时制下使用
private boolean mIsAm;
// 用于标识当前是否处于24小时制视图模式true表示24小时制false表示12小时制
private boolean mIs24HourView;
// 用于存储组件当前的启用状态,初始化为默认启用状态
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
// 用于标记是否处于初始化阶段,在初始化过程中某些逻辑可能会有不同处理,避免不必要的重复操作等
private boolean mInitialising;
// 定义一个接口类型的成员变量,用于设置当日期和时间发生变化时的回调监听器,外部类可以实现该接口来响应变化事件
private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 内部类实现的日期选择器NumberPicker的值变化监听器当用户在日期选择器上选择不同日期时触发
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 根据新选择的日期与旧日期的差值调整Calendar对象中的日期增加或减少相应天数
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
// 更新日期相关的显示控制,例如刷新显示的日期字符串等
updateDateControl();
// 触发日期和时间变化的回调方法,通知外部可能关注此变化的地方进行相应处理
onDateTimeChanged();
}
};
// 内部类实现的小时选择器NumberPicker的值变化监听器当用户在小时选择器上选择不同小时时触发
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
if (!mIs24HourView) {
// 在12小时制下如果从上午11时切换到下午12时中午意味着日期需要增加一天
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
}
// 反之从下午12时中午切换到上午11时日期需要减少一天
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;
}
// 如果是上午11时与下午12时中午之间切换还需要更新AM/PM标识并刷新相关显示控制
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm =!mIsAm;
updateAmPmControl();
}
} else {
// 在24小时制下如果从23时切换到0时日期需要增加一天
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
}
// 反之从0时切换到23时日期需要减少一天
else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
// 根据当前选择的小时考虑12小时制与24小时制转换情况设置Calendar对象中的小时信息
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));
}
}
};
// 内部类实现的分钟选择器NumberPicker的值变化监听器当用户在分钟选择器上选择不同分钟时触发
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;
// 如果从最大分钟值59分切换到最小分钟值0分意味着小时需要增加1小时时间进位
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
}
// 反之从最小分钟值切换到最大分钟值小时需要减少1小时时间退位
else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
if (offset!= 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
int newHour = getCurrentHourOfDay();
// 根据新的小时值判断是否切换AM/PM标识并更新相关显示控制仅在12小时制下相关
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
updateAmPmControl();
} else {
mIsAm = true;
updateAmPmControl();
}
}
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
}
};
// 内部类实现的AM/PM选择器NumberPicker的值变化监听器当用户在AM/PM选择器上切换时触发
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm =!mIsAm;
// 根据切换后的AM/PM标识相应地调整Calendar对象中的小时信息增加或减少12小时
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组件默认根据系统设置判断是否采用24小时制视图
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
// 构造函数使用指定的时间以毫秒为单位的时间戳初始化DateTimePicker组件默认根据系统设置判断是否采用24小时制视图
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
// 完整的构造函数用于初始化DateTimePicker组件传入上下文、指定的时间以及是否采用24小时制视图的标识
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
// 获取一个Calendar实例用于存储和操作日期时间信息初始化为当前时间如果没有传入指定时间的话
mDate = Calendar.getInstance();
mInitialising = true;
// 根据当前小时数判断是上午还是下午用于初始化AM/PM标识仅在12小时制下相关
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
// 加载布局文件到该组件中布局文件中应该包含了各个NumberPicker组件等用于展示和交互的视图元素
inflate(context, R.layout.datetime_picker, this);
// 获取布局文件中定义的日期选择器NumberPicker组件并进行相关初始化设置
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 获取小时选择器NumberPicker组件并设置其值变化监听器
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 获取分钟选择器NumberPicker组件设置其最小值、最大值以及长按更新间隔等属性并设置值变化监听器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 获取用于显示AM/PM的NumberPicker组件设置其最小值、最大值并设置显示的字符串值从DateFormatSymbols获取AM/PM标识字符串再设置其值变化监听器
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// 调用相关方法更新各个控件的初始显示状态,使其展示正确的初始日期、时间以及相关格式等信息
updateDateControl();
updateHourControl();
updateAmPmControl();
// 根据传入的参数设置是否采用24小时制视图模式并相应更新控件显示
set24HourView(is24HourView);
// 设置当前日期时间为传入的指定时间(如果有传入的话),或者保持默认的当前时间
setCurrentDate(date);
// 设置组件的初始启用状态
setEnabled(isEnabled());
// 初始化完成将初始化标记设置为false后续操作不再按照初始化阶段处理
mInitialising = false;
}
// 重写父类的setEnabled方法用于设置组件及其包含的各个子控件NumberPicker组件的启用状态同时更新内部的启用状态记录变量
@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;
}
// 重写父类的isEnabled方法返回组件当前的启用状态
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
* Calendar
*
* @return the current date in millis
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
* Calendar
*
* @param date The current date in millis
*/
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
setCurrentDate(cal.get();
}
}
}

@ -1,204 +0,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;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance();
private boolean mIs24HourView;
private OnDateTimeSetListener mOnDateTimeSetListener;
private DateTimePicker mDateTimePicker;
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
public DateTimePickerDialog(Context context, long date) {
super(context);
mDateTimePicker = new DateTimePicker(context);
setView(mDateTimePicker);
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
mDate.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);
set24HourView(DateFormat.is24HourFormat(this.getContext()));
updateTitle(mDate.getTimeInMillis());
}
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
private void updateTitle(long date) {
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}
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它是一个自定义的对话框组件用于展示日期和时间选择的交互界面
// 内部包含了DateTimePicker组件来实现具体的日期时间选择功能并提供了设置选择结果监听器等功能方便用户在对话框中选择日期和时间并获取选择结果。
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 用于存储当前选择的日期和时间信息基于Calendar类实现初始化为当前系统时间后续会根据用户在对话框中的选择进行更新
private Calendar mDate = Calendar.getInstance();
// 用于标识当前是否处于24小时制视图模式true表示24小时制false表示12小时制初始值会根据系统设置来确定
private boolean mIs24HourView;
// 定义一个接口类型的成员变量,用于设置当用户点击确定按钮完成日期和时间选择后触发的回调监听器,外部类可以实现该接口来获取选择结果
private OnDateTimeSetListener mOnDateTimeSetListener;
// 用于展示和操作日期时间选择的具体组件是DateTimePickerDialog的核心子组件用户通过它来实际选择日期和时间
private DateTimePicker mDateTimePicker;
// 定义一个接口,用于外部类实现,以便在用户完成日期和时间选择并点击确定按钮后接收通知并获取选择的日期时间信息(以毫秒为单位的时间戳形式)
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
// 构造函数用于创建DateTimePickerDialog实例传入上下文和初始的日期时间以毫秒为单位的时间戳
public DateTimePickerDialog(Context context, long date) {
super(context);
// 创建一个DateTimePicker实例用于在对话框中展示日期和时间选择的交互界面传入当前上下文它会根据默认设置显示初始的日期时间等信息
mDateTimePicker = new DateTimePicker(context);
// 将创建的DateTimePicker组件设置为对话框的内容视图这样对话框展示时就会显示日期时间选择的相关界面
setView(mDateTimePicker);
// 为DateTimePicker组件设置日期和时间变化的监听器当用户在DateTimePicker中改变了日期、时间等信息时触发相应逻辑
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
// 根据用户选择的新的年、月、日、时、分信息更新内部存储的Calendar对象mDate中的对应字段使mDate始终保持最新的选择状态
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
// 根据更新后的日期时间信息调用updateTitle方法更新对话框的标题使其显示当前选择的日期和时间
updateTitle(mDate.getTimeInMillis());
}
});
// 设置对话框初始显示的日期和时间将传入的时间戳解析并设置到内部的Calendar对象mDate
mDate.setTimeInMillis(date);
// 将秒数设置为0确保在处理日期时间时秒数处于初始默认状态可能是为了统一和简化选择的时间精度只精确到分钟级别
mDate.set(Calendar.SECOND, 0);
// 将当前的日期和时间信息设置到DateTimePicker组件中使其初始展示的内容与传入的初始日期时间一致
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置对话框的确定按钮按钮文本从资源文件中获取通过R.string.datetime_dialog_ok获取对应的字符串资源并将当前类实现了OnClickListener接口作为点击事件的监听器传入
setButton(context.getString(R.string.datetime_dialog_ok), this);
// 设置对话框的取消按钮按钮文本从资源文件中获取通过R.string.datetime_dialog_cancel获取对应的字符串资源传入null表示使用默认的取消按钮行为通常是关闭对话框
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置判断是否采用24小时制视图模式调用set24HourView方法进行相应设置并更新对话框标题等相关显示信息
set24HourView(DateFormat.is24HourFormat(this.getContext()));
updateTitle(mDate.getTimeInMillis());
}
// 用于设置对话框的日期时间选择界面是否采用24小时制视图模式更新内部的标识变量并可能影响DateTimePicker组件的显示例如AM/PM选择器的可见性等
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
// 用于设置当用户点击确定按钮完成日期和时间选择后触发的回调监听器外部类可以通过实现OnDateTimeSetListener接口并传入相应实例来处理选择结果
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
// 私有方法用于更新对话框的标题根据传入的日期时间以毫秒为单位的时间戳以及当前的24小时制视图模式标识等信息格式化并设置标题显示的内容
private void updateTitle(long date) {
// 定义用于格式化日期时间显示的标志位,包括显示年、日期、时间等信息
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
// 根据当前是否处于24小时制视图模式添加对应的格式化标志以便正确格式化时间显示是采用24小时制还是12小时制带AM/PM标识的格式
flag |= mIs24HourView? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
// 使用DateUtils工具类的formatDateTime方法根据传入的上下文、日期时间戳以及格式化标志格式化日期时间信息并设置为对话框的标题内容
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
// 实现OnClickListener接口的点击事件处理方法当用户点击对话框中的按钮这里主要关注确定按钮时触发
// 根据按钮点击情况以及是否设置了OnDateTimeSetListener监听器来决定是否触发监听器回调并传递选择的日期时间信息
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener!= null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -1,138 +0,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;
public class DropdownMenu {
private Button mButton;
private PopupMenu mPopupMenu;
private Menu mMenu;
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
mButton.setBackgroundResource(R.drawable.dropdown_icon);
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
});
}
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}
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类用于创建一个下拉菜单的功能组件它将一个Button按钮与一个PopupMenu弹出式菜单相关联
// 点击按钮时会弹出对应的菜单,并且可以设置菜单选项的点击监听器、查找特定菜单项以及设置按钮显示的标题等操作。
public class DropdownMenu {
// 用于存储关联的Button按钮对象该按钮作为触发弹出菜单显示的交互元素
private Button mButton;
// 用于存储创建的PopupMenu弹出式菜单对象承载具体的菜单内容和交互逻辑
private PopupMenu mPopupMenu;
// 用于存储PopupMenu对应的Menu对象方便后续对菜单本身进行一些操作比如查找菜单项等
private Menu mMenu;
// 构造函数用于初始化DropdownMenu实例传入上下文、要关联的Button按钮以及菜单资源的ID
public DropdownMenu(Context context, Button button, int menuId) {
// 将传入的Button按钮对象赋值给成员变量mButton以便后续操作
mButton = button;
// 为Button按钮设置背景资源这里使用了资源文件中定义的drawable资源dropdown_icon作为按钮的背景图片
// 通常用于展示一个下拉箭头之类的图标,提示用户该按钮可以点击弹出菜单
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建一个PopupMenu实例传入当前上下文和关联的Button按钮使得弹出菜单能够在合适的位置以按钮为锚点显示出来
mPopupMenu = new PopupMenu(context, mButton);
// 获取PopupMenu对应的Menu对象并赋值给成员变量mMenu方便后续操作菜单内容
mMenu = mPopupMenu.getMenu();
// 使用MenuInflater菜单填充器将指定资源ID对应的菜单布局资源填充到创建的Menu对象中
// 这样就构建好了具体的菜单结构,包含了各个菜单项等内容
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 为Button按钮设置点击事件监听器当按钮被点击时触发相应逻辑
mButton.setOnClickListener(new OnClickListener() {
// 实现OnClickListener接口的点击事件处理方法当按钮被点击时
public void onClick(View v) {
// 调用PopupMenu的show方法显示弹出式菜单使其展示在屏幕上供用户选择菜单项
mPopupMenu.show();
}
});
}
// 用于设置PopupMenu中菜单项的点击事件监听器外部可以传入实现了OnMenuItemClickListener接口的实例
// 来处理用户点击菜单项后的相应逻辑
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu!= null) {
// 如果PopupMenu对象不为空为其设置菜单项点击事件监听器将传入的监听器对象关联到PopupMenu上
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
// 用于在已构建的Menu对象中查找指定ID的菜单项返回对应的MenuItem对象方便外部对特定菜单项进行操作比如获取其属性、设置其状态等
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
// 用于设置Button按钮显示的标题文本内容改变按钮上展示给用户的文字提示信息
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}

@ -1,164 +0,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.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;
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
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName);
}
}
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
private class FolderListItem extends LinearLayout {
private TextView mName;
public FolderListItem(Context context) {
super(context);
inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name);
}
public void bind(String name) {
mName.setText(name);
}
}
}
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;
// FoldersListAdapter类继承自CursorAdapter它是一个用于将数据库游标Cursor中的数据适配到ListView等列表视图组件的适配器类
// 主要用于展示文件夹相关信息的列表,每个列表项对应一个文件夹的名称或特定标识,同时提供了获取文件夹名称等相关功能。
public class FoldersListAdapter extends CursorAdapter {
// 定义一个字符串数组,用于指定从数据库查询时需要获取的列名。
// 这里获取的是便签的唯一标识符ID和文件夹名称片段SNIPPET可能用于表示文件夹名称等相关信息两列。
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
};
// 定义常量表示查询结果中ID列对应的索引位置方便后续从Cursor中获取数据这里索引为0。
public static final int ID_COLUMN = 0;
// 定义常量表示查询结果中用于表示文件夹名称或名称片段列对应的索引位置方便后续从Cursor中获取数据这里索引为1。
public static final int NAME_COLUMN = 1;
// 构造函数用于初始化FoldersListAdapter实例接收上下文和数据库游标Cursor作为参数调用父类的构造函数完成基础的初始化工作。
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub此处可能是预留的代码编写位置目前为空可根据后续需求添加额外的初始化逻辑。
}
// 重写CursorAdapter的newView方法该方法用于创建一个新的视图View对象作为列表中的一个新的列表项视图。
// 在这里创建并返回一个自定义的FolderListItem视图对象用于展示文件夹相关信息。
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
}
// 重写CursorAdapter的bindView方法该方法用于将游标Cursor中当前位置的数据绑定到指定的视图View进行数据展示等操作。
@Override
public void bindView(View view, Context context, Cursor cursor) {
// 判断传入的视图是否是FolderListItem类型的实例确保进行正确的绑定操作。
if (view instanceof FolderListItem) {
// 获取文件夹名称相关信息根据游标中获取的ID列的值进行判断如果ID等于Notes.ID_ROOT_FOLDER可能是代表根文件夹的特定标识
// 则从资源文件中获取对应的特定字符串可能是表示“上级文件夹”之类的提示文本作为文件夹名称否则从游标中获取对应的名称列NAME_COLUMN的值作为文件夹名称。
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER)? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 调用FolderListItem的bind方法将获取到的文件夹名称设置到对应的视图中的TextView组件上进行显示。
((FolderListItem) view).bind(folderName);
}
}
// 定义一个方法,用于获取指定位置的文件夹名称,接收上下文和位置索引作为参数。
// 通过调用getItem方法获取对应位置的游标Cursor对象然后按照前面同样的逻辑判断并返回文件夹名称。
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实例传入上下文对象调用父类的构造函数完成基础初始化
// 并加载对应的布局文件folder_list_item.xml到该视图中然后获取布局中的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);
}
}
}

@ -1,134 +0,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.gtask.remote;
// 导入所需的Android类和接口
import android.app.Notification; // 通知类
import android.app.NotificationManager; // 通知管理类
import android.app.PendingIntent; // 意图的延迟执行类
import android.content.Context; // 上下文类
import android.content.Intent; // 意图类
import android.os.AsyncTask; // 异步任务类
// 导入项目内部的其他类
import net.micode.notes.R; // 资源类
import net.micode.notes.ui.NotesListActivity; // 笔记列表活动
import net.micode.notes.ui.NotesPreferenceActivity; // 笔记偏好设置活动
// 定义一个继承自AsyncTask的类用于执行后台任务
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 定义通知ID
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 定义一个接口,用于任务完成时的回调
public interface OnCompleteListener {
void onComplete();
}
// 声明成员变量
private Context mContext; // 上下文
private NotificationManager mNotifiManager; // 通知管理器
private GTaskManager mTaskManager; // 任务管理器
private OnCompleteListener mOnCompleteListener; // 任务完成监听器
// 构造函数,初始化成员变量
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);// 获取通知服务
mTaskManager = GTaskManager.getInstance();// 获取任务管理器实例
}
// 取消同步的方法
public void cancelSync() {
mTaskManager.cancelSync();
}
// 发布进度的方法注意这里重写了publishProgress方法
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
}
// 显示通知的方法
private void showNotification(int tickerId, String content) {
// 创建通知
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS; // 设置默认灯光
notification.flags = Notification.FLAG_AUTO_CANCEL;// 设置自动取消
PendingIntent pendingIntent;// 延迟意图
// 根据tickerId判断点击通知后的跳转页面
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);
}
// 设置通知的详细信息
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
// 发送通知
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
// 在后台线程中执行的任务
@Override
protected Integer doInBackground(Void... unused) {
// 发布登录进度的通知
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
// 执行同步任务,并返回结果
return mTaskManager.sync(mContext, this);
}
// 更新进度的方法
@Override
protected void onProgressUpdate(String... progress) {
// 显示同步中的通知
showNotification(R.string.ticker_syncing, progress[0]);
// 如果上下文是GTaskSyncService的实例则发送广播
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
// 任务执行完成后的方法
@Override
protected void onPostExecute(Integer result) {
// 根据结果显示不同的通知
if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
}
// 如果设置了任务完成监听器则在新线程中调用其onComplete方法
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}
}).start();
}
}
}

@ -1,665 +0,0 @@
// 声明包名这是Java项目中的一个约定用于组织类
package net.micode.notes.gtask.remote;
// 导入所需的Android和其他Java库
import android.accounts.Account; // 用于表示单个用户帐户的类
import android.accounts.AccountManager; // 用于管理帐户的类
import android.accounts.AccountManagerFuture; // 用于表示异步操作结果的类
import android.app.Activity; // 表示单个屏幕的应用组件
import android.os.Bundle; // 用于携带数据的一组键值对
import android.text.TextUtils; // 提供用于操作字符串的实用工具方法
import android.util.Log; // 用于打印日志的类
// 导入项目内部的其他类
import net.micode.notes.gtask.data.Node; // 节点数据模型
import net.micode.notes.gtask.data.Task; // 任务数据模型
import net.micode.notes.gtask.data.TaskList; // 任务列表数据模型
import net.micode.notes.gtask.exception.ActionFailureException; // 自定义异常,表示操作失败
import net.micode.notes.gtask.exception.NetworkFailureException; // 自定义异常,表示网络失败
import net.micode.notes.tool.GTaskStringUtils; // 工具类,提供字符串处理的实用方法
import net.micode.notes.ui.NotesPreferenceActivity; // 设置界面的Activity
// 导入Apache HttpClient库中的类用于发送HTTP请求
import org.apache.http.HttpEntity; // 表示HTTP消息的实体部分
import org.apache.http.HttpResponse; // 表示HTTP响应
import org.apache.http.client.ClientProtocolException; // 表示HTTP协议错误的异常
import org.apache.http.client.entity.UrlEncodedFormEntity; // 表示表单数据的实体
import org.apache.http.client.methods.HttpGet; // 表示HTTP GET请求的类
import org.apache.http.client.methods.HttpPost; // 表示HTTP POST请求的类
import org.apache.http.cookie.Cookie; // 表示HTTP cookie的类
import org.apache.http.impl.client.BasicCookieStore; // 用于存储HTTP cookies的类
import org.apache.http.impl.client.DefaultHttpClient; // 默认的HTTP客户端实现
import org.apache.http.message.BasicNameValuePair; // 表示表单中名称-值对的类
// 导入HTTP参数设置相关的类
import org.apache.http.params.BasicHttpParams; // 表示HTTP参数的类
import org.apache.http.params.HttpConnectionParams; // 用于设置HTTP连接参数的类
import org.apache.http.params.HttpParams; // HTTP参数的接口
import org.apache.http.params.HttpProtocolParams; // 用于设置HTTP协议参数的类
// 导入JSON处理相关的类
import org.json.JSONArray; // 表示JSON数组的类
import org.json.JSONException; // 表示JSON格式错误的异常
import org.json.JSONObject; // 表示JSON对象的类
// 导入Java标准库中的类
import java.io.BufferedReader; // 用于读取文本(字符)输入流并缓冲字符,以便提供字符、数组和行的高效读取
import java.io.IOException; // 表示I/O操作失败的异常
import java.io.InputStream; // 表示字节输入流的抽象类
import java.io.InputStreamReader; // 是桥接字节流和字符流的输入流
import java.util.LinkedList; // 实现了List接口的双向链表
import java.util.List; // List接口是Collection接口的子接口
import java.util.zip.GZIPInputStream; // 用于读取GZIP格式压缩文件的输入流
import java.util.zip.Inflater; // 用于解压缩数据流的类
import java.util.zip.InflaterInputStream; // 使用Inflater解压缩输入流的类
// 声明GTaskClient类这是一个用于与Google Tasks API交互的客户端类
public class GTaskClient {
// 定义日志标签,用于日志输出
private static final String TAG = GTaskClient.class.getSimpleName();
// 定义Google Tasks的URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// 定义用于获取Google Tasks数据的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// 定义用于向Google Tasks发送数据的URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 定义单例模式的实例变量
private static GTaskClient mInstance = null;
// 定义HTTP客户端变量
private DefaultHttpClient mHttpClient;
// 定义GET请求的URL
private String mGetUrl;
// 定义POST请求的URL
private String mPostUrl;
// 定义客户端版本变量
private long mClientVersion;
// 定义登录状态变量
private boolean mLoggedin;
// 定义最后登录时间变量
private long mLastLoginTime;
// 定义操作ID变量
private int mActionId;
// 定义帐户变量
private Account mAccount;
// 定义更新数据的JSON数组变量
private JSONArray mUpdateArray;
// 私有构造函数,用于实现单例模式
private GTaskClient() {
// 初始化变量
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
mClientVersion = -1;
mLoggedin = false;
mLastLoginTime = 0;
mActionId = 1;
mAccount = null;
mUpdateArray = null;
}
// 提供获取GTaskClient实例的静态方法实现单例模式
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
}
return mInstance;
}
public boolean login(Activity activity) {
// 假设cookie在5分钟后过期然后需要重新登录
final long interval = 1000 * 60 * 5;
// 如果上次登录时间加上间隔时间小于当前系统时间,则标记为未登录
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// 如果已经登录,但同步账户名称与设置中的账户名称不一致,则标记为未登录
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false;
}
// 如果已经登录则记录日志并返回true
if (mLoggedin) {
Log.d(TAG, "already logged in");
return true;
}
// 更新上次登录时间为当前系统时间
mLastLoginTime = System.currentTimeMillis();
// 尝试登录Google账户
String authToken = loginGoogleAccount(activity, false);
// 如果获取到的authToken为空则记录错误日志并返回false
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
// 如果账户不是gmail.com或googlemail.com则使用自定义域名登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index);
url.append(suffix + "/");
mGetUrl = url.toString() + "ig";
mPostUrl = url.toString() + "r/ig";
// 尝试使用自定义域名登录Google Tasks
if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true;
}
}
// 如果还未登录则尝试使用Google官方URL登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
// 如果登录失败则返回false
if (!tryToLoginGtask(activity, authToken)) {
return false;
}
}
// 标记为已登录并返回true
mLoggedin = true;
return true;
}
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
// 获取AccountManager实例
AccountManager accountManager = AccountManager.get(activity);
// 获取所有Google类型的账户
Account[] accounts = accountManager.getAccountsByType("com.google");
// 如果没有可用的Google账户则记录错误日志并返回null
if (accounts.length == 0) {
Log.e(TAG, "there is no available google account");
return null;
}
// 从设置中获取同步账户名称
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null;
// 遍历账户列表,找到与设置中的账户名称匹配的账户
for (Account a : accounts) {
if (a.name.equals(accountName)) {
account = a;
break;
}
}
// 如果找到了匹配的账户则更新mAccount
if (account != null) {
mAccount = account;
} else {
// 如果未找到匹配的账户则记录错误日志并返回null
Log.e(TAG, "unable to get an account with the same name in the settings");
return null;
}
// 获取账户的认证令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
// 获取认证令牌的结果
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
// 如果需要使令牌失效,则使当前令牌失效并重新登录
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false);
}
} catch (Exception e) {
// 如果获取令牌失败则记录错误日志并将authToken设为null
Log.e(TAG, "get auth token failed");
authToken = null;
}
// 返回认证令牌
return authToken;
}
// 尝试使用提供的authToken登录Google Tasks如果失败则尝试重新登录Google账户并再次尝试
private boolean tryToLoginGtask(Activity activity, String authToken) {
// 首先尝试使用提供的authToken登录Google Tasks
if (!loginGtask(authToken)) {
// 如果登录失败可能是因为authToken已过期现在我们尝试使登录Google账户来无效化旧令牌并获取新令牌
authToken = loginGoogleAccount(activity, true); // 尝试重新登录Google账户true可能表示强制刷新令牌
if (authToken == null) {
// 如果重新登录失败,记录错误日志
Log.e(TAG, "login google account failed");
return false; // 返回登录失败
}
// 使用新获取的authToken再次尝试登录Google Tasks
if (!loginGtask(authToken)) {
// 如果仍然登录失败,记录错误日志
Log.e(TAG, "login gtask failed");
return false; // 返回登录失败
}
}
// 如果任何一次登录成功,返回登录成功
return true;
}
// 使用提供的authToken登录Google Tasks
private boolean loginGtask(String authToken) {
// 设置HTTP连接和套接字超时时间
int timeoutConnection = 10000; // 连接超时时间10秒
int timeoutSocket = 15000; // 套接字超时时间15秒
HttpParams httpParameters = new BasicHttpParams(); // 创建HTTP参数对象
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // 设置连接超时
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // 设置套接字超时
mHttpClient = new DefaultHttpClient(httpParameters); // 创建HTTP客户端实例
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); // 创建Cookie存储实例
mHttpClient.setCookieStore(localBasicCookieStore); // 设置HTTP客户端的Cookie存储
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); // 禁用HTTP/1.1的Expect-Continue机制
// 尝试登录Google Tasks
try {
// 构建登录URL将authToken作为查询参数附加
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); // 创建HTTP GET请求
HttpResponse response = null; // 初始化HTTP响应对象
response = mHttpClient.execute(httpGet); // 执行HTTP GET请求
// 从响应中获取Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); // 获取所有Cookie
boolean hasAuthCookie = false; // 初始化认证Cookie存在标志
for (Cookie cookie : cookies) { // 遍历所有Cookie
if (cookie.getName().contains("GTL")) { // 如果Cookie名称包含"GTL"则认为是认证Cookie
hasAuthCookie = true; // 设置认证Cookie存在标志为true
}
}
if (!hasAuthCookie) { // 如果没有找到认证Cookie
Log.w(TAG, "it seems that there is no auth cookie"); // 记录警告日志
}
// 从响应中提取客户端版本信息
String resString = getResponseContent(response.getEntity()); // 获取响应内容
String jsBegin = "_setup("; // JavaScript响应开始的标记
String jsEnd = ")}</script>"; // JavaScript响应结束的标记
int begin = resString.indexOf(jsBegin); // 查找JavaScript开始的索引
int end = resString.lastIndexOf(jsEnd); // 查找JavaScript结束的索引
String jsString = null; // 初始化JavaScript字符串
if (begin != -1 && end != -1 && begin < end) { // 如果找到了JavaScript的开始和结束标记
jsString = resString.substring(begin + jsBegin.length(), end); // 提取JavaScript字符串
}
JSONObject js = new JSONObject(jsString); // 将JavaScript字符串转换为JSONObject
mClientVersion = js.getLong("v"); // 从JSONObject中获取客户端版本信息
} catch (JSONException e) { // 如果解析JSON时发生异常
Log.e(TAG, e.toString()); // 记录错误日志
e.printStackTrace(); // 打印异常堆栈信息
return false; // 返回登录失败
} catch (Exception e) { // 如果发生其他异常
// 简单地捕获所有异常
Log.e(TAG, "httpget gtask_url failed"); // 记录错误日志
return false; // 返回登录失败
}
// 如果没有发生异常,返回登录成功
return true;
}
// 生成一个唯一的动作ID每次调用时ID递增
private int getActionId() {
return mActionId++; // 返回当前ID并递增ID
}
// 创建一个用于发送HTTP POST请求的HttpPost对象
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); // 创建HttpPost对象指向mPostUrl
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); // 设置请求头,指定内容类型和字符集
httpPost.setHeader("AT", "1"); // 设置请求头,可能用于认证或其他目的
return httpPost; // 返回HttpPost对象
}
// 定义一个方法用于从HttpEntity中获取响应内容
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
// 如果实体有内容编码,则获取该编码
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding); // 打印编码信息
}
InputStream input = entity.getContent(); // 获取输入流
// 如果内容编码是gzip则使用GZIPInputStream进行解压
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
// 如果内容编码是deflate则使用InflaterInputStream进行解压
Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater);
}
try {
InputStreamReader isr = new InputStreamReader(input); // 创建输入流读取器
BufferedReader br = new BufferedReader(isr); // 创建缓冲读取器
StringBuilder sb = new StringBuilder(); // 用于构建响应内容的字符串
while (true) {
String buff = br.readLine(); // 逐行读取内容
if (buff == null) {
return sb.toString(); // 如果读到空行,说明读取完毕,返回构建好的字符串
}
sb = sb.append(buff); // 将读取到的行追加到字符串构建器中
}
} finally {
input.close(); // 无论是否发生异常,都关闭输入流
}
}
// 定义一个方法用于发送POST请求
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first"); // 如果未登录,则打印错误日志
throw new ActionFailureException("not logged in"); // 抛出未登录异常
}
HttpPost httpPost = createHttpPost(); // 创建HttpPost对象方法未在代码中给出
try {
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>(); // 创建键值对列表
list.add(new BasicNameValuePair("r", js.toString())); // 将JSON对象转换为字符串并添加到列表中
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); // 创建表单实体
httpPost.setEntity(entity); // 设置HttpPost的实体
// 执行POST请求
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity()); // 获取响应内容
return new JSONObject(jsString); // 将响应内容转换为JSONObject
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString()); // 打印异常信息
e.printStackTrace(); // 打印堆栈跟踪
throw new NetworkFailureException("postRequest failed"); // 抛出网络失败异常
} catch (IOException e) {
Log.e(TAG, e.toString()); // 打印异常信息
e.printStackTrace(); // 打印堆栈跟踪
throw new NetworkFailureException("postRequest failed"); // 抛出网络失败异常
} catch (JSONException e) {
Log.e(TAG, e.toString()); // 打印异常信息
e.printStackTrace(); // 打印堆栈跟踪
throw new ActionFailureException("unable to convert response content to jsonobject"); // 抛出操作失败异常
} catch (Exception e) {
Log.e(TAG, e.toString()); // 打印异常信息
e.printStackTrace(); // 打印堆栈跟踪
throw new ActionFailureException("error occurs when posting request"); // 抛出操作失败异常
}
}
// 定义一个方法,用于创建任务
public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); // 提交更新(方法未在代码中给出)
try {
JSONObject jsPost = new JSONObject(); // 创建JSON对象用于POST请求
JSONArray actionList = new JSONArray(); // 创建JSON数组用于存储动作列表
// 向动作列表中添加任务创建动作
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将动作列表添加到JSON对象中
// 添加客户端版本信息
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送POST请求
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 获取响应中的第一个结果
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务的GID
} catch (JSONException e) {
Log.e(TAG, e.toString()); // 打印异常信息
e.printStackTrace(); // 打印堆栈跟踪
throw new ActionFailureException("create task: handing jsonobject failed"); // 抛出操作失败异常
}
}
// 创建一个任务列表,并可能抛出网络失败异常
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject(); // 创建一个JSON对象用于发送请求
JSONArray actionList = new JSONArray(); // 创建一个JSON数组用于存放动作列表
// 将创建任务的动作添加到动作列表中
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将动作列表添加到请求JSON中
// 添加客户端版本信息到请求JSON中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送请求并接收响应
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); // 从响应中提取结果
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); // 设置任务列表的ID
} catch (JSONException e) {
Log.e(TAG, e.toString()); // 记录异常
e.printStackTrace(); // 打印异常堆栈
throw new ActionFailureException("create tasklist: handing jsonobject failed"); // 抛出动作失败异常
}
}
// 提交更新到服务器
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject(); // 创建一个JSON对象用于发送请求
// 将更新动作列表添加到请求JSON中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// 添加客户端版本信息到请求JSON中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); // 发送请求
mUpdateArray = null; // 清空更新数组
} catch (JSONException e) {
Log.e(TAG, e.toString()); // 记录异常
e.printStackTrace(); // 打印异常堆栈
throw new ActionFailureException("commit update: handing jsonobject failed"); // 抛出动作失败异常
}
}
}
// 添加一个更新节点到更新数组中,如果更新数组已满则先提交更新
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// 如果更新数组非空且长度超过10则先提交更新
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
if (mUpdateArray == null)
mUpdateArray = new JSONArray(); // 初始化更新数组
mUpdateArray.put(node.getUpdateAction(getActionId())); // 添加更新动作到更新数组
}
}
// 移动一个任务到另一个任务列表或在该任务列表内移动
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject(); // 创建一个JSON对象用于发送请求
JSONArray actionList = new JSONArray(); // 创建一个JSON数组用于存放动作列表
JSONObject action = new JSONObject(); // 创建一个JSON对象用于存放动作信息
// 设置动作类型为移动并添加其他必要信息到动作JSON中
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {
// 如果在同一个任务列表中移动且不是第一个任务则添加前一个兄弟任务的ID
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); // 添加来源任务列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); // 添加目标父任务列表ID
if (preParent != curParent) {
// 如果跨任务列表移动则添加目标任务列表ID
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action); // 将动作添加到动作列表中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将动作列表添加到请求JSON中
// 添加客户端版本信息到请求JSON中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); // 发送请求
} catch (JSONException e) {
Log.e(TAG, e.toString()); // 记录异常
e.printStackTrace(); // 打印异常堆栈
throw new ActionFailureException("move task: handing jsonobject failed"); // 抛出动作失败异常
}
}
// 删除一个节点
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); // 提交之前的更新
try {
JSONObject jsPost = new JSONObject(); // 创建一个JSON对象用于发送请求
JSONArray actionList = new JSONArray(); // 创建一个JSON数组用于存放动作列表
// 标记节点为已删除,并将删除动作添加到动作列表中
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); // 将动作列表添加到请求JSON中
// 添加客户端版本信息到请求JSON中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); // 发送请求
mUpdateArray = null; // 清空更新数组
} catch (JSONException e) {
Log.e(TAG, e.toString()); // 记录异常
e.printStackTrace(); // 打印异常堆栈
throw new ActionFailureException("delete node: handing jsonobject failed"); // 抛出动作失败异常
}
}
// 定义一个方法,用于获取任务列表,可能会抛出网络失败异常
public JSONArray getTaskLists() throws NetworkFailureException {
// 检查用户是否已登录
if (!mLoggedin) {
// 如果没有登录,记录错误日志
Log.e(TAG, "please login first");
// 抛出一个动作失败异常,提示未登录
throw new ActionFailureException("not logged in");
}
try {
// 创建一个HTTP GET请求
HttpGet httpGet = new HttpGet(mGetUrl);
// 初始化HTTP响应对象为null
HttpResponse response = null;
// 执行HTTP GET请求
response = mHttpClient.execute(httpGet);
// 从响应中获取任务列表的字符串内容
String resString = getResponseContent(response.getEntity());
// 定义JSON字符串的开始和结束标记
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
// 在响应字符串中查找开始和结束标记的位置
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
// 初始化JSON字符串为null
String jsString = null;
// 如果找到了开始和结束标记,并且开始位置在结束位置之前
if (begin != -1 && end != -1 && begin < end) {
// 提取JSON字符串
jsString = resString.substring(begin + jsBegin.length(), end);
}
// 将提取的JSON字符串转换为JSONObject
JSONObject js = new JSONObject(jsString);
// 从JSONObject中获取名为"t"的对象然后从中获取名为GTASK_JSON_LISTS的JSONArray
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) {
// 如果捕获到客户端协议异常,记录错误日志并抛出网络失败异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) {
// 如果捕获到IO异常记录错误日志并抛出网络失败异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
// 如果捕获到JSON解析异常记录错误日志并抛出动作失败异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed");
}
}
// 定义一个方法,用于获取特定任务列表的内容,可能会抛出网络失败异常
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
// 提交更新(可能用于同步或更新状态)
commitUpdate();
try {
// 创建用于POST请求的JSONObject
JSONObject jsPost = new JSONObject();
// 创建一个JSONArray用于存放动作列表
JSONArray actionList = new JSONArray();
// 创建一个JSONObject用于存放单个动作
JSONObject action = new JSONObject();
// 设置动作列表中的动作类型、动作ID、列表ID和是否获取已删除项
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
// 将动作添加到动作列表中
actionList.put(action);
// 将动作列表添加到POST请求的JSONObject中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送POST请求并获取响应
JSONObject jsResponse = postRequest(jsPost);
// 从响应中获取任务列表的JSONArray
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) {
// 如果捕获到JSON解析异常记录错误日志并抛出动作失败异常
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed");
}
}
// 定义一个方法,用于获取同步账户信息
public Account getSyncAccount() {
// 返回账户信息
return mAccount;
}
// 定义一个方法,用于重置更新数组
public void resetUpdateArray() {
// 将更新数组设置为null
mUpdateArray = null;
}
}

@ -1,876 +0,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.gtask.remote;
// 导入必要的Android和Java类
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.data.MetaData;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.SqlNote;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
// 声明GTaskManager类
public class GTaskManager {
// 定义日志标签
private static final String TAG = GTaskManager.class.getSimpleName();
// 定义同步状态常量
public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4;
// 声明单例实例和成员变量
private static GTaskManager mInstance = null;
private Activity mActivity;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mSyncing;
private boolean mCancelled;
private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid;
// 私有构造函数,用于创建单例
private GTaskManager() {
// 初始化成员变量
mSyncing = false;
mCancelled = false;
mGTaskListHashMap = new HashMap<String, TaskList>();
mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>();
mMetaList = null;
mLocalDeleteIdMap = new HashSet<Long>();
mGidToNid = new HashMap<String, Long>();
mNidToGid = new HashMap<Long, String>();
}
// 获取GTaskManager单例实例
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
}
return mInstance;
}
// 设置Activity上下文用于获取认证令牌
public synchronized void setActivityContext(Activity activity) {
mActivity = activity;
}
// 执行同步操作
public int sync(Context context, GTaskASyncTask asyncTask) {
// 如果已经在同步,则返回同步进行中状态
if (mSyncing) {
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
// 初始化成员变量
mContext = context;
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
// 清除所有哈希映射和集合
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
try {
// 获取GTaskClient实例
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// 登录Google Tasks
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// 从Google获取任务列表
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// 执行内容同步
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
Log.e(TAG, e.toString());
return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) {
Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR;
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {
// 清除所有哈希映射和集合,重置同步状态
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
mSyncing = false;
}
// 返回同步结果状态
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
// 定义一个初始化任务列表的方法,该方法可能会抛出网络失败异常
private void initGTaskList() throws NetworkFailureException {
// 如果任务被取消,则直接返回,不执行后续操作
if (mCancelled)
return;
// 获取GTaskClient的实例
GTaskClient client = GTaskClient.getInstance();
try {
// 从客户端获取任务列表的JSON数组
JSONArray jsTaskLists = client.getTaskLists();
// 首先初始化元数据列表
mMetaList = null;
// 遍历所有的任务列表
for (int i = 0; i < jsTaskLists.length(); i++) {
// 获取当前任务列表的JSON对象
JSONObject object = jsTaskLists.getJSONObject(i);
// 获取任务列表的ID
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
// 获取任务列表的名称
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 如果任务列表名称以特定的前缀开始,并且等于特定的元数据文件夹名称
if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
// 初始化元数据列表
mMetaList = new TaskList();
// 使用JSON对象设置元数据列表的内容
mMetaList.setContentByRemoteJSON(object);
// 加载元数据
JSONArray jsMetas = client.getTaskList(gid);
// 遍历所有的元数据
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
MetaData metaData = new MetaData();
// 使用JSON对象设置元数据的内容
metaData.setContentByRemoteJSON(object);
// 如果该元数据值得保存
if (metaData.isWorthSaving()) {
// 将元数据添加到元数据列表中
mMetaList.addChildTask(metaData);
// 如果元数据有GID则将其添加到哈希映射中
if (metaData.getGid() != null) {
mMetaHashMap.put(metaData.getRelatedGid(), metaData);
}
}
}
}
}
// 如果元数据列表不存在,则创建它
if (mMetaList == null) {
mMetaList = new TaskList();
// 设置元数据列表的名称
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META);
// 通过客户端创建元数据列表
GTaskClient.getInstance().createTaskList(mMetaList);
}
// 初始化任务列表
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 如果任务列表名称以特定的前缀开始,并且不等于元数据文件夹名称
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList();
// 使用JSON对象设置任务列表的内容
tasklist.setContentByRemoteJSON(object);
// 将任务列表添加到哈希映射中
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist);
// 加载任务
JSONArray jsTasks = client.getTaskList(gid);
// 遍历所有的任务
for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task();
// 使用JSON对象设置任务的内容
task.setContentByRemoteJSON(object);
// 如果该任务值得保存
if (task.isWorthSaving()) {
// 设置任务的元数据
task.setMetaInfo(mMetaHashMap.get(gid));
// 将任务添加到任务列表中
tasklist.addChildTask(task);
// 更新任务在哈希映射中的引用
mGTaskHashMap.put(gid, task);
}
}
}
}
} catch (JSONException e) {
// 捕获JSON异常记录错误日志
Log.e(TAG, e.toString());
e.printStackTrace();
// 抛出自定义的操作失败异常
throw new ActionFailureException("initGTaskList: handing JSONObject failed");
}
}
// 定义一个名为syncContent的私有方法该方法可能会抛出NetworkFailureException异常
private void syncContent() throws NetworkFailureException {
// 定义一个变量syncType用于存储同步类型
int syncType;
// 定义一个Cursor对象c初始化为null用于查询数据库
Cursor c = null;
// 定义一个字符串变量gid用于存储Google任务的ID
String gid;
// 定义一个Node对象node用于表示Google任务节点
Node node;
// 清空本地删除ID的映射表
mLocalDeleteIdMap.clear();
// 如果同步操作被取消,则直接返回
if (mCancelled) {
return;
}
// 处理本地已删除的笔记
try {
// 查询本地数据库中非系统类型且不在回收站的笔记
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, null);
// 如果查询结果不为空
if (c != null) {
while (c.moveToNext()) {
// 获取Google任务的ID
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
// 从HashMap中获取对应的Node对象
node = mGTaskHashMap.get(gid);
if (node != null) {
// 从HashMap中移除该Node对象
mGTaskHashMap.remove(gid);
// 执行远程删除操作
doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
}
// 将本地笔记ID添加到删除ID映射表中
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
}
} else {
// 如果查询失败,记录警告日志
Log.w(TAG, "failed to query trash folder");
}
} finally {
// 关闭Cursor对象释放资源
if (c != null) {
c.close();
c = null;
}
}
// 首先同步文件夹
syncFolder();
// 处理数据库中存在的笔记
try {
// 查询本地数据库中类型为笔记且不在回收站的笔记
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
// 如果查询结果不为空
if (c != null) {
while (c.moveToNext()) {
// 获取Google任务的ID
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
// 从HashMap中获取对应的Node对象
node = mGTaskHashMap.get(gid);
if (node != null) {
// 从HashMap中移除该Node对象
mGTaskHashMap.remove(gid);
// 更新gid到nid的映射以及nid到gid的映射
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
// 获取同步类型
syncType = node.getSyncAction(c);
} else {
// 如果gid为空表示是本地新增的笔记
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// 如果gid不为空但不在HashMap中表示远程已删除
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
// 执行同步操作
doContentSync(syncType, node, c);
}
} else {
// 如果查询失败,记录警告日志
Log.w(TAG, "failed to query existing note in database");
}
} finally {
// 关闭Cursor对象释放资源
if (c != null) {
c.close();
c = null;
}
}
// 遍历HashMap中剩余的项执行本地添加操作
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// 检查mCancelled标志确保同步操作未被取消
// 清空本地删除表
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
// 如果批量删除失败抛出ActionFailureException异常
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// 刷新本地同步ID
if (!mCancelled) {
// 提交更新并刷新本地同步ID
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
}
}
// 定义一个私有的同步文件夹方法,该方法可能会抛出网络失败异常
private void syncFolder() throws NetworkFailureException {
Cursor c = null; // 初始化一个游标对象,用于数据库查询
String gid; // 用于存储从数据库查询得到的Google任务ID
Node node; // 用于存储节点对象,代表一个文件夹或任务
int syncType; // 用于存储同步类型
// 如果同步操作被取消,则直接返回
if (mCancelled) {
return;
}
// 同步根文件夹的部分
try {
// 从内容提供者查询根文件夹的信息
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
if (c != null) {
c.moveToNext(); // 移动到查询结果的第一行
gid = c.getString(SqlNote.GTASK_ID_COLUMN); // 获取Google任务ID
node = mGTaskHashMap.get(gid); // 从哈希表中获取节点对象
if (node != null) {
// 如果节点存在,则更新本地和远程的映射关系,并根据需要更新远程名称
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
// 如果节点不存在,则添加远程节点
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
} else {
// 如果查询失败,则记录警告日志
Log.w(TAG, "failed to query root folder");
}
} finally {
// 确保游标被关闭
if (c != null) {
c.close();
c = null;
}
}
// 同步通话记录文件夹的部分(类似于根文件夹的处理逻辑)
// ...(代码省略,逻辑同上)
// 同步本地已存在的文件夹的部分
try {
// 从内容提供者查询所有非垃圾文件夹的信息
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) { // 遍历查询结果
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
// 如果节点存在,则更新映射关系,并根据节点的同步动作进行同步
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c);
} else {
// 如果节点不存在则根据Google任务ID是否为空决定是本地添加还是远程删除
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
doContentSync(syncType, node, c); // 根据同步类型进行同步
}
} else {
// 如果查询失败,则记录警告日志
Log.w(TAG, "failed to query existing folder");
}
} finally {
// 确保游标被关闭
if (c != null) {
c.close();
c = null;
}
}
// 同步远程添加的文件夹的部分
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
gid = entry.getKey();
node = entry.getValue();
if (mGTaskHashMap.containsKey(gid)) {
// 如果本地已经存在该Google任务ID的节点则更新本地映射并添加本地节点
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
}
// 如果同步操作没有被取消,则提交更新
if (!mCancelled)
GTaskClient.getInstance().commitUpdate();
}
// 定义一个方法用于内容同步,接收同步类型、节点和游标作为参数,可能抛出网络失败异常
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
// 如果同步被取消,则直接返回
if (mCancelled) {
return;
}
MetaData meta; // 定义一个MetaData对象用于后续操作
// 根据不同的同步类型执行不同的操作
switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL: // 本地添加节点
addLocalNode(node);
break;
case Node.SYNC_ACTION_ADD_REMOTE: // 远程添加节点
addRemoteNode(node, c);
break;
case Node.SYNC_ACTION_DEL_LOCAL: // 本地删除节点
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); // 从哈希映射中获取MetaData对象
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta); // 删除节点
}
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); // 将本地删除节点的ID添加到映射中
break;
case Node.SYNC_ACTION_DEL_REMOTE: // 远程删除节点
meta = mMetaHashMap.get(node.getGid()); // 从哈希映射中获取MetaData对象
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta); // 删除节点
}
GTaskClient.getInstance().deleteNode(node); // 删除远程节点
break;
case Node.SYNC_ACTION_UPDATE_LOCAL: // 更新本地节点
updateLocalNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_REMOTE: // 更新远程节点
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT: // 更新冲突,当前简单使用本地更新
// merging both modifications maybe a good idea
// right now just use local update simply
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE: // 无操作
break;
case Node.SYNC_ACTION_ERROR: // 错误类型,默认抛出异常
default:
throw new ActionFailureException("unkown sync action type");
}
}
// 定义一个方法用于添加本地节点
private void addLocalNode(Node node) throws NetworkFailureException {
// 如果同步被取消,则直接返回
if (mCancelled) {
return;
}
SqlNote sqlNote; // 定义一个SqlNote对象用于后续操作
// 判断节点类型,如果是任务列表,则进行特殊处理
if (node instanceof TaskList) {
// 根据任务列表的名称判断是否为特殊列表(如默认列表、通话记录列表)
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
} else if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else {
sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent()); // 设置节点内容
sqlNote.setParentId(Notes.ID_ROOT_FOLDER); // 设置父节点ID为根文件夹ID
}
} else { // 如果是任务节点,则进行通用处理
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent(); // 获取节点内容的JSON对象
try {
// 检查JSON对象中是否包含特定字段并根据需要进行处理
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// 如果数据库中已存在该ID则移除ID字段
note.remove(NoteColumns.ID);
}
}
}
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// 如果数据库中已存在该数据ID则移除数据ID字段
data.remove(DataColumns.ID);
}
}
}
}
} catch (JSONException e) {
Log.w(TAG, e.toString());
e.printStackTrace();
}
sqlNote.setContent(js); // 设置节点内容的JSON对象
// 获取父节点的ID并设置给当前节点
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node");
}
sqlNote.setParentId(parentId.longValue());
}
// 创建本地节点
sqlNote.setGtaskId(node.getGid()); // 设置节点的全局ID
sqlNote.commit(false); // 提交节点到数据库
// 更新全局ID到本地ID的映射
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// 更新MetaData
updateRemoteMeta(node.getGid(), sqlNote);
}
// 定义一个私有方法,用于更新本地节点,参数包括节点和数据库游标
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
// 如果操作被取消,则直接返回
if (mCancelled) {
return;
}
SqlNote sqlNote;
// 创建一个SqlNote实例用于更新笔记
sqlNote = new SqlNote(mContext, c);
// 设置SqlNote的内容为节点的本地JSON内容
sqlNote.setContent(node.getLocalJSONFromContent());
// 根据节点类型获取父节点的ID如果是任务则通过GID查找否则使用根文件夹ID
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
// 如果找不到父节点的ID则记录错误并抛出异常
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
}
// 设置SqlNote的父节点ID
sqlNote.setParentId(parentId.longValue());
// 提交更改到数据库true表示立即写入
sqlNote.commit(true);
// 更新远程元数据
updateRemoteMeta(node.getGid(), sqlNote);
}
// 定义一个私有方法,用于添加远程节点,参数包括节点和数据库游标
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
// 如果操作被取消,则直接返回
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
Node n;
// 如果是笔记类型,则进行远程更新
if (sqlNote.isNoteType()) {
Task task = new Task();
// 设置任务的内容为SqlNote的内容
task.setContentByLocalJSON(sqlNote.getContent());
// 查找父任务的GID
String parentGid = mNidToGid.get(sqlNote.getParentId());
// 如果找不到父任务的GID则记录错误并抛出异常
if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task");
}
// 将任务添加到父任务列表中
mGTaskListHashMap.get(parentGid).addChildTask(task);
// 创建远程任务
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// 更新远程元数据
updateRemoteMeta(task.getGid(), sqlNote);
} else {
TaskList tasklist = null;
// 根据SqlNote的ID判断文件夹类型并构建文件夹名称
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
else
folderName += sqlNote.getSnippet();
// 遍历所有任务列表,查找是否存在同名文件夹
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
String gid = entry.getKey();
TaskList list = entry.getValue();
if (list.getName().equals(folderName)) {
tasklist = list;
// 如果存在同名文件夹且已经在GTaskHashMap中则移除
if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid);
}
break;
}
}
// 如果没有找到同名文件夹,则创建新文件夹
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().createTaskList(tasklist);
mGTaskListHashMap.put(tasklist.getGid(), tasklist);
}
n = (Node) tasklist;
}
// 更新本地SqlNote的GtaskID
sqlNote.setGtaskId(n.getGid());
// 提交更改到数据库false表示延迟写入
sqlNote.commit(false);
// 重置本地修改标记
sqlNote.resetLocalModified();
// 再次提交更改到数据库true表示立即写入
sqlNote.commit(true);
// 更新GID和ID的映射关系
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
// 定义一个方法,用于更新远程节点。该方法接收一个节点和一个游标作为参数,并可能抛出网络失败异常。
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
// 如果同步被取消,则直接返回。
if (mCancelled) {
return;
}
// 使用上下文和游标创建一个SqlNote对象。
SqlNote sqlNote = new SqlNote(mContext, c);
// 更新远程内容将节点的内容设置为从SqlNote获取的本地JSON内容。
node.setContentByLocalJSON(sqlNote.getContent());
// 调用GTaskClient的实例来添加或更新这个节点。
GTaskClient.getInstance().addUpdateNode(node);
// 更新节点的元数据。
updateRemoteMeta(node.getGid(), sqlNote);
// 如果需要,移动任务。
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
// 获取当前父任务的GID。
String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) {
// 如果找不到父任务列表,记录错误并抛出异常。
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot update remote task");
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
// 如果任务的前一个父列表与当前父列表不同,则移动任务。
if (preParentList != curParentList) {
preParentList.removeChildTask(task);
curParentList.addChildTask(task);
GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
}
}
// 清除本地的修改标志,并提交更改。
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
// 定义一个方法,用于更新远程元数据。
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) {
// 如果元数据已存在,则更新它。
metaData.setMeta(gid, sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(metaData);
} else {
// 如果元数据不存在,则创建新的元数据并添加到列表中。
metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData);
mMetaHashMap.put(gid, metaData);
GTaskClient.getInstance().createTask(metaData);
}
}
}
// 定义一个方法用于刷新本地的同步ID。
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
}
// 清除现有的哈希映射,并初始化任务列表。
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
initGTaskList();
Cursor c = null;
try {
// 查询本地笔记,排除系统类型和垃圾文件夹。
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid);
if (node != null) {
// 如果找到了对应的节点则更新其同步ID。
mGTaskHashMap.remove(gid);
ContentValues values = new ContentValues();
values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
// 如果找不到对应的节点,则记录错误。
Log.e(TAG, "something is missed");
throw new ActionFailureException(
"some local items don't have gid after sync");
}
}
} else {
// 如果查询失败,则记录警告。
Log.w(TAG, "failed to query local note to refresh sync id");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
}
// 定义一个方法,用于获取同步账户的名称。
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
// 定义一个方法,用于取消同步。
public void cancelSync() {
mCancelled = true;
}

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

@ -1,145 +0,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.gtask.remote;
// 导入必要的Android类
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
// 定义一个继承自Service的类用于同步任务
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) { // 如果当前没有正在执行的同步任务
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() {
mSyncTask = null; // 任务完成后将任务对象置为null
sendBroadcast(""); // 发送广播,通知同步完成
stopSelf(); // 停止服务
}
});
sendBroadcast(""); // 发送广播,通知开始同步(这里可能需要发送具体信息)
mSyncTask.execute(); // 执行异步任务
}
}
// 取消同步的私有方法
private void cancelSync() {
if (mSyncTask != null) { // 如果当前有正在执行的同步任务
mSyncTask.cancelSync(); // 取消任务
}
}
// 当服务被创建时调用
@Override
public void onCreate() {
mSyncTask = null; // 初始化同步任务对象为null
}
// 当服务被命令启动时调用
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); // 获取Intent中的附加数据
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; // 如果服务被杀死系统会重新创建服务并调用onStartCommand方法
}
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
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null); // 是否正在同步
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); // 同步进度信息
sendBroadcast(intent); // 发送广播
}
// 提供一个静态方法用于从Activity启动同步服务
public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity); // 设置GTaskManager的Activity上下文
Intent intent = new Intent(activity, GTaskSyncService.class); // 创建Intent
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC); // 添加动作类型
activity.startService(intent); // 启动服务
}
// 提供一个静态方法用于从Context取消同步服务
public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); // 创建Intent
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); // 添加动作类型
context.startService(intent); // 启动服务以取消同步
}
// 提供一个静态方法,用于检查是否正在同步
public static boolean isSyncing() {
return mSyncTask != null; // 返回mSyncTask是否为null
}
// 提供一个静态方法,用于获取同步进度信息
public static String getProgressString() {
return mSyncProgress; // 返回mSyncProgress的值
}
}

@ -1,313 +0,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.model;
// 导入所需的Android和内容提供者操作的类
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
// 导入项目内部的数据模型类
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
// 导入Java的ArrayList类
import java.util.ArrayList;
// 声明Note类
public class Note {
// 用于存储笔记差异值的ContentValues对象
private ContentValues mNoteDiffValues;
// 用于存储笔记数据的NoteData对象
private NoteData mNoteData;
// 用于日志记录的标签
private static final String TAG = "Note";
/**
* ID
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// 创建一个新的ContentValues对象用于存储要插入数据库的数据
ContentValues values = new ContentValues();
// 获取当前时间作为创建和修改时间
long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE); // 设置笔记类型为普通笔记
values.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为本地已修改
values.put(NoteColumns.PARENT_ID, folderId); // 设置父文件夹ID
// 向内容提供者插入数据并获取返回的Uri
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
long noteId = 0;
try {
// 从返回的Uri中提取笔记ID
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
// 如果提取ID时发生异常则记录错误日志并将noteId设置为0
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
// 如果noteId为-1则抛出异常
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
}
return noteId; // 返回新创建的笔记ID
}
// Note类的构造函数
public Note() {
mNoteDiffValues = new ContentValues(); // 初始化差异值对象
mNoteData = new NoteData(); // 初始化笔记数据对象
}
// 设置笔记的某个键值对,并标记为已修改
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value); // 存储键值对
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); // 标记为已修改
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); // 更新修改时间
}
// 设置文本数据的某个键值对
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value); // 调用NoteData对象的方法设置文本数据
}
// 设置文本数据的ID
public void setTextDataId(long id) {
mNoteData.setTextDataId(id); // 调用NoteData对象的方法设置文本数据ID
}
// 获取文本数据的ID
public long getTextDataId() {
return mNoteData.mTextDataId; // 返回NoteData对象中的文本数据ID
}
// 设置通话数据的ID
public void setCallDataId(long id) {
mNoteData.setCallDataId(id); // 调用NoteData对象的方法设置通话数据ID
}
// 设置通话数据的某个键值对
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value); // 调用NoteData对象的方法设置通话数据
}
// 判断笔记是否已本地修改
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); // 判断差异值对象或NoteData对象是否标记为已修改
}
// 同步笔记到数据库
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId); // 如果笔记ID非法则抛出异常
}
if (!isLocalModified()) {
return true; // 如果笔记未修改则直接返回true
}
/**
* LOCAL_MODIFIEDMODIFIED_DATE
* 使
*/
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
Log.e(TAG, "Update note error, should not happen"); // 如果更新失败,则记录错误日志
// 不返回,继续执行后续代码
}
mNoteDiffValues.clear(); // 清空差异值对象
// 如果NoteData对象标记为已修改并且推送到内容提供者失败则返回false
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
}
return true; // 同步成功返回true
}
// 定义一个私有的内部类NoteData用于管理笔记数据的存储和操作
private class NoteData {
// 文本数据的ID
private long mTextDataId;
// 用于存储文本数据的ContentValues对象
private ContentValues mTextDataValues;
// 通话数据的ID
private long mCallDataId;
// 用于存储通话数据的ContentValues对象
private ContentValues mCallDataValues;
// 用于日志输出的标签
private static final String TAG = "NoteData";
// NoteData类的构造函数初始化数据
public NoteData() {
// 初始化文本数据和通话数据的ContentValues对象
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
// 初始化数据ID为0表示未设置
mTextDataId = 0;
mCallDataId = 0;
}
// 判断是否有本地数据被修改
boolean isLocalModified() {
// 如果文本数据或通话数据的ContentValues对象不为空则表示有数据被修改
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
// 设置文本数据的ID
void setTextDataId(long id) {
// 如果传入的ID小于等于0则抛出异常
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
}
// 设置文本数据的ID
mTextDataId = id;
}
// 设置通话数据的ID
void setCallDataId(long id) {
// 如果传入的ID小于等于0则抛出异常
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
}
// 设置通话数据的ID
mCallDataId = id;
}
// 设置通话数据,并标记为已修改
void setCallData(String key, String value) {
// 将数据存入mCallDataValues
mCallDataValues.put(key, value);
// 标记为已修改注意这里mNoteDiffValues没有在类中定义可能是个错误或者遗漏
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新修改日期
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
// 设置文本数据,并标记为已修改
void setTextData(String key, String value) {
// 将数据存入mTextDataValues
mTextDataValues.put(key, value);
// 标记为已修改注意同样mNoteDiffValues没有在类中定义
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新修改日期
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
// 将数据推送到ContentResolver中
Uri pushIntoContentResolver(Context context, long noteId) {
// 检查noteId的有效性
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
// 创建一个操作列表,用于批量操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
// 处理文本数据
if(mTextDataValues.size() > 0) {
// 添加noteId到文本数据中
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
// 如果是新数据,则插入到数据库中
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
// 设置新插入的数据的ID
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
// 插入失败,记录错误并清理数据
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}
} else {
// 如果是已存在的数据,则更新
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
// 清理文本数据,为下一次操作做准备
mTextDataValues.clear();
}
// 处理通话数据,逻辑与文本数据处理相同
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}
mCallDataValues.clear();
}
// 如果存在操作,则执行批量操作
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
// 返回操作结果的URI如果结果为空则返回null
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
// 记录远程异常并返回null
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
// 记录操作应用异常并返回null
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}
}
// 如果没有操作则返回null
return null;
}
}

@ -1,335 +0,0 @@
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实现了OnClickListener、NoteSettingChangedListener、OnTextViewChangeListener接口用于编辑笔记相关的操作和界面交互
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
// 内部类,用于方便地持有笔记头部视图相关的控件引用
private class HeadViewHolder {
public TextView tvModified; // 用于显示笔记修改时间的TextView
public ImageView ivAlertIcon; // 用于显示提醒图标比如闹钟图标等的ImageView
public TextView tvAlertDate; // 用于显示提醒时间相关文本的TextView
public ImageView ibSetBgColor; // 用于设置背景颜色的按钮ImageView
}
// 以下是一些静态的映射关系用于将界面上的按钮ID与对应的颜色资源ID等进行关联
// 将背景颜色选择按钮的ID映射到对应的颜色资源ID如黄色、红色等颜色的资源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);
}
// 将颜色资源ID映射到对应的已选择该颜色时显示的标识视图的ID比如选中黄色背景时对应的选中标识视图的ID
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);
}
// 将字体大小选择按钮的ID映射到对应的字体大小资源ID如大字体、小字体等对应的资源ID
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);
}
// 将字体大小资源ID映射到对应的已选择该字体大小时显示的标识视图的ID
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"; // 用于日志输出的标记字符串
private HeadViewHolder mNoteHeaderHolder; // 笔记头部视图相关控件的持有者实例
private View mHeadViewPanel; // 笔记头部整体的视图
private View mNoteBgColorSelector; // 背景颜色选择器的视图(通常是包含多个颜色选项的布局)
private View mFontSizeSelector; // 字体大小选择器的视图(包含不同字体大小选项的布局)
private EditText mNoteEditor; // 用于编辑笔记内容的EditText控件
private View mNoteEditorPanel; // 包含笔记编辑区域的整体视图(可能用于设置背景等相关属性)
private WorkingNote mWorkingNote; // 代表正在编辑的笔记对象,包含笔记的各种属性和操作方法
private SharedPreferences mSharedPrefs; // 用于获取和保存应用的共享偏好设置
private int mFontSizeId; // 当前选中的字体大小对应的资源ID
private static final String PREFERENCE_FONT_SIZE = "pref_font_size"; // 用于存储字体大小偏好设置的键名
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10; // 发送到桌面的快捷方式图标标题的最大长度
public static final String TAG_CHECKED = String.valueOf('\u221A'); // 用于表示列表项被选中的前缀标记字符串(自定义的特殊字符表示)
public static final String TAG_UNCHECKED = String.valueOf('\u25A1'); // 用于表示列表项未被选中的前缀标记字符串(自定义的特殊字符表示)
private LinearLayout mEditTextList; // 用于显示笔记内容为列表模式时的列表布局LinearLayout
private String mUserQuery; // 用户输入的查询字符串(可能用于搜索笔记内容等场景)
private Pattern mPattern; // 用于对用户查询内容进行正则匹配的模式对象
// Activity创建时调用的方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置该Activity对应的布局文件
this.setContentView(R.layout.note_edit);
// 如果savedInstanceState为null即Activity首次创建不是从内存恢复的情况并且初始化Activity状态失败则直接结束该Activity
if (savedInstanceState == null &&!initActivityState(getIntent())) {
finish();
return;
}
// 初始化相关资源,如查找视图等操作
initResources();
}
/**
* ActivityActivity
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// 如果保存的状态不为null且包含特定的额外数据通过Intent.EXTRA_UID标识则尝试重新初始化Activity状态
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");
}
}
// 根据传入的Intent初始化Activity的状态比如确定是查看已有笔记还是新建笔记等情况并加载相应的笔记数据
private boolean initActivityState(Intent intent) {
/**
* Intent.ACTION_VIEWIDNotesListActivity
*/
mWorkingNote = null;
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
mUserQuery = "";
/**
* IntentActivityID
*/
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
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 {
// 从数据库加载指定ID的笔记对象如果加载失败则记录错误日志并结束该Activity
mWorkingNote = WorkingNote.load(this, noteId);
if (mWorkingNote == null) {
Log.e(TAG, "load note failed with note id" + noteId);
finish();
return false;
}
}
// 设置软键盘的显示模式,初始为隐藏且根据布局调整大小
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
} else if (TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {
// 新建笔记的情况
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE,
Notes.TYPE_WIDGET_INVALIDE);
int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID,
ResourceParser.getDefaultBgId(this));
// 解析可能的通话记录笔记相关信息(如果有)
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);
if (callDate!= 0 && phoneNumber!= null) {
if (TextUtils.isEmpty(phoneNumber)) {
Log.w(TAG, "The call record number is null");
}
long noteId = 0;
if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(),
phoneNumber, callDate)) > 0) {
mWorkingNote = WorkingNote.load(this, noteId);
if (mWorkingNote == null) {
Log.e(TAG, "load call note failed with note id" + noteId);
finish();
return false;
}
} else {
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId,
widgetType, bgResId);
mWorkingNote.convertToCallNote(phoneNumber, callDate);
}
} else {
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType,
bgResId);
}
// 设置软键盘的显示模式,初始为可见且根据布局调整大小
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else {
Log.e(TAG, "Intent not specified action, should not support");
finish();
return false;
}
// 设置笔记对象的设置状态改变监听器为当前Activity实现了NoteSettingChangedListener接口
mWorkingNote.setOnSettingStatusChangedListener(this);
return true;
}
// Activity恢复可见时如从暂停状态恢复调用的方法用于初始化笔记编辑界面的相关显示内容
@Override
protected void onResume() {
super.onResume();
initNoteScreen();
}
// 初始化笔记编辑界面的显示内容,包括设置字体样式、根据笔记模式显示不同内容、设置头部和编辑区域的背景等
private void initNoteScreen() {
mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId));
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {
switchToListMode(mWorkingNote.getContent());
} else {
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
mNoteEditor.setSelection(mNoteEditor.getText().length());
}
for (Integer id : sBgSelectorSelectionMap.keySet()) {
findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);
}
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_YEAR));
/**
* TODO: 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 {
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);
};
}
// 当Activity接收到新的Intent时调用该方法比如通过启动模式设置可以接收新的Intent情况重新初始化Activity状态
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
initActivityState(intent);
}
// 在Activity可能被销毁前如系统内存不足、用户切换应用等情况保存当前Activity的相关状态信息比如正在编辑的笔记的ID等
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
/**
* IDIDID
*/
if (!mWorkingNote.existInDatabase()) {
saveNote();
}
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");
}
// 用于分发触摸事件,当背景颜色选择器或字体大小选择器可见时,判断触摸事件是否在其区域外,如果在区域外则隐藏相应的选择器视图
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&&!inRangeOfView(mNoteBgColorSelector, ev)) {
mNoteBgColorSelector.setVisibility(View.GONE);
return true;
}
if (mFontSizeSelector.getVisibility() == View.VISIBLE

@ -1,452 +0,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.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;
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
private int mIndex;
private int mSelectionStartBeforeDelete;
private static final String SCHEME_TEL = "tel:" ;
private static final String SCHEME_HTTP = "http:" ;
private static final String SCHEME_EMAIL = "mailto:" ;
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);
}
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
*/
public interface OnTextViewChangeListener {
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*/
void onEditTextDelete(int index, String text);
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*/
void onEditTextEnter(int index, String text);
/**
* Hide or show item option when text change
*/
void onTextChange(int index, boolean hasText);
}
private OnTextViewChangeListener mOnTextViewChangeListener;
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
}
public void setIndex(int index) {
mIndex = index;
}
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft();
y -= getTotalPaddingTop();
x += getScrollX();
y += getScrollY();
Layout layout = getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
Selection.setSelection(getText(), off);
break;
}
return super.onTouchEvent(event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
break;
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString();
setText(getText().subSequence(0, selectionStart));
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
break;
default:
break;
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false);
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);
}
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {
if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
urls[0].onClick(NoteEditText.this);
return true;
}
});
}
}
super.onCreateContextMenu(menu);
}
}
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类继承自EditText是一个自定义的文本编辑框控件在基础的文本编辑功能上进行了扩展
// 用于处理与便签编辑相关的特定交互逻辑,比如响应回车键、删除键操作,根据文本内容变化显示或隐藏相关菜单项,以及处理文本中的链接点击等功能。
public class NoteEditText extends EditText {
// 用于日志记录的标签,方便在日志输出中识别该类相关的日志信息。
private static final String TAG = "NoteEditText";
// 用于记录当前编辑文本框在整个编辑列表中的索引位置,方便在进行插入、删除等操作时确定其相对位置。
private int mIndex;
// 用于记录在按下删除键KEYCODE_DEL之前文本选择的起始位置以便后续判断是否执行特定的删除逻辑比如删除当前文本框等情况
private int mSelectionStartBeforeDelete;
// 定义电话链接的协议头(表示以拨打电话的方式打开链接)。
private static final String SCHEME_TEL = "tel:";
// 定义超文本传输协议链接的协议头(表示以网页浏览的方式打开链接)。
private static final String SCHEME_HTTP = "http:";
// 定义邮件链接的协议头(表示以发送邮件的方式打开链接)。
private static final String SCHEME_EMAIL = "mailto:";
// 用于将不同的链接协议头与对应的字符串资源ID进行映射这些字符串资源可能用于在菜单中显示对应链接类型的描述信息方便用户识别链接的作用。
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);
}
// 定义一个接口,用于与外部类(如`NoteEditActivity`)进行交互,通知外部在文本编辑框中文本发生特定变化(删除、添加、内容变更等)时进行相应处理。
public interface OnTextViewChangeListener {
/**
* KEYCODE_DEL
*/
void onEditTextDelete(int index, String text);
/**
* KEYCODE_ENTER
*/
void onEditTextEnter(int index, String text);
/**
*
*/
void onTextChange(int index, boolean hasText);
}
// 用于存储实现了`OnTextViewChangeListener`接口的监听器对象,外部类可以通过设置该监听器来响应文本编辑框中的相关文本变化事件。
private OnTextViewChangeListener mOnTextViewChangeListener;
// 构造函数接收上下文对象调用父类的构造函数进行初始化同时初始化当前编辑文本框的索引为0。
public NoteEditText(Context context) {
super(context, null);
mIndex = 0;
}
// 用于设置当前编辑文本框在整个编辑列表中的索引位置。
public void setIndex(int index) {
mIndex = index;
}
// 用于设置文本变化监听器对象,外部类通过传入实现了`OnTextViewChangeListener`接口的实例,来接收文本编辑框中的相关文本变化通知并进行处理。
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
// 构造函数,接收上下文和属性集对象,调用父类对应的构造函数进行初始化,采用系统默认的编辑文本框样式(通过`android.R.attr.editTextStyle`指定)。
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
// 构造函数接收上下文、属性集和默认样式资源ID调用父类对应的构造函数进行初始化此处`TODO Auto-generated constructor stub`表示可能需要后续补充一些特定的初始化逻辑(目前为空)。
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
// 重写父类的`onTouchEvent`方法,用于处理触摸事件,主要实现了点击文本区域时根据触摸位置设置文本光标位置的功能,以便用户能方便地在指定位置进行文本编辑操作。
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 获取触摸点相对于文本编辑框左边的距离(去除文本框的内边距等影响),并考虑滚动偏移量,得到在文本内容区域内的横坐标位置。
int x = (int) event.getX();
x -= getTotalPaddingLeft();
x += getScrollX();
// 获取触摸点相对于文本编辑框上边的距离(去除文本框的内边距等影响),并考虑滚动偏移量,得到在文本内容区域内的纵坐标位置。
int y = (int) event.getY();
y -= getTotalPaddingTop();
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`方法用于处理按键按下事件在这里主要是记录按下删除键KEYCODE_DEL时文本选择的起始位置以及在按下回车键KEYCODE_ENTER时进行一些特定的逻辑处理目前是返回false可能后续会添加更多逻辑
@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`方法,用于处理按键抬起事件,在这里根据抬起的按键不同执行不同的逻辑,
// 比如按下删除键抬起时如果文本框索引不为0且文本选择起始位置为0可能表示要删除当前文本框等情况则通知监听器执行删除逻辑
// 按下回车键抬起时,获取当前光标位置后的文本内容,将其作为新添加文本框的初始内容,并通知监听器执行添加文本框的逻辑。
@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`方法,用于创建上下文菜单(长按文本时弹出的菜单),在这里主要是处理文本中包含链接(通过`URLSpan`标识)的情况,
// 如果选中的文本区域内只有一个链接根据链接的协议头查找对应的菜单描述资源ID并添加一个菜单项用于点击链接执行相应操作如打开网页、拨打电话、发送邮件等
@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);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) {
int defaultResId = 0;
for (String schema : sSchemaActionResMap.keySet()) {
if (urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// 点击菜单项时执行链接对应的点击操作比如打开相应的网页、拨打电话或者发送邮件等调用URLSpan的onClick方法来触发具体操作。
urls[0].onClick(NoteEditText.this);
return true;
}
});
}
}
super.onCreateContextMenu(menu);
}
}

@ -1,224 +0,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;
public class NoteItemData {
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
};
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
mName = mPhoneNumber;
}
}
}
if (mName == null) {
mName = "";
}
checkPostion(cursor);
}
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
} else {
mIsOneNoteFollowingFolder = true;
}
}
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
public boolean isLast() {
return mIsLastItem;
}
public String getCallName() {
return mName;
}
public boolean isFirst() {
return mIsFirstItem;
}
public boolean isSingle() {
return mIsOnlyOneItem;
}
public long getId() {
return mId;
}
public long getAlertDate() {
return mAlertDate;
}
public long getCreatedDate() {
return mCreatedDate;
}
public boolean hasAttachment() {
return mHasAttachment;
}
public long getModifiedDate() {
return mModifiedDate;
}
public int getBgColorId() {
return mBgColorId;
}
public long getParentId() {
return mParentId;
}
public int getNotesCount() {
return mNotesCount;
}
public long getFolderId () {
return mParentId;
}
public int getType() {
return mType;
}
public int getWidgetType() {
return mWidgetType;
}
public int getWidgetId() {
return mWidgetId;
}
public String getSnippet() {
return mSnippet;
}
public boolean hasAlert() {
return (mAlertDate > 0);
}
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}

@ -1,132 +0,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.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;
public abstract class NoteWidgetProvider extends AppWidgetProvider {
public static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
};
public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
private static final String TAG = "NoteWidgetProvider";
@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])});
}
}
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);
/**
* Generate the pending intent to start host for the widget
*/
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);
}
}
}
protected abstract int getBgResourceId(int bgId);
protected abstract int getLayoutId();
protected abstract int getWidgetType();
}

@ -1,47 +0,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.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_2x extends NoteWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
}
@Override
protected int getLayoutId() {
return R.layout.widget_2x;
}
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X;
}
}

@ -1,46 +0,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.widget;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_4x extends NoteWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds);
}
protected int getLayoutId() {
return R.layout.widget_4x;
}
@Override
protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
}
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X;
}
}

File diff suppressed because it is too large Load Diff

@ -1,382 +0,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.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;
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;
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
};
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context;
mNotesCount = 0;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
}
public boolean isInChoiceMode() {
return mChoiceMode;
}
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mChoiceMode = mode;
}
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
}
}
}
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
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);
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*/
} else {
Log.e(TAG, "Invalid cursor");
return null;
}
}
}
return itemSet;
}
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0;
}
Iterator<Boolean> iter = values.iterator();
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
}
}
return count;
}
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
}
public boolean isSelectedItem(final int position) {
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() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
// NotesListAdapter类继承自CursorAdapter是一个用于适配便签列表数据到ListView等列表视图组件的适配器类
// 它负责将从数据库查询获取的Cursor数据转换为适合展示的视图项并处理了列表项的选择、计数以及与小部件相关属性获取等功能逻辑。
public class NotesListAdapter extends CursorAdapter {
// 用于日志记录的标签,方便在日志输出中识别该类相关的日志信息。
private static final String TAG = "NotesListAdapter";
// 用于存储上下文信息,方便后续在创建视图、获取资源等操作中使用。
private Context mContext;
// 使用HashMap来存储列表项的选中状态键为列表项的位置索引值为布尔类型表示是否被选中以此记录用户在多选模式下对各列表项的选择情况。
private HashMap<Integer, Boolean> mSelectedIndex;
// 用于记录便签的数量,通过遍历游标数据统计得出,便于后续判断全选等相关逻辑时使用。
private int mNotesCount;
// 用于标记当前列表是否处于多选模式,控制相关的界面交互和数据处理逻辑,例如是否显示多选菜单、是否响应多选相关操作等。
private boolean mChoiceMode;
// 内部静态类用于封装与便签关联的小部件的属性信息包含小部件的ID和类型两个成员变量方便在处理便签与小部件关联操作时传递和使用相关数据。
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
};
// 构造函数接收上下文对象作为参数调用父类构造函数传入上下文和空游标初始化同时初始化选中状态的HashMap和记录便签数量的变量并保存传入的上下文信息。
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context;
mNotesCount = 0;
}
// 重写父类的方法,用于创建一个新的视图对象来展示列表项,在这里返回一个自定义的`NotesListItem`视图对象,该对象负责具体的便签数据展示布局和渲染。
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
}
// 重写父类的方法,用于将数据绑定到已创建的视图对象上进行展示,在这里从游标中获取便签数据封装成`NoteItemData`对象,
// 然后调用`NotesListItem`的`bind`方法将数据、多选模式状态以及该项是否被选中的信息传递进去,完成数据与视图的绑定展示。
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
// 用于设置指定位置的列表项的选中状态,将位置索引和对应的选中状态存入`mSelectedIndex` HashMap中并通知数据集已改变使得列表视图能够更新相应的显示状态。
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
}
// 用于判断当前列表是否处于多选模式,外部代码可以调用该方法获取相应的状态信息,以决定是否显示多选相关的界面元素或执行相应逻辑。
public boolean isInChoiceMode() {
return mChoiceMode;
}
// 用于设置列表的多选模式状态,当进入或退出多选模式时调用该方法,会先清空之前的选中状态记录,然后更新`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集合遍历`mSelectedIndex`中所有被标记为选中的位置索引,通过`getItemId`方法获取对应项的ID
// 并添加到`HashSet`集合中返回同时对特殊的根文件夹ID情况进行日志记录因为可能不符合预期的选中逻辑
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
itemSet.add(id);
}
}
}
return itemSet;
}
// 用于获取所有已选中列表项关联的小部件属性集合,遍历`mSelectedIndex`中所有被标记为选中的位置索引,通过`getItem`方法获取对应位置的游标数据,
// 进而创建`AppWidgetAttribute`对象并填充小部件的ID和类型信息添加到`HashSet`集合中返回,同时对游标无效的情况进行日志记录并返回`null`。
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
if (c!= null) {
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
/**
* Don't close cursor here, only the adapter could close it
*/
} else {
Log.e(TAG, "Invalid cursor");
return null;
}
}
}
return itemSet;
}
// 用于获取当前已选中列表项的数量,通过获取`mSelectedIndex`中所有值(即各位置的选中状态)的集合,然后遍历该集合统计值为`true`(表示选中)的个数并返回。
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0;
}
Iterator<Boolean> iter = values.iterator();
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
}
}
return count;
}
// 用于判断是否所有符合条件通常是便签类型相关限定的列表项都已被选中通过比较已选中的数量和总的便签数量来确定若已选中数量不为0且等于便签数量则返回`true`,表示全选状态。
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount!= 0 && checkedCount == mNotesCount);
}
// 用于判断指定位置的列表项是否被选中,先判断对应位置在`mSelectedIndex`中的值是否为`null`(未记录则视为未选中),
// 若不为`null`则返回该位置记录的选中状态(`true`表示选中,`false`表示未选中)。
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
}
return mSelectedIndex.get(position);
}
// 重写父类的方法,当数据集内容发生变化时会被调用,在这里调用`calcNotesCount`方法重新计算便签的数量,以保证相关统计数据的准确性。
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
}
// 重写父类的方法,当游标数据发生改变(比如重新查询获取了新的数据)时会被调用,同样在这里调用`calcNotesCount`方法重新计算便签的数量,以适配新的数据情况。
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
}
// 私有方法用于计算便签的数量通过遍历游标中的所有记录根据记录对应的便签类型判断是否为普通便签若是则数量加1最终得到总的便签数量并更新`mNotesCount`变量。
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c!= null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}

@ -1,161 +0,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.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;
// NotesListItem类继承自LinearLayout代表了便签列表中的每一个列表项视图负责将便签相关的数据展示在对应的UI元素上
// 包括标题、时间、提醒图标、联系人姓名等信息,并根据不同的便签类型、状态等设置相应的显示样式和背景。
public class NotesListItem extends LinearLayout {
// 用于显示提醒图标的ImageView组件根据便签是否有提醒等情况来决定其显示与否以及显示的图标资源。
private ImageView mAlert;
// 用于显示便签标题的TextView组件展示便签的主要内容摘要或者文件夹名称等信息会根据不同的便签类型和状态设置合适的文本样式和内容。
private TextView mTitle;
// 用于显示便签相关时间信息如修改时间的TextView组件通过格式化处理将时间戳转换为相对时间的文本展示给用户。
private TextView mTime;
// 用于显示联系人姓名如果便签与通话记录等相关的TextView组件在对应的业务场景下展示相关联系人的名字。
private TextView mCallName;
// 用于存储当前列表项对应的便签数据对象,方便在其他方法中获取便签的各项属性来进行界面元素的设置和判断逻辑。
private NoteItemData mItemData;
// 用于在多选模式下显示选择状态的CheckBox组件根据是否处于多选模式以及当前便签类型等条件来控制其显示和选中状态。
private CheckBox mCheckBox;
// 构造函数,接收上下文对象作为参数,调用父类构造函数初始化,然后通过`inflate`方法将布局文件(`R.layout.note_item`填充到当前的LinearLayout中
// 并找到布局中的各个UI组件实例方便后续进行数据绑定和操作。
public NotesListItem(Context context) {
super(context);
inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
// 用于将便签数据绑定到列表项的各个UI组件上进行展示根据便签的类型、是否处于多选模式以及是否有提醒等不同情况设置相应组件的显示状态、文本内容、图标资源等信息
// 同时还会调用`setBackground`方法根据便签的状态设置合适的背景样式。
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 如果处于多选模式且当前便签类型为普通便签(`Notes.TYPE_NOTE`则显示CheckBox组件并根据传入的选中状态参数设置其选中状态。
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
// 否则隐藏CheckBox组件例如在非多选模式或者不是普通便签类型时不需要显示选择框。
mCheckBox.setVisibility(View.GONE);
}
// 将传入的便签数据对象赋值给成员变量,方便后续在其他方法中获取便签的各项属性信息进行操作。
mItemData = data;
// 如果便签的ID是通话记录文件夹的ID`Notes.ID_CALL_RECORD_FOLDER`进行以下针对通话记录文件夹类型的UI设置。
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
// 隐藏联系人姓名的TextView组件因为对于通话记录文件夹本身不需要展示联系人姓名。
mCallName.setVisibility(View.GONE);
// 显示提醒图标(这里的提醒图标可能代表通话记录相关的特定含义),并设置其可见状态为显示。
mAlert.setVisibility(View.VISIBLE);
// 设置标题的文本样式为主要项目的文本外观样式通过资源ID `R.style.TextAppearancePrimaryItem`指定)。
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()));
// 设置提醒图标的资源为通话记录相关的图标(`R.drawable.call_record`),使其显示对应的图标样式。
mAlert.setImageResource(R.drawable.call_record);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
// 如果便签的父ID是通话记录文件夹的ID意味着该便签属于通话记录文件夹下的具体便签进行以下设置。
mCallName.setVisibility(View.VISIBLE);
// 设置联系人姓名的TextView组件显示对应的联系人姓名通过获取便签数据中的联系人姓名属性进行展示。
mCallName.setText(data.getCallName());
// 设置标题的文本样式为次要项目的文本外观样式通过资源ID `R.style.TextAppearanceSecondaryItem`指定)。
mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem);
// 设置标题的文本内容为格式化后的便签片段内容(通过`DataUtils`工具类的方法进行格式化处理),展示便签的主要摘要信息。
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
// 如果便签有提醒设置,则显示提醒图标(这里是时钟图标代表提醒),并设置其可见状态为显示。
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
// 如果没有提醒设置,则隐藏提醒图标。
mAlert.setVisibility(View.GONE);
}
} else {
// 如果便签不属于通话记录文件夹相关情况进行以下通用的便签UI设置。
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 如果便签类型是文件夹类型(`Notes.TYPE_FOLDER`),设置标题的文本内容为文件夹名称加上该文件夹下便签数量的格式化文本,展示文件夹相关信息,同时隐藏提醒图标(文件夹一般无提醒概念)。
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);
}
}
}
// 设置时间的TextView组件显示的文本内容通过`DateUtils`工具类的方法将便签的修改时间戳转换为相对时间的文本格式如“刚刚”“10分钟前”等展示给用户。
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 调用`setBackground`方法,根据便签的数据信息(如类型、状态等)设置列表项的背景样式,以区分不同情况的便签显示效果。
setBackground(data);
}
// 私有方法,根据便签的数据信息(主要是类型、是否单独、是否是第一个、最后一个等状态信息)来设置列表项的背景资源,
// 通过`NoteItemBgResources`工具类的相关方法获取对应的背景资源ID并设置为当前列表项的背景。
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 {
// 如果是文件夹类型,则统一设置为文件夹对应的背景资源(通过`NoteItemBgResources`工具类的相关方法获取)。
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
// 用于获取当前列表项对应的便签数据对象,外部代码可以调用该方法获取便签的详细信息,方便进行其他相关的业务逻辑处理(比如点击列表项后根据便签数据进行相应操作等)。
public NoteItemData getItemData() {
return mItemData;
}
}

@ -1,743 +0,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.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);
/* using the app icon for navigation */
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();
// need to set sync account automatically if user has added a new
// account
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)) {
// the first time to set account
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
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);
// set button state
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
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();
// clean up last sync time
setLastSyncTime(this, 0);
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
}
editor.commit();
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();
}
public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
}
}
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return false;
}
}
}
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;
// NotesPreferenceActivity类继承自PreferenceActivity是用于管理便签应用偏好设置的Activity
// 涉及与账户相关的设置(如选择同步账户、切换账户、移除账户等)、同步操作的控制(开始同步、取消同步)以及根据不同状态更新界面显示等功能逻辑。
public class NotesPreferenceActivity extends PreferenceActivity {
// 用于存储偏好设置名称的常量作为获取SharedPreferences对象时的名称参数用于保存和读取应用的各种偏好设置数据。
public static final String PREFERENCE_NAME = "notes_preferences";
// 用于存储同步账户名称偏好设置的键名通过该键可以在SharedPreferences中存取当前选择的同步账户名称信息。
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
// 用于存储上次同步时间偏好设置的键名,用于记录和获取应用最后一次同步操作的时间戳信息。
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";
// 用于在偏好设置中标识账户相关分类的键名用于在布局资源中找到对应的PreferenceCategory组件方便进行账户相关偏好设置项的管理操作。
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
// 用于在添加账户意图中传递权限过滤相关信息的键名从代码中看是与添加谷歌账户相关操作中使用具体过滤“gmail-ls”权限相关情况用于控制账户添加时的一些权限筛选逻辑。
private static final String AUTHORITIES_FILTER_KEY = "authorities";
// 用于存储偏好设置中账户分类的PreferenceCategory对象通过它可以对账户相关的偏好设置项进行添加、移除等操作方便管理账户设置相关的UI展示和逻辑处理。
private PreferenceCategory mAccountCategory;
// 用于接收同步服务相关广播的广播接收器对象,当同步服务有状态变化(如开始同步、取消同步、同步进度更新等)时会接收到广播并进行相应的界面更新等操作。
private GTaskReceiver mReceiver;
// 用于存储原始的账户列表信息,在判断是否新增账户等逻辑中使用,通过对比前后账户列表来确定是否有账户添加的情况发生。
private Account[] mOriAccounts;
// 用于标记是否添加了新账户的布尔变量,在账户相关操作逻辑中(如在`onResume`方法中判断是否需要自动设置同步账户)根据其值来执行相应的处理逻辑。
private boolean mHasAddedAccount;
// Activity创建时调用的方法进行一些初始化操作如设置ActionBar的返回按钮可用、加载偏好设置资源文件、获取账户分类组件、注册广播接收器以及添加列表头部视图等操作。
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
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);
}
// Activity重新恢复到前台时调用的方法在这里主要判断是否有新添加的账户如果有则尝试自动设置同步账户然后调用`refreshUI`方法更新整个偏好设置界面的显示内容,以反映最新的状态。
@Override
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
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();
}
// Activity销毁时调用的方法在这里主要进行广播接收器的注销操作避免出现内存泄漏等问题然后调用父类的销毁方法完成其他相关的清理工作。
@Override
protected void onDestroy() {
if (mReceiver!= null) {
unregisterReceiver(mReceiver);
}
super.onDestroy();
}
// 用于加载账户偏好设置相关的UI展示内容先移除账户分类下已有的所有偏好设置项然后创建一个新的偏好设置项用于显示账户相关信息并设置其标题、摘要以及点击监听器等最后将其添加到账户分类中进行展示。
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)) {
// the first time to set account
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog();
}
} else {
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
mAccountCategory.addPreference(accountPref);
}
// 用于加载同步按钮相关的UI展示和点击事件逻辑设置根据同步服务当前是否正在同步来设置按钮的文本如显示“同步”或“取消同步”以及对应的点击监听器启动或取消同步操作
// 同时根据同步情况和上次同步时间来设置显示同步状态文本视图的内容和可见性,展示给用户同步相关的状态信息。
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
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);
}
}
}
// 用于更新整个偏好设置界面的显示内容,通过调用`loadAccountPreference`和`loadSyncButton`方法分别更新账户相关设置和同步按钮相关的UI展示以反映最新的应用状态和设置信息。
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();
}
// 用于获取设备上已登录的谷歌账户列表,通过`AccountManager`获取指定类型“com.google”的账户信息返回账户数组方便在账户选择等相关操作中展示和使用这些账户数据。
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
// 用于设置同步账户名称将传入的账户名称保存到SharedPreferences中同时进行一些相关的清理操作如重置上次同步时间、清除本地与同步任务`gtask`)相关的信息等,
// 最后通过Toast提示用户设置成功的信息并且只有当传入的账户名称与当前保存的不一致时才执行实际的设置操作。
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (account!= null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
editor.commit();
// clean up last sync time
setLastSyncTime(this, 0);
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
// 用于移除当前设置的同步账户相关信息从SharedPreferences中移除同步账户名称和上次同步时间的记录同时清除本地与同步任务`gtask`)相关的信息,以达到彻底移除账户相关设置的效果。
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
}
editor.commit();
// clean up local gtask related info
new Thread(new Runnable() {
public void run() {
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
// 静态方法用于获取当前设置的同步账户名称从SharedPreferences中根据对应的键`PREFERENCE_SYNC_ACCOUNT_NAME`)读取账户名称信息,如果不存在则返回空字符串。
public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
// 静态方法用于设置上次同步时间将传入的时间戳保存到SharedPreferences中通过编辑对象提交更改方便后续在界面展示等地方获取并显示上次同步的时间信息。
public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context

@ -1,213 +0,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.tool;
// 导入Android框架中的Context类和PreferenceManager类
import android.content.Context;
import android.preference.PreferenceManager;
// 导入项目中的资源类和偏好设置活动类
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
// 声明一个工具类,用于解析和管理资源
public class ResourceParser {
// 定义一些常量来表示不同的颜色
public static final int YELLOW = 0; // 黄色
public static final int BLUE = 1; // 蓝色
public static final int WHITE = 2; // 白色
public static final int GREEN = 3; // 绿色
public static final int RED = 4; // 红色
// 默认背景颜色设置为黄色
public static final int BG_DEFAULT_COLOR = YELLOW;
// 定义一些常量来表示不同的字体大小
public static final int TEXT_SMALL = 0; // 小号字体
public static final int TEXT_MEDIUM = 1; // 中号字体
public static final int TEXT_LARGE = 2; // 大号字体
public static final int TEXT_SUPER = 3; // 特大字体
// 默认字体大小设置为中号
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// 内部类,用于管理笔记背景资源
public static class NoteBgResources {
// 定义不同颜色背景的编辑界面资源数组
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
};
// 定义不同颜色背景的编辑界面标题资源数组
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
};
// 根据颜色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) {
// 检查用户是否设置了背景颜色偏好
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 如果设置了则随机返回一个颜色ID
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 否则返回默认颜色ID
return BG_DEFAULT_COLOR;
}
}
// 内部类,用于管理笔记条目背景资源
public static class NoteItemBgResources {
// 定义不同颜色背景的列表第一项资源数组
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
};
// 定义不同颜色背景的列表正常项资源数组
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
};
// 定义不同颜色背景的列表最后一项资源数组
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
};
// 定义不同颜色背景的列表单项资源数组(用于只有一个条目时)
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
};
// 根据颜色ID获取对应的列表第一项背景资源
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
// 根据颜色ID获取对应的列表最后一项背景资源
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
// 根据颜色ID获取对应的列表单项背景资源
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
// 根据颜色ID获取对应的列表正常项背景资源
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
// 获取文件夹背景资源
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
// 内部类,用于管理小部件背景资源
public static class WidgetBgResources {
// 定义不同颜色背景的小部件2x大小资源数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
// 根据颜色ID获取对应的小部件2x大小背景资源
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 定义不同颜色背景的小部件4x大小资源数组
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
// 根据颜色ID获取对应的小部件4x大小背景资源
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
// 内部类,用于管理文本外观资源
public static class TextAppearanceResources {
// 定义不同字体大小的文本外观资源数组
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
// 根据字体大小ID获取对应的文本外观资源
// 注意这里有一个检查如果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;
}
}
}

@ -1,361 +0,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.model; // 定义包名,用于组织类
import android.appwidget.AppWidgetManager; // 导入Android的小部件管理器类
// 定义一个名为WorkingNote的公共类
public class WorkingNote {
// 定义一个Note类型的私有成员变量mNote用于存储笔记信息
private Note mNote;
// 定义一个长整型私有成员变量mNoteId用于存储笔记的ID
private long mNoteId;
// 定义一个字符串类型的私有成员变量mContent用于存储笔记的内容
private String mContent;
// 定义一个整型私有成员变量mMode用于存储笔记的模式
private int mMode;
// 定义一个长整型私有成员变量mAlertDate用于存储笔记的提醒日期
private long mAlertDate;
// 定义一个长整型私有成员变量mModifiedDate用于存储笔记的最后修改日期
private long mModifiedDate;
// 定义一个整型私有成员变量mBgColorId用于存储笔记的背景颜色ID
private int mBgColorId;
// 定义一个整型私有成员变量mWidgetId用于存储笔记关联的小部件ID
private int mWidgetId;
// 定义一个整型私有成员变量mWidgetType用于存储笔记关联的小部件类型
private int mWidgetType;
// 定义一个长整型私有成员变量mFolderId用于存储笔记所属的文件夹ID
private long mFolderId;
// 定义一个Context类型的私有成员变量mContext用于获取应用程序的上下文
private Context mContext;
// 定义一个静态的字符串常量TAG用于日志输出
private static final String TAG = "WorkingNote";
// 定义一个布尔型的私有成员变量mIsDeleted用于标记笔记是否被删除
private boolean mIsDeleted;
// 定义一个NoteSettingChangedListener类型的私有成员变量mNoteSettingStatusListener用于监听笔记设置变化
private NoteSettingChangedListener mNoteSettingStatusListener;
// 定义一个静态的字符串数组DATA_PROJECTION用于指定查询数据库时返回的列
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
// 定义一个静态的字符串数组NOTE_PROJECTION用于指定查询笔记数据库时返回的列
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE
};
// 定义一些常量,用于索引查询结果中的列
private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// 私有构造函数,用于创建新的笔记对象
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
mModifiedDate = System.currentTimeMillis(); // 设置当前时间为最后修改时间
mFolderId = folderId;
mNote = new Note(); // 初始化Note对象
mNoteId = 0;
mIsDeleted = false;
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE; // 设置默认的小部件类型为无效
}
// 私有构造函数,用于加载已存在的笔记对象
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
mIsDeleted = false;
mNote = new Note();
loadNote(); // 加载笔记信息
}
// 私有方法,用于从数据库中加载笔记信息
private void loadNote() {
// 使用ContentResolver查询数据库获取指定ID的笔记信息
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
// 从查询结果中读取笔记的详细信息
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
}
cursor.close(); // 关闭Cursor
} else {
// 如果查询失败,则记录日志并抛出异常
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData(); // 加载笔记的附加数据
}
// 定义一个私有方法,用于加载笔记数据
private void loadNoteData() {
// 使用内容解析器查询笔记数据
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
}, null);
// 检查查询结果是否非空
if (cursor != null) {
// 移动到查询结果的第一行
if (cursor.moveToFirst()) {
do {
// 获取笔记的类型
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
// 如果是普通笔记类型
if (DataConstants.NOTE.equals(type)) {
// 获取笔记内容
mContent = cursor.getString(DATA_CONTENT_COLUMN);
// 获取笔记的模式(如检查列表模式)
mMode = cursor.getInt(DATA_MODE_COLUMN);
// 设置笔记的ID
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
}
// 如果是电话笔记类型
else if (DataConstants.CALL_NOTE.equals(type)) {
// 设置电话笔记的ID
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
// 如果类型不匹配,记录日志
Log.d(TAG, "Wrong note type with type:" + type);
}
} while (cursor.moveToNext()); // 继续移动到下一行,直到遍历完所有结果
}
// 关闭游标
cursor.close();
} else {
// 如果查询结果为空,记录错误日志并抛出异常
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}
}
// 定义一个静态方法,用于创建一个空的笔记对象
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
// 初始化笔记对象并设置属性
WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
note.setWidgetType(widgetType);
return note;
}
// 定义一个静态方法用于根据ID加载笔记对象
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
// 定义一个同步方法,用于保存笔记
public synchronized boolean saveNote() {
// 检查笔记是否值得保存
if (isWorthSaving()) {
// 如果笔记在数据库中不存在
if (!existInDatabase()) {
// 获取一个新的笔记ID
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
// 如果获取ID失败记录错误日志并返回false
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
// 同步笔记数据到数据库
mNote.syncNote(mContext, mNoteId);
// 如果笔记关联了小部件,并且小部件有效,通知小部件内容已更改
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
return true; // 保存成功
} else {
return false; // 不值得保存
}
}
// 检查笔记是否存在于数据库中
public boolean existInDatabase() {
return mNoteId > 0;
}
// 检查笔记是否值得保存
private boolean isWorthSaving() {
// 如果笔记被标记为删除,或者不存在于数据库中且内容为空,或者存在于数据库中但未被本地修改,则不值得保存
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
} else {
return true;
}
}
// 设置笔记设置状态改变的监听器
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
// 设置提醒日期
public void setAlertDate(long date, boolean set) {
// 如果设置的日期与当前日期不同,更新日期并通知监听器
if (date != mAlertDate) {
mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
}
// 如果设置了监听器,通知监听器提醒日期已更改
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onClockAlertChanged(date, set);
}
}
// 标记笔记为已删除或未删除
public void markDeleted(boolean mark) {
mIsDeleted = mark;
// 如果笔记关联了小部件,并且小部件有效,通知小部件内容已更改
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
}
// 设置笔记背景颜色ID
public void setBgColorId(int id) {
// 如果设置的ID与当前ID不同更新ID并通知监听器
if (id != mBgColorId) {
mBgColorId = id;
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged();
}
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
}
}
// 设置检查列表模式
public void setCheckListMode(int mode) {
// 如果设置的模式与当前模式不同,更新模式并通知监听器
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
}
mMode = mode;
mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
}
}
// 设置小部件类型
public void setWidgetType(int type) {
// 如果设置的小部件类型与当前类型不同,更新类型
if (type != mWidgetType) {
mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
}
}
// 设置小部件ID
public void setWidgetId(int id) {
// 如果设置的小部件ID与当前ID不同更新ID
if (id != mWidgetId) {
mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
}
}
// 设置笔记内容
public void setWorkingText(String text) {
// 如果设置的内容与当前内容不同,更新内容
if (!TextUtils.equals(mContent, text)) {
mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent);
}
}
// 将笔记转换为电话笔记
public void convertToCallNote(String phoneNumber, long callDate) {
// 设置电话笔记的日期和电话号码
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
// 设置电话笔记所属的文件夹ID为电话记录文件夹
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}
// 检查笔记是否有提醒日期
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}
// 获取笔记内容
public String getContent() {
return mContent;
}
// 获取笔记的提醒日期
public long getAlertDate() {
return mAlertDate;
}
// 获取笔记的最后修改日期
public long getModifiedDate() {
return mModifiedDate;
}
// 获取笔记背景颜色的资源ID
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
// 获取笔记背景颜色的ID
public int getBgColorId

Binary file not shown.

Binary file not shown.
Loading…
Cancel
Save