Compare commits

..

24 Commits
master ... duan

Author SHA1 Message Date
dxj babf2a6263 java/net/micode/notes/widget/NoteWidgetProvider_4x.java
2 months ago
dxj 8c1c4082d6 java/net/micode/notes/widget/NoteWidgetProvider_2x.java
2 months ago
dxj 1117cdc99a java/net/micode/notes/widget/NoteWidgetProvider.java
2 months ago
dxj a4f37ebbaf java/net/micode/notes/ui/NotesPreferenceActivity.java
2 months ago
dxj 8c81e9b068 java/net/micode/notes/ui/NotesListItem.java
2 months ago
dxj d0e9099c79 java/net/micode/notes/ui/NotesListAdapter.java
2 months ago
dxj 6d1cc27695 java/net/micode/notes/ui/NotesListAdapter.java
2 months ago
dxj a9409c9f1d java/net/micode/notes/ui/NotesListActivity.java
2 months ago
dxj 450f9ac78c java/net/micode/notes/ui/NoteItemData.java
2 months ago
dxj 3c652b9d11 java/net/micode/notes/ui/NoteEditText.java
2 months ago
dxj 5efbfb2bb0 java/net/micode/notes/ui/NoteEditActivity.java
2 months ago
dxj e508f53f1e java/net/micode/notes/ui/FoldersListAdapter.java
2 months ago
dxj fab7301354 ui/DropdownMenu
3 months ago
dxj cc9514e5d8 ui/DateTimePickerDialog
3 months ago
dxj f2e9a9ee96 ui/DataTimePicker的注释
3 months ago
dxj d0a5d5ab38 这段代码是一个Android广播接收器(BroadcastReceiver),它的核心作用是在系统闹钟提醒触发时,启动一个全屏的提醒界面。
3 months ago
dxj a58728df00 这段代码是一个Android广播接收器(BroadcastReceiver),它的核心作用是在系统闹钟提醒触发时,启动一个全屏的提醒界面。
3 months ago
dxj 86c2ec5569 Merge branch 'duan' of https://bdgit.educoder.net/pq36pyhjl/miNote2 into duan
3 months ago
dxj e6730baeb2 注释java\net\micode\notes\ui\AlarmInitReceiver.java文件,该文件实现了闹钟初始化广播接收器,用于在系统启动或时间变更时重新设置所有未触发的便签提醒,继承自BroadcastReceiver,监听系统广播事件
3 months ago
dxj 9e1b5bdccc 注释java\net\micode\notes\ui\AlarmInitReceiver.java文件,该文件实现了闹钟初始化广播接收器,用于在系统启动或时间变更时重新设置所有未触发的便签提醒,继承自BroadcastReceiver,监听系统广播事件
3 months ago
dxj 32cb7de08c 注释java/net/micode/notes/ui/AlarmAlertActivity.java下的代码,该部分实现了闹钟提醒活动,负责处理便签提醒触发时的界面和声音播放,实现对话框按钮点击监听器和对话框关闭监听器
3 months ago
dxj f4f28055df Merge branch 'duan' of https://bdgit.educoder.net/pq36pyhjl/miNote2 into duan
3 months ago
dxj 2f8d089b95 test
3 months ago
林俊彦 eb4ffdd6c9 版本0
3 months ago

@ -14,8 +14,12 @@
* limitations under the License. * limitations under the License.
*/ */
/*
*
*/
package net.micode.notes.ui; package net.micode.notes.ui;
// 导入Android基础组件
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;
@ -23,9 +27,13 @@ import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener; import android.content.DialogInterface.OnDismissListener;
import android.content.Intent; import android.content.Intent;
// 导入音频相关组件
import android.media.AudioManager; import android.media.AudioManager;
import android.media.MediaPlayer; import android.media.MediaPlayer;
import android.media.RingtoneManager; import android.media.RingtoneManager;
// 导入Android系统服务相关
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.PowerManager; import android.os.PowerManager;
@ -33,104 +41,104 @@ import android.provider.Settings;
import android.view.Window; import android.view.Window;
import android.view.WindowManager; import android.view.WindowManager;
// 导入项目资源
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.DataUtils;
import java.io.IOException; import java.io.IOException;
/**
* - 便
*
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
private long mNoteId; private long mNoteId; // 用于存储便签ID
private String mSnippet; private String mSnippet; // 用于存储便签摘要
private static final int SNIPPET_PREW_MAX_LEN = 60; private static final int SNIPPET_PREW_MAX_LEN = 60; // 便签摘要的最大长度
MediaPlayer mPlayer; MediaPlayer mPlayer; // 用于播放闹钟声音的MediaPlayer对象
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
final Window win = getWindow(); final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); // 设置窗口在锁屏状态下显示
if (!isScreenOn()) { if (!isScreenOn()) { // 如果屏幕未点亮,则设置相关标志以点亮屏幕
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
} }
Intent intent = getIntent(); Intent intent = getIntent(); // 获取启动此活动的Intent
try { try {
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); // 从Intent中获取便签ID
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); // 根据ID获取便签摘要
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet; : mSnippet; // 截取摘要并添加额外信息
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
mPlayer = new MediaPlayer(); mPlayer = new MediaPlayer(); // 创建MediaPlayer对象
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { // 检查便签是否可见
showActionDialog(); showActionDialog(); // 显示操作对话框
playAlarmSound(); playAlarmSound(); // 播放闹钟声音
} else { } else {
finish(); finish(); // 如果便签不可见,则结束活动
} }
} }
private boolean isScreenOn() { private boolean isScreenOn() { // 检查屏幕是否点亮
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn(); return pm.isScreenOn();
} }
private void playAlarmSound() { private void playAlarmSound() { // 播放闹钟声音
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); // 获取默认闹钟铃声URI
int silentModeStreams = Settings.System.getInt(getContentResolver(), int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); // 获取静音模式下受影响的音频流类型
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { // 如果闹钟声音被静音则设置MediaPlayer的音频流类型
mPlayer.setAudioStreamType(silentModeStreams); mPlayer.setAudioStreamType(silentModeStreams);
} else { } else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
} }
try { try {
mPlayer.setDataSource(this, url); mPlayer.setDataSource(this, url); // 设置MediaPlayer的数据源
mPlayer.prepare(); mPlayer.prepare(); // 准备播放
mPlayer.setLooping(true); mPlayer.setLooping(true); // 设置循环播放
mPlayer.start(); mPlayer.start(); // 开始播放
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (SecurityException e) { } catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
private void showActionDialog() { private void showActionDialog() { // 显示操作对话框
AlertDialog.Builder dialog = new AlertDialog.Builder(this); AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.app_name); dialog.setTitle(R.string.app_name); // 设置对话框标题
dialog.setMessage(mSnippet); dialog.setMessage(mSnippet); // 设置对话框消息
dialog.setPositiveButton(R.string.notealert_ok, this); dialog.setPositiveButton(R.string.notealert_ok, this); // 设置确定按钮及其监听器
if (isScreenOn()) { if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this); dialog.setNegativeButton(R.string.notealert_enter, this); // 如果屏幕已点亮,则设置取消按钮及其监听器
} }
dialog.show().setOnDismissListener(this); dialog.show().setOnDismissListener(this); // 显示对话框并设置关闭监听器
} }
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) { // 对话框按钮点击事件处理
switch (which) { switch (which) {
case DialogInterface.BUTTON_NEGATIVE: case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
@ -143,16 +151,16 @@ public class AlarmAlertActivity extends Activity implements OnClickListener, OnD
} }
} }
public void onDismiss(DialogInterface dialog) { public void onDismiss(DialogInterface dialog) { // 对话框关闭事件处理
stopAlarmSound(); stopAlarmSound(); // 停止闹钟声音
finish(); finish(); // 结束活动
} }
private void stopAlarmSound() { private void stopAlarmSound() { // 停止闹钟声音
if (mPlayer != null) { if (mPlayer != null) {
mPlayer.stop(); mPlayer.stop(); // 停止播放
mPlayer.release(); mPlayer.release(); // 释放资源
mPlayer = null; mPlayer = null; // 置空引用
} }
} }
} }

@ -16,6 +16,7 @@
package net.micode.notes.ui; package net.micode.notes.ui;
// 导入Android系统服务相关
import android.app.AlarmManager; import android.app.AlarmManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
@ -24,42 +25,59 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.database.Cursor; import android.database.Cursor;
// 导入项目数据模型和常量
import net.micode.notes.data.Notes; import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
* 广 - 便
* BroadcastReceiver广
*/
public class AlarmInitReceiver extends BroadcastReceiver { public class AlarmInitReceiver extends BroadcastReceiver {
// 数据库查询投影列(需要查询的字段)
private static final String [] PROJECTION = new String [] { private static final String [] PROJECTION = new String [] {
NoteColumns.ID, NoteColumns.ID, // 便签ID列
NoteColumns.ALERTED_DATE NoteColumns.ALERTED_DATE // 提醒时间列
}; };
private static final int COLUMN_ID = 0; // 列索引常量
private static final int COLUMN_ALERTED_DATE = 1; private static final int COLUMN_ID = 0; // ID列的索引
private static final int COLUMN_ALERTED_DATE = 1; // 提醒时间列的索引
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
long currentDate = System.currentTimeMillis(); long currentDate = System.currentTimeMillis(); // 获取当前系统时间
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, // 查询内容提供者获取需要设置提醒的便签
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, Cursor c = context.getContentResolver().query(
new String[] { String.valueOf(currentDate) }, Notes.CONTENT_NOTE_URI, // 便签内容URI
null); PROJECTION, // 需要查询的列
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, // 筛选条件:提醒时间未过期且类型为普通便签
new String[] { String.valueOf(currentDate) }, // 当前时间作为筛选参数
null); // 排序方式(无)
if (c != null) { if (c != null) {
if (c.moveToFirst()) { if (c.moveToFirst()) { // 游标移动到第一条记录
do { do {
long alertDate = c.getLong(COLUMN_ALERTED_DATE); long alertDate = c.getLong(COLUMN_ALERTED_DATE); // 获取提醒时间
// 创建发送给AlarmReceiver的Intent
Intent sender = new Intent(context, AlarmReceiver.class); Intent sender = new Intent(context, AlarmReceiver.class);
// 设置数据URINote内容URI + 当前便签ID
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID))); sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));
// 创建PendingIntent延迟触发的广播
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alermManager = (AlarmManager) context
// 获取系统闹钟服务
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE); .getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); // 设置精确闹钟RTC_WAKEUP会在指定时间唤醒设备
} while (c.moveToNext()); alarmManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 循环处理下一条记录
} }
c.close(); c.close(); // 关闭游标释放资源
} }
} }
} }

@ -1,30 +1,39 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * MiCode
* * Apache License 2.0
* 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; package net.micode.notes.ui;
// 导入必要的Android类
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
/**
* BroadcastReceiver
* 广
*/
//111111111111111
// 11111111111
public class AlarmReceiver extends BroadcastReceiver { public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
* @param context
* @param intent 广
*/
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 将接收到的意图重定向到闹钟提醒Activity
intent.setClass(context, AlarmAlertActivity.class); intent.setClass(context, AlarmAlertActivity.class);
// 添加新的任务栈标识因为可能从非Activity环境启动Activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动闹钟提醒界面Activity
context.startActivity(intent); context.startActivity(intent);
} }
} }

@ -1,17 +1,6 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) *
* * Apache License 2.0 MiCode
* 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; package net.micode.notes.ui;
@ -21,64 +10,102 @@ import java.util.Calendar;
import net.micode.notes.R; import net.micode.notes.R;
import android.content.Context; import android.content.Context;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.view.View; import android.view.View;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.NumberPicker; import android.widget.NumberPicker;
/**
* DateTimePicker FrameLayout
*/
public class DateTimePicker extends FrameLayout { public class DateTimePicker extends FrameLayout {
// 默认启用状态
private static final boolean DEFAULT_ENABLE_STATE = true; private static final boolean DEFAULT_ENABLE_STATE = true;
// 一天中的小时数12小时制
private static final int HOURS_IN_HALF_DAY = 12; private static final int HOURS_IN_HALF_DAY = 12;
// 一天中的小时数24小时制
private static final int HOURS_IN_ALL_DAY = 24; private static final int HOURS_IN_ALL_DAY = 24;
// 一周中的天数
private static final int DAYS_IN_ALL_WEEK = 7; private static final int DAYS_IN_ALL_WEEK = 7;
// 日期选择器的最小值
private static final int DATE_SPINNER_MIN_VAL = 0; private static final int DATE_SPINNER_MIN_VAL = 0;
// 日期选择器的最大值(一周的天数减一)
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;
// 24小时制下小时选择器的最小值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;
// 24小时制下小时选择器的最大值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;
// 12小时制下小时选择器的最小值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;
// 12小时制下小时选择器的最大值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;
// 分钟选择器的最小值
private static final int MINUT_SPINNER_MIN_VAL = 0; private static final int MINUT_SPINNER_MIN_VAL = 0;
// 分钟选择器的最大值
private static final int MINUT_SPINNER_MAX_VAL = 59; private static final int MINUT_SPINNER_MAX_VAL = 59;
// 上午/下午选择器的最小值
private static final int AMPM_SPINNER_MIN_VAL = 0; private static final int AMPM_SPINNER_MIN_VAL = 0;
// 上午/下午选择器的最大值
private static final int AMPM_SPINNER_MAX_VAL = 1; private static final int AMPM_SPINNER_MAX_VAL = 1;
// 日期选择器组件
private final NumberPicker mDateSpinner; private final NumberPicker mDateSpinner;
// 小时选择器组件
private final NumberPicker mHourSpinner; private final NumberPicker mHourSpinner;
// 分钟选择器组件
private final NumberPicker mMinuteSpinner; private final NumberPicker mMinuteSpinner;
// 上午/下午选择器组件
private final NumberPicker mAmPmSpinner; private final NumberPicker mAmPmSpinner;
// 当前选中的日期
private Calendar mDate; private Calendar mDate;
// 用于显示日期的字符串数组
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK]; private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 是否是上午
private boolean mIsAm; private boolean mIsAm;
// 是否为24小时制视图
private boolean mIs24HourView; private boolean mIs24HourView;
// 控件是否启用
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; private boolean mIsEnabled = DEFAULT_ENABLE_STATE;
// 是否正在初始化
private boolean mInitialising; private boolean mInitialising;
// 日期时间变化监听器
private OnDateTimeChangedListener mOnDateTimeChangedListener; private OnDateTimeChangedListener mOnDateTimeChangedListener;
// 日期选择器值变化监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 更新日期
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl(); updateDateControl();
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
// 小时选择器值变化监听器
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false; boolean isDateChanged = false;
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
if (!mIs24HourView) { if (!mIs24HourView) {
// 处理12小时制下的日期变化
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) { if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
@ -88,12 +115,14 @@ public class DateTimePicker extends FrameLayout {
cal.add(Calendar.DAY_OF_YEAR, -1); cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true; isDateChanged = true;
} }
// 切换上午/下午状态
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY || if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) { oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm; mIsAm = !mIsAm;
updateAmPmControl(); updateAmPmControl();
} }
} else { } else {
// 处理24小时制下的日期变化
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) { if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
@ -104,9 +133,11 @@ public class DateTimePicker extends FrameLayout {
isDateChanged = true; isDateChanged = true;
} }
} }
// 更新小时并设置到日历对象中
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY); int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour); mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged(); onDateTimeChanged();
// 如果日期发生变化,则更新年、月、日
if (isDateChanged) { if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR)); setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH)); setCurrentMonth(cal.get(Calendar.MONTH));
@ -115,142 +146,256 @@ public class DateTimePicker extends FrameLayout {
} }
}; };
/**
*
*/
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 获取分钟选择器的最小值和最大值0 和 59
int minValue = mMinuteSpinner.getMinValue(); int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue(); int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0; int offset = 0;
/*
* 59 -> 0
* 0 -> 59退
*/
if (oldVal == maxValue && newVal == minValue) { if (oldVal == maxValue && newVal == minValue) {
offset += 1; offset += 1; // 增加一小时
} else if (oldVal == minValue && newVal == maxValue) { } else if (oldVal == minValue && newVal == maxValue) {
offset -= 1; offset -= 1; // 减少一小时
} }
// 如果有小时偏移(即跨了小时)
if (offset != 0) { if (offset != 0) {
// 更新日历中的小时值
mDate.add(Calendar.HOUR_OF_DAY, offset); mDate.add(Calendar.HOUR_OF_DAY, offset);
// 同步更新小时选择器的显示值
mHourSpinner.setValue(getCurrentHour()); mHourSpinner.setValue(getCurrentHour());
// 更新日期控件(可能跨天)
updateDateControl(); updateDateControl();
// 获取当前小时24小时制
int newHour = getCurrentHourOfDay(); int newHour = getCurrentHourOfDay();
/*
* AM PM AM/PM
* - >= 12 PM
* - AM
*/
if (newHour >= HOURS_IN_HALF_DAY) { if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false; mIsAm = false;
updateAmPmControl(); updateAmPmControl(); // 更新 AM/PM 显示
} else { } else {
mIsAm = true; mIsAm = true;
updateAmPmControl(); updateAmPmControl(); // 更新 AM/PM 显示
} }
} }
// 设置新的分钟值到日历对象中
mDate.set(Calendar.MINUTE, newVal); mDate.set(Calendar.MINUTE, newVal);
// 触发日期时间变化的回调
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
/**
* AM/PM AM/PM
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override @Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) { public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 切换 AM/PM 状态true 表示 AMfalse 表示 PM
mIsAm = !mIsAm; mIsAm = !mIsAm;
// 根据当前是 AM 还是 PM 调整小时数:
if (mIsAm) { if (mIsAm) {
// 如果切换为 AM则减去 12 小时
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else { } else {
// 如果切换为 PM则加上 12 小时
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
} }
// 更新 AM/PM 控件显示状态
updateAmPmControl(); updateAmPmControl();
// 通知外部监听器日期时间已发生变化
onDateTimeChanged(); onDateTimeChanged();
} }
}; };
/**
*
*/
public interface OnDateTimeChangedListener { public interface OnDateTimeChangedListener {
/**
*
*
* @param view DateTimePicker
* @param year
* @param month 0
* @param dayOfMonth
* @param hourOfDay 24
* @param minute
*/
void onDateTimeChanged(DateTimePicker view, int year, int month, void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute); int dayOfMonth, int hourOfDay, int minute);
} }
/**
* 使 DateTimePicker
*/
public DateTimePicker(Context context) { public DateTimePicker(Context context) {
this(context, System.currentTimeMillis()); this(context, System.currentTimeMillis());
} }
/**
* 使 DateTimePicker
* 使 24
*
* @param context Activity Application
* @param date
*/
public DateTimePicker(Context context, long date) { public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context)); this(context, date, DateFormat.is24HourFormat(context));
} }
/**
* DateTimePicker UI
*
* @param context
* @param date
* @param is24HourView 使 24
*/
public DateTimePicker(Context context, long date, boolean is24HourView) { public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context); super(context);
// 初始化 Calendar 对象,用于保存当前选择的日期时间
mDate = Calendar.getInstance(); mDate = Calendar.getInstance();
// 标记为正在初始化中(避免监听器在初始化过程中触发不必要的回调)
mInitialising = true; mInitialising = true;
// 判断当前是否为 AM小时 >= 12 表示 PM
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY;
// 加载布局文件 R.layout.datetime_picker 并添加到当前 FrameLayout 中
inflate(context, R.layout.datetime_picker, this); inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器 NumberPicker
mDateSpinner = (NumberPicker) findViewById(R.id.date); mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL); // 设置最小值为 0
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL); // 设置最大值为 6一周7天
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); // 设置监听器
// 初始化小时选择器 NumberPicker
mHourSpinner = (NumberPicker) findViewById(R.id.hour); mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); // 设置监听器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化分钟选择器 NumberPicker
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL); // 设置最小值为 0
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL); // 设置最大值为 59
mMinuteSpinner.setOnLongPressUpdateInterval(100); // 长按递增间隔时间为 100ms
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); // 设置监听器
// 获取 AM/PM 的本地化字符串(如 "AM", "PM"
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings(); String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
// 初始化 AM/PM 选择器 NumberPicker
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm); mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL); // 设置最小值为 0
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL); // 设置最大值为 1
mAmPmSpinner.setDisplayedValues(stringsForAmPm); mAmPmSpinner.setDisplayedValues(stringsForAmPm); // 设置显示值为 "AM"/"PM"
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); // 设置监听器
// update controls to initial state // 初始化各控件的显示状态
updateDateControl(); updateDateControl(); // 更新日期选择器显示
updateHourControl(); updateHourControl(); // 更新小时选择器显示
updateAmPmControl(); updateAmPmControl(); // 更新 AM/PM 显示状态
// 设置是否启用 24 小时制视图
set24HourView(is24HourView); set24HourView(is24HourView);
// set to current time // 设置初始日期时间
setCurrentDate(date); setCurrentDate(date);
// 设置控件的启用状态
setEnabled(isEnabled()); setEnabled(isEnabled());
// set the content descriptions // 设置内容描述等辅助功能信息(未展示具体实现)
// 结束初始化过程
mInitialising = false; mInitialising = false;
} }
/**
* setEnabled DateTimePicker /
*
* @param enabled true false
*/
@Override @Override
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
// 如果当前状态与目标状态相同,则无需处理
if (mIsEnabled == enabled) { if (mIsEnabled == enabled) {
return; return;
} }
// 调用父类方法设置自身启用状态
super.setEnabled(enabled); super.setEnabled(enabled);
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled); // 设置各个 NumberPicker 子控件的启用状态
mHourSpinner.setEnabled(enabled); mDateSpinner.setEnabled(enabled); // 日期选择器
mAmPmSpinner.setEnabled(enabled); mMinuteSpinner.setEnabled(enabled); // 分钟选择器
mHourSpinner.setEnabled(enabled); // 小时选择器
mAmPmSpinner.setEnabled(enabled); // AM/PM 选择器
// 更新当前控件的启用状态标志
mIsEnabled = enabled; mIsEnabled = enabled;
} }
/**
* isEnabled
*
* @return true false
*/
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return mIsEnabled; return mIsEnabled; // 返回内部保存的启用状态标志
} }
/** /**
* Get the current date in millis *
* *
* @return the current date in millis * @return
*/ */
public long getCurrentDateInTimeMillis() { public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis(); return mDate.getTimeInMillis(); // 返回 Calendar 对象中的时间戳
} }
/** /**
* Set the current date *
* *
* @param date The current date in millis * @param date
*/ */
public void setCurrentDate(long date) { public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date); cal.setTimeInMillis(date); // 将时间戳转换为 Calendar 对象
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE)); // 调用另一个方法设置年、月、日、小时、分钟
setCurrentDate(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY),
cal.get(Calendar.MINUTE));
} }
/** /**
@ -262,224 +407,338 @@ public class DateTimePicker extends FrameLayout {
* @param hourOfDay The current hourOfDay * @param hourOfDay The current hourOfDay
* @param minute The current minute * @param minute The current minute
*/ */
public void setCurrentDate(int year, int month, /**
int dayOfMonth, int hourOfDay, int minute) { *
*
* @param year 2025
* @param month 0 11
* @param dayOfMonth 1
* @param hourOfDay 240~23
* @param minute 0~59
*/
public void setCurrentDate(int year, int month, int dayOfMonth, int hourOfDay, int minute) {
// 设置年份
setCurrentYear(year); setCurrentYear(year);
// 设置月份
setCurrentMonth(month); setCurrentMonth(month);
// 设置日
setCurrentDay(dayOfMonth); setCurrentDay(dayOfMonth);
// 设置小时
setCurrentHour(hourOfDay); setCurrentHour(hourOfDay);
// 设置分钟
setCurrentMinute(minute); setCurrentMinute(minute);
} }
/** /**
* Get current year * Get current year
* *
* @return The current year * @return The current year
*/ */
/**
*
*
* @return Calendar 2025
*/
public int getCurrentYear() { public int getCurrentYear() {
return mDate.get(Calendar.YEAR); return mDate.get(Calendar.YEAR);
} }
/** /**
* Set current year * UI
* *
* @param year The current year * @param year 2025
*/ */
public void setCurrentYear(int year) { public void setCurrentYear(int year) {
// 如果不是初始化阶段,并且新值与当前年份相同,则无需处理
if (!mInitialising && year == getCurrentYear()) { if (!mInitialising && year == getCurrentYear()) {
return; return;
} }
// 更新 Calendar 对象中的年份
mDate.set(Calendar.YEAR, year); mDate.set(Calendar.YEAR, year);
// 更新日期控件(如 NumberPicker 显示)
updateDateControl(); updateDateControl();
// 触发日期时间变化的回调事件
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* Get current month in the year *
* *
* @return The current month in the year * @return Calendar 0 11
*/ */
public int getCurrentMonth() { public int getCurrentMonth() {
return mDate.get(Calendar.MONTH); return mDate.get(Calendar.MONTH);
} }
/** /**
* Set current month in the year * UI
* *
* @param month The month in the year * @param month 0 11
*/ */
public void setCurrentMonth(int month) { public void setCurrentMonth(int month) {
// 如果不是初始化阶段,并且新值与当前月份相同,则无需处理
if (!mInitialising && month == getCurrentMonth()) { if (!mInitialising && month == getCurrentMonth()) {
return; return;
} }
// 更新 Calendar 对象中的月份
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
// 更新日期控件(如星期几等显示内容)
updateDateControl(); updateDateControl();
// 触发日期时间变化的回调事件
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* Get current day of the month *
* *
* @return The day of the month * @return Calendar 1 ~ 31
*/ */
public int getCurrentDay() { public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH); return mDate.get(Calendar.DAY_OF_MONTH);
} }
/** /**
* Set current day of the month *
* *
* @param dayOfMonth The day of the month * @param dayOfMonth 1 ~ 31
*/ */
public void setCurrentDay(int dayOfMonth) { public void setCurrentDay(int dayOfMonth) {
// 如果不是初始化阶段,并且新值与当前日期相同,则无需处理
if (!mInitialising && dayOfMonth == getCurrentDay()) { if (!mInitialising && dayOfMonth == getCurrentDay()) {
return; return;
} }
// 更新 Calendar 对象中的日期(即月中的第几天)
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// 更新日期控件(如星期几等显示内容)
updateDateControl(); updateDateControl();
// 触发日期时间变化的回调事件
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* Get current hour in 24 hour mode, in the range (0~23) * 24
* @return The current hour in 24 hour mode *
* @return Calendar 0 ~ 23
*/ */
public int getCurrentHourOfDay() { public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY); return mDate.get(Calendar.HOUR_OF_DAY);
} }
/**
* 24
*
* @return 2412 1 ~ 12
*/
private int getCurrentHour() { private int getCurrentHour() {
if (mIs24HourView){ if (mIs24HourView) {
// 如果是 24 小时视图,直接返回 0~23 的小时值
return getCurrentHourOfDay(); return getCurrentHourOfDay();
} else { } else {
int hour = getCurrentHourOfDay(); int hour = getCurrentHourOfDay();
if (hour > HOURS_IN_HALF_DAY) { if (hour > HOURS_IN_HALF_DAY) {
// 下午:将 13~23 转换为 1~11
return hour - HOURS_IN_HALF_DAY; return hour - HOURS_IN_HALF_DAY;
} else { } else {
// 上午0 转换为 12其他保持原样1~11
return hour == 0 ? HOURS_IN_HALF_DAY : hour; return hour == 0 ? HOURS_IN_HALF_DAY : hour;
} }
} }
} }
/** /**
* Set current hour in 24 hour mode, in the range (0~23) * 24 UI
* *
* @param hourOfDay * @param hourOfDay 0 ~ 23
*/ */
public void setCurrentHour(int hourOfDay) { public void setCurrentHour(int hourOfDay) {
// 如果不是初始化阶段,且新值与当前小时相同,则无需处理
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return; return;
} }
// 更新 Calendar 对象中的小时24小时制
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
// 如果是 12 小时制视图,需要处理 AM/PM 和显示值
if (!mIs24HourView) { if (!mIs24HourView) {
if (hourOfDay >= HOURS_IN_HALF_DAY) { if (hourOfDay >= HOURS_IN_HALF_DAY) {
// 下午12~23
mIsAm = false; mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) { if (hourOfDay > HOURS_IN_HALF_DAY) {
// 13~23 转换为 1~11
hourOfDay -= HOURS_IN_HALF_DAY; hourOfDay -= HOURS_IN_HALF_DAY;
} }
// else: hourOfDay == 12 → 不变
} else { } else {
// 上午0~11
mIsAm = true; mIsAm = true;
if (hourOfDay == 0) { if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY; // 0 点显示为 12 AM
hourOfDay = HOURS_IN_HALF_DAY; // 12
} }
// else: 1~11 → 不变
} }
// 更新 AM/PM 控件显示状态
updateAmPmControl(); updateAmPmControl();
} }
// 设置小时选择器的显示值NumberPicker
mHourSpinner.setValue(hourOfDay); mHourSpinner.setValue(hourOfDay);
// 触发日期时间变化回调
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* Get currentMinute *
* *
* @return The Current Minute * @return Calendar 0 ~ 59
*/ */
public int getCurrentMinute() { public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE); return mDate.get(Calendar.MINUTE);
} }
/** /**
* Set current minute *
*
* @param minute 0 ~ 59
*/ */
public void setCurrentMinute(int minute) { public void setCurrentMinute(int minute) {
// 如果不是初始化阶段,且新值与当前分钟相同,则无需处理
if (!mInitialising && minute == getCurrentMinute()) { if (!mInitialising && minute == getCurrentMinute()) {
return; return;
} }
// 更新分钟选择器 NumberPicker 的显示值
mMinuteSpinner.setValue(minute); mMinuteSpinner.setValue(minute);
// 更新 Calendar 对象中的分钟值
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
// 触发日期时间变化的回调事件
onDateTimeChanged(); onDateTimeChanged();
} }
/** /**
* @return true if this is in 24 hour view else false. * 24
*
* @return 24 true false
*/ */
public boolean is24HourView () { public boolean is24HourView () {
return mIs24HourView; return mIs24HourView;
} }
/** /**
* Set whether in 24 hour or AM/PM mode. * 使 24
* *
* @param is24HourView True for 24 hour mode. False for AM/PM mode. * @param is24HourView true 使 24 false 使 AM/PM
*/ */
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) { if (mIs24HourView == is24HourView) {
return; return; // 如果状态未变,无需处理
} }
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
// 根据模式切换 AM/PM 控件的可见性
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl(); int hour = getCurrentHourOfDay(); // 获取当前小时
setCurrentHour(hour);
updateAmPmControl(); updateHourControl(); // 更新小时选择器范围12/24
setCurrentHour(hour); // 重新设置小时以适配新视图
updateAmPmControl(); // 更新 AM/PM 显示状态
} }
/**
* MM.dd EEEE
*/
private void updateDateControl() { private void updateDateControl() {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis()); cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); // 回退几天,构建一周范围
mDateSpinner.setDisplayedValues(null);
mDateSpinner.setDisplayedValues(null); // 清空旧数据
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1); cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
} }
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); mDateSpinner.setDisplayedValues(mDateDisplayValues); // 设置新数据显示
mDateSpinner.invalidate(); mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); // 默认选中中间日期
mDateSpinner.invalidate(); // 刷新控件
} }
/**
* AM/PM
*/
private void updateAmPmControl() { private void updateAmPmControl() {
if (mIs24HourView) { if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE); mAmPmSpinner.setVisibility(View.GONE); // 24小时制隐藏 AM/PM
} else { } else {
int index = mIsAm ? Calendar.AM : Calendar.PM; int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index); mAmPmSpinner.setValue(index); // 设置当前 AM/PM 状态
mAmPmSpinner.setVisibility(View.VISIBLE); mAmPmSpinner.setVisibility(View.VISIBLE); // 显示 AM/PM 控件
} }
} }
/**
* 12/24
*/
private void updateHourControl() { private void updateHourControl() {
if (mIs24HourView) { if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); // 0
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); // 23
} else { } else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); // 1
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); // 12
} }
} }
/** /**
* Set the callback that indicates the 'Set' button has been pressed. *
* @param callback the callback, if null will do nothing *
* @param callback null
*/ */
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback; mOnDateTimeChangedListener = callback;
} }
/**
*
*/
private void onDateTimeChanged() { private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) { if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
} }
} }
} }

@ -29,62 +29,134 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat; import android.text.format.DateFormat;
import android.text.format.DateUtils; import android.text.format.DateUtils;
/**
* DateTimePicker
*
*
*
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener { public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 当前选中的日期时间
private Calendar mDate = Calendar.getInstance(); private Calendar mDate = Calendar.getInstance();
// 是否使用 24 小时制显示时间
private boolean mIs24HourView; private boolean mIs24HourView;
// 时间设置完成后的回调接口
private OnDateTimeSetListener mOnDateTimeSetListener; private OnDateTimeSetListener mOnDateTimeSetListener;
// 自定义的时间选择控件
private DateTimePicker mDateTimePicker; private DateTimePicker mDateTimePicker;
/**
*
*/
public interface OnDateTimeSetListener { public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date); void OnDateTimeSet(AlertDialog dialog, long date);
} }
/**
*
*
* @param context
* @param date
*/
public DateTimePickerDialog(Context context, long date) { public DateTimePickerDialog(Context context, long date) {
super(context); super(context);
// 创建一个 DateTimePicker 实例作为核心选择控件
mDateTimePicker = new DateTimePicker(context); mDateTimePicker = new DateTimePicker(context);
// 设置该控件为对话框的内容视图
setView(mDateTimePicker); setView(mDateTimePicker);
// 设置日期时间变化监听器,用于更新内部时间和标题
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() { mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month, public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) { int dayOfMonth, int hourOfDay, int minute) {
// 更新 Calendar 对象中的各个时间字段
mDate.set(Calendar.YEAR, year); mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month); mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute); mDate.set(Calendar.MINUTE, minute);
// 更新对话框标题以反映最新时间
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
}); });
// 设置初始时间
mDate.setTimeInMillis(date); mDate.setTimeInMillis(date);
// 秒数设为 0避免出现不必要的误差
mDate.set(Calendar.SECOND, 0); mDate.set(Calendar.SECOND, 0);
// 将当前时间同步到 DateTimePicker 控件中
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis()); mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置“确定”按钮并绑定点击事件
setButton(context.getString(R.string.datetime_dialog_ok), this); setButton(context.getString(R.string.datetime_dialog_ok), this);
// 设置“取消”按钮,不绑定点击事件
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null); setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置决定是否启用 24 小时制
set24HourView(DateFormat.is24HourFormat(this.getContext())); set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 初始化对话框标题
updateTitle(mDate.getTimeInMillis()); updateTitle(mDate.getTimeInMillis());
} }
/**
* 使 24
*
* @param is24HourView true 使 24
*/
public void set24HourView(boolean is24HourView) { public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView; mIs24HourView = is24HourView;
} }
/**
*
*
* @param callBack
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) { public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack; mOnDateTimeSetListener = callBack;
} }
/**
*
*
* @param date
*/
private void updateTitle(long date) { private void updateTitle(long date) {
int flag = int flag =
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME; DateUtils.FORMAT_SHOW_TIME;
// 根据是否为 24 小时制设置格式标志
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR; flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
// 设置对话框标题为格式化后的时间字符串
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag)); setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
} }
/**
*
*
* @param arg0
* @param arg1
*/
public void onClick(DialogInterface arg0, int arg1) { public void onClick(DialogInterface arg0, int arg1) {
// 如果设置了监听器,则调用回调方法传递最终时间
if (mOnDateTimeSetListener != null) { if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis()); mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
} }
} }
} }

@ -27,17 +27,46 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R; import net.micode.notes.R;
/**
* PopupMenu
*
*
*/
public class DropdownMenu { public class DropdownMenu {
// 下拉菜单绑定的按钮控件
private Button mButton; private Button mButton;
// Android 原生 PopupMenu 实例
private PopupMenu mPopupMenu; private PopupMenu mPopupMenu;
// 菜单对象,用于操作菜单项
private Menu mMenu; private Menu mMenu;
/**
*
*
* @param context
* @param button
* @param menuId ID R.menu.xxx
*/
public DropdownMenu(Context context, Button button, int menuId) { public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; mButton = button;
// 设置按钮背景为下拉图标
mButton.setBackgroundResource(R.drawable.dropdown_icon); mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 创建 PopupMenu 实例
mPopupMenu = new PopupMenu(context, mButton); mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单对象
mMenu = mPopupMenu.getMenu(); mMenu = mPopupMenu.getMenu();
// 使用菜单资源填充 PopupMenu
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击事件,点击时显示菜单
mButton.setOnClickListener(new OnClickListener() { mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mPopupMenu.show(); mPopupMenu.show();
@ -45,17 +74,34 @@ public class DropdownMenu {
}); });
} }
/**
*
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) { public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) { if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); mPopupMenu.setOnMenuItemClickListener(listener);
} }
} }
/**
* ID MenuItem
*
* @param id ID
* @return MenuItem
*/
public MenuItem findItem(int id) { public MenuItem findItem(int id) {
return mMenu.findItem(id); return mMenu.findItem(id);
} }
/**
*
*
* @param title
*/
public void setTitle(CharSequence title) { public void setTitle(CharSequence title) {
mButton.setText(title); mButton.setText(title);
} }
} }

@ -30,11 +30,13 @@ import net.micode.notes.data.Notes.NoteColumns;
public class FoldersListAdapter extends CursorAdapter { public class FoldersListAdapter extends CursorAdapter {
// 定义查询的列
public static final String [] PROJECTION = { public static final String [] PROJECTION = {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
}; };
// 列索引常量
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1; public static final int NAME_COLUMN = 1;
@ -45,12 +47,14 @@ public class FoldersListAdapter extends CursorAdapter {
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
// 创建新的视图
return new FolderListItem(context); return new FolderListItem(context);
} }
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) { if (view instanceof FolderListItem) {
// 获取文件夹名称,如果是根文件夹则使用特定字符串
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName); ((FolderListItem) view).bind(folderName);
@ -59,6 +63,7 @@ public class FoldersListAdapter extends CursorAdapter {
public String getFolderName(Context context, int position) { public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position); Cursor cursor = (Cursor) getItem(position);
// 获取指定位置的文件夹名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
} }
@ -68,11 +73,13 @@ public class FoldersListAdapter extends CursorAdapter {
public FolderListItem(Context context) { public FolderListItem(Context context) {
super(context); super(context);
// 加载布局并初始化控件
inflate(context, R.layout.folder_list_item, this); inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name); mName = (TextView) findViewById(R.id.tv_folder_name);
} }
public void bind(String name) { public void bind(String name) {
// 设置文件夹名称
mName.setText(name); mName.setText(name);
} }
} }

File diff suppressed because it is too large Load Diff

@ -1,17 +1,6 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * MiCode
* * Apache License, Version 2.0
* 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; package net.micode.notes.ui;
@ -37,15 +26,17 @@ import net.micode.notes.R;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
// 定义 NoteEditText 类,继承自 EditText用于笔记编辑文本框
public class NoteEditText extends EditText { public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText"; private static final String TAG = "NoteEditText"; // 日志标签
private int mIndex; private int mIndex; // 当前编辑文本的索引
private int mSelectionStartBeforeDelete; private int mSelectionStartBeforeDelete; // 删除前的光标起始位置
private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_TEL = "tel:"; // 电话 URI scheme
private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_HTTP = "http:"; // HTTP URI scheme
private static final String SCHEME_EMAIL = "mailto:" ; private static final String SCHEME_EMAIL = "mailto:"; // 邮件 URI scheme
// 定义 URI scheme 和对应操作资源 ID 的映射关系
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static { static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
@ -54,56 +45,59 @@ public class NoteEditText extends EditText {
} }
/** /**
* Call by the {@link NoteEditActivity} to delete or add edit text * NoteEditActivity
*/ */
public interface OnTextViewChangeListener { public interface OnTextViewChangeListener {
/** /**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens *
* and the text is null
*/ */
void onEditTextDelete(int index, String text); 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); void onEditTextEnter(int index, String text);
/** /**
* Hide or show item option when text change *
*/ */
void onTextChange(int index, boolean hasText); void onTextChange(int index, boolean hasText);
} }
private OnTextViewChangeListener mOnTextViewChangeListener; private OnTextViewChangeListener mOnTextViewChangeListener; // 编辑文本变化监听器
// 构造函数
public NoteEditText(Context context) { public NoteEditText(Context context) {
super(context, null); super(context, null);
mIndex = 0; mIndex = 0; // 默认索引为 0
} }
// 设置编辑文本的索引
public void setIndex(int index) { public void setIndex(int index) {
mIndex = index; mIndex = index;
} }
// 设置编辑文本变化监听器
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener; mOnTextViewChangeListener = listener;
} }
// 构造函数
public NoteEditText(Context context, AttributeSet attrs) { public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle); super(context, attrs, android.R.attr.editTextStyle);
} }
// 构造函数
public NoteEditText(Context context, AttributeSet attrs, int defStyle) { public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
} }
// 处理触摸事件,用于设置文本选择
@Override @Override
public boolean onTouchEvent(MotionEvent event) { public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_DOWN:
// 计算触摸位置相对于文本的偏移量
int x = (int) event.getX(); int x = (int) event.getX();
int y = (int) event.getY(); int y = (int) event.getY();
x -= getTotalPaddingLeft(); x -= getTotalPaddingLeft();
@ -112,75 +106,84 @@ public class NoteEditText extends EditText {
y += getScrollY(); y += getScrollY();
Layout layout = getLayout(); Layout layout = getLayout();
int line = layout.getLineForVertical(y); int line = layout.getLineForVertical(y); // 获取垂直位置对应的行号
int off = layout.getOffsetForHorizontal(line, x); int off = layout.getOffsetForHorizontal(line, x); // 获取水平位置对应的偏移量
Selection.setSelection(getText(), off); Selection.setSelection(getText(), off); // 设置文本选择
break; break;
} }
return super.onTouchEvent(event); return super.onTouchEvent(event); // 调用父类的触摸事件处理方法
} }
// 处理键盘按下事件
@Override @Override
public boolean onKeyDown(int keyCode, KeyEvent event) { public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) { switch (keyCode) {
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
// 如果设置了编辑文本变化监听器,则不允许处理回车键事件
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
return false; return false;
} }
break; break;
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
mSelectionStartBeforeDelete = getSelectionStart(); mSelectionStartBeforeDelete = getSelectionStart(); // 保存删除前的光标起始位置
break; break;
default: default:
break; break;
} }
return super.onKeyDown(keyCode, event); return super.onKeyDown(keyCode, event); // 调用父类的键盘按下事件处理方法
} }
// 处理键盘弹起事件
@Override @Override
public boolean onKeyUp(int keyCode, KeyEvent event) { public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) { switch (keyCode) {
case KeyEvent.KEYCODE_DEL: case KeyEvent.KEYCODE_DEL:
// 如果设置了编辑文本变化监听器,则处理删除事件
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
if (0 == mSelectionStartBeforeDelete && mIndex != 0) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) { // 如果光标在起始位置且不是第一个编辑文本
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); // 删除当前编辑文本
return true; return true;
} }
} else { } else {
Log.d(TAG, "OnTextViewChangeListener was not seted"); Log.d(TAG, "未设置编辑文本变化监听器");
} }
break; break;
case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_ENTER:
// 如果设置了编辑文本变化监听器,则处理回车键事件
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
int selectionStart = getSelectionStart(); int selectionStart = getSelectionStart(); // 获取光标起始位置
String text = getText().subSequence(selectionStart, length()).toString(); String text = getText().subSequence(selectionStart, length()).toString(); // 获取当前选择的文本
setText(getText().subSequence(0, selectionStart)); setText(getText().subSequence(0, selectionStart)); // 设置文本为选择位置之前的内容
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 添加新的编辑文本
} else { } else {
Log.d(TAG, "OnTextViewChangeListener was not seted"); Log.d(TAG, "未设置编辑文本变化监听器");
} }
break; break;
default: default:
break; break;
} }
return super.onKeyUp(keyCode, event); return super.onKeyUp(keyCode, event); // 调用父类的键盘弹起事件处理方法
} }
// 处理焦点变化事件
@Override @Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
// 如果设置了编辑文本变化监听器,则通知文本变化
if (mOnTextViewChangeListener != null) { if (mOnTextViewChangeListener != null) {
if (!focused && TextUtils.isEmpty(getText())) { if (!focused && TextUtils.isEmpty(getText())) { // 如果失去焦点且文本为空
mOnTextViewChangeListener.onTextChange(mIndex, false); mOnTextViewChangeListener.onTextChange(mIndex, false); // 通知文本为空
} else { } else {
mOnTextViewChangeListener.onTextChange(mIndex, true); mOnTextViewChangeListener.onTextChange(mIndex, true); // 通知文本不为空
} }
} }
super.onFocusChanged(focused, direction, previouslyFocusedRect); super.onFocusChanged(focused, direction, previouslyFocusedRect); // 调用父类的焦点变化事件处理方法
} }
// 创建上下文菜单
@Override @Override
protected void onCreateContextMenu(ContextMenu menu) { protected void onCreateContextMenu(ContextMenu menu) {
// 如果文本是 Spanned 类型,则处理 URLSpan
if (getText() instanceof Spanned) { if (getText() instanceof Spanned) {
int selStart = getSelectionStart(); int selStart = getSelectionStart();
int selEnd = getSelectionEnd(); int selEnd = getSelectionEnd();
@ -188,30 +191,31 @@ public class NoteEditText extends EditText {
int min = Math.min(selStart, selEnd); int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd); int max = Math.max(selStart, selEnd);
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); // 获取选中文本中的 URLSpan
if (urls.length == 1) { if (urls.length == 1) { // 如果只有一个 URLSpan
int defaultResId = 0; int defaultResId = 0;
for(String schema: sSchemaActionResMap.keySet()) { // 遍历 URI scheme 和操作资源 ID 的映射关系,找到对应的资源 ID
if(urls[0].getURL().indexOf(schema) >= 0) { for (String schema : sSchemaActionResMap.keySet()) {
if (urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema); defaultResId = sSchemaActionResMap.get(schema);
break; break;
} }
} }
if (defaultResId == 0) { if (defaultResId == 0) { // 如果未找到对应的资源 ID则使用默认资源 ID
defaultResId = R.string.note_link_other; defaultResId = R.string.note_link_other;
} }
// 添加菜单项并设置点击监听器
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() { new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
// goto a new intent urls[0].onClick(NoteEditText.this); // 跳转到对应链接
urls[0].onClick(NoteEditText.this);
return true; return true;
} }
}); });
} }
} }
super.onCreateContextMenu(menu); super.onCreateContextMenu(menu); // 调用父类的上下文菜单创建方法
} }
} }

@ -1,17 +1,6 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * MiCode
* * Apache License, Version 2.0
* 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; package net.micode.notes.ui;
@ -27,72 +16,78 @@ import net.micode.notes.tool.DataUtils;
public class NoteItemData { public class NoteItemData {
static final String [] PROJECTION = new String [] { // 定义查询投影,指定要查询的列
NoteColumns.ID, static final String[] PROJECTION = new String[]{
NoteColumns.ALERTED_DATE, NoteColumns.ID, // 笔记 ID
NoteColumns.BG_COLOR_ID, NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.CREATED_DATE, NoteColumns.BG_COLOR_ID, // 背景颜色 ID
NoteColumns.HAS_ATTACHMENT, NoteColumns.CREATED_DATE, // 创建日期
NoteColumns.MODIFIED_DATE, NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.NOTES_COUNT, NoteColumns.MODIFIED_DATE, // 修改日期
NoteColumns.PARENT_ID, NoteColumns.NOTES_COUNT, // 笔记数量
NoteColumns.SNIPPET, NoteColumns.PARENT_ID, // 父级 ID
NoteColumns.TYPE, NoteColumns.SNIPPET, // 摘要
NoteColumns.WIDGET_ID, NoteColumns.TYPE, // 类型
NoteColumns.WIDGET_TYPE, NoteColumns.WIDGET_ID, // 小部件 ID
NoteColumns.WIDGET_TYPE // 小部件类型
}; };
private static final int ID_COLUMN = 0; // 定义各列在查询结果中的索引
private static final int ALERTED_DATE_COLUMN = 1; private static final int ID_COLUMN = 0;
private static final int BG_COLOR_ID_COLUMN = 2; private static final int ALERTED_DATE_COLUMN = 1;
private static final int CREATED_DATE_COLUMN = 3; private static final int BG_COLOR_ID_COLUMN = 2;
private static final int HAS_ATTACHMENT_COLUMN = 4; private static final int CREATED_DATE_COLUMN = 3;
private static final int MODIFIED_DATE_COLUMN = 5; private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int NOTES_COUNT_COLUMN = 6; private static final int MODIFIED_DATE_COLUMN = 5;
private static final int PARENT_ID_COLUMN = 7; private static final int NOTES_COUNT_COLUMN = 6;
private static final int SNIPPET_COLUMN = 8; private static final int PARENT_ID_COLUMN = 7;
private static final int TYPE_COLUMN = 9; private static final int SNIPPET_COLUMN = 8;
private static final int WIDGET_ID_COLUMN = 10; private static final int TYPE_COLUMN = 9;
private static final int WIDGET_TYPE_COLUMN = 11; 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 mId; // 笔记 ID
private long mCreatedDate; private long mAlertDate; // 提醒日期
private boolean mHasAttachment; private int mBgColorId; // 背景颜色 ID
private long mModifiedDate; private long mCreatedDate; // 创建日期
private int mNotesCount; private boolean mHasAttachment; // 是否有附件
private long mParentId; private long mModifiedDate; // 修改日期
private String mSnippet; private int mNotesCount; // 笔记数量
private int mType; private long mParentId; // 父级 ID
private int mWidgetId; private String mSnippet; // 摘要
private int mWidgetType; private int mType; // 类型
private String mName; private int mWidgetId; // 小部件 ID
private String mPhoneNumber; private int mWidgetType; // 小部件类型
private String mName; // 名称
private boolean mIsLastItem; private String mPhoneNumber; // 电话号码
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem; // 定义位置相关的成员变量
private boolean mIsOneNoteFollowingFolder; private boolean mIsLastItem; // 是否是最后一个项目
private boolean mIsMultiNotesFollowingFolder; private boolean mIsFirstItem; // 是否是第一个项目
private boolean mIsOnlyOneItem; // 是否只有一个项目
private boolean mIsOneNoteFollowingFolder; // 是否有一个笔记跟随文件夹
private boolean mIsMultiNotesFollowingFolder; // 是否有多个笔记跟随文件夹
// 构造函数,用于从游标中初始化笔记数据
public NoteItemData(Context context, Cursor cursor) { public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN); mId = cursor.getLong(ID_COLUMN); // 获取笔记 ID
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN); // 获取提醒日期
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN); // 获取背景颜色 ID
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN); // 获取创建日期
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false; // 获取是否有附件
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN); // 获取修改日期
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN); // 获取笔记数量
mParentId = cursor.getLong(PARENT_ID_COLUMN); mParentId = cursor.getLong(PARENT_ID_COLUMN); // 获取父级 ID
mSnippet = cursor.getString(SNIPPET_COLUMN); mSnippet = cursor.getString(SNIPPET_COLUMN); // 获取摘要
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace( // 移除摘要中的标记标签
NoteEditActivity.TAG_UNCHECKED, ""); NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN); mType = cursor.getInt(TYPE_COLUMN); // 获取类型
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); mWidgetId = cursor.getInt(WIDGET_ID_COLUMN); // 获取小部件 ID
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN); // 获取小部件类型
mPhoneNumber = ""; mPhoneNumber = "";
// 如果是通话记录文件夹,则获取电话号码和联系人名称
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId); mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) { if (!TextUtils.isEmpty(mPhoneNumber)) {
@ -106,119 +101,143 @@ public class NoteItemData {
if (mName == null) { if (mName == null) {
mName = ""; mName = "";
} }
checkPostion(cursor); checkPostion(cursor); // 检查位置信息
} }
// 检查位置信息,确定项目在游标中的位置关系
private void checkPostion(Cursor cursor) { private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false; mIsLastItem = cursor.isLast() ? true : false; // 是否是最后一个项目
mIsFirstItem = cursor.isFirst() ? true : false; mIsFirstItem = cursor.isFirst() ? true : false; // 是否是第一个项目
mIsOnlyOneItem = (cursor.getCount() == 1); mIsOnlyOneItem = (cursor.getCount() == 1); // 是否只有一个项目
mIsMultiNotesFollowingFolder = false; mIsMultiNotesFollowingFolder = false; // 默认没有多个笔记跟随文件夹
mIsOneNoteFollowingFolder = false; mIsOneNoteFollowingFolder = false; // 默认没有一个笔记跟随文件夹
// 如果是笔记且不是第一个项目,则检查前面的项目类型
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) { if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition(); int position = cursor.getPosition();
if (cursor.moveToPrevious()) { if (cursor.moveToPrevious()) { // 移动到前一个项目
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER // 如果前一个项目是文件夹或系统类型,则判断是否有一个或多个笔记跟随文件夹
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) { if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER || cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) { if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true; mIsMultiNotesFollowingFolder = true; // 有多个笔记跟随文件夹
} else { } else {
mIsOneNoteFollowingFolder = true; mIsOneNoteFollowingFolder = true; // 有一个笔记跟随文件夹
} }
} }
if (!cursor.moveToNext()) { if (!cursor.moveToNext()) { // 尝试移回原位置
throw new IllegalStateException("cursor move to previous but can't move back"); throw new IllegalStateException("cursor move to previous but can't move back");
} }
} }
} }
} }
public boolean isOneFollowingFolder() { // 返回是否有多个笔记跟随文件夹
return mIsOneNoteFollowingFolder;
}
public boolean isMultiFollowingFolder() { public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder; return mIsMultiNotesFollowingFolder;
} }
// 返回是否有提醒
public boolean hasAlert() {
return (mAlertDate > 0);
}
// 返回是否是通话记录
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
// 返回是否是最后一个项目
public boolean isLast() { public boolean isLast() {
return mIsLastItem; return mIsLastItem;
} }
// 返回联系人名称
public String getCallName() { public String getCallName() {
return mName; return mName;
} }
// 返回是否是第一个项目
public boolean isFirst() { public boolean isFirst() {
return mIsFirstItem; return mIsFirstItem;
} }
// 返回是否只有一个项目
public boolean isSingle() { public boolean isSingle() {
return mIsOnlyOneItem; return mIsOnlyOneItem;
} }
// 返回是否有一个笔记跟随文件夹
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
// 返回笔记 ID
public long getId() { public long getId() {
return mId; return mId;
} }
// 返回提醒日期
public long getAlertDate() { public long getAlertDate() {
return mAlertDate; return mAlertDate;
} }
// 返回创建日期
public long getCreatedDate() { public long getCreatedDate() {
return mCreatedDate; return mCreatedDate;
} }
// 返回是否有附件
public boolean hasAttachment() { public boolean hasAttachment() {
return mHasAttachment; return mHasAttachment;
} }
// 返回修改日期
public long getModifiedDate() { public long getModifiedDate() {
return mModifiedDate; return mModifiedDate;
} }
// 返回背景颜色 ID
public int getBgColorId() { public int getBgColorId() {
return mBgColorId; return mBgColorId;
} }
// 返回父级 ID
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
// 返回笔记数量
public int getNotesCount() { public int getNotesCount() {
return mNotesCount; return mNotesCount;
} }
public long getFolderId () { // 返回文件夹 ID
public long getFolderId() {
return mParentId; return mParentId;
} }
// 返回类型
public int getType() { public int getType() {
return mType; return mType;
} }
// 返回小部件类型
public int getWidgetType() { public int getWidgetType() {
return mWidgetType; return mWidgetType;
} }
// 返回小部件 ID
public int getWidgetId() { public int getWidgetId() {
return mWidgetId; return mWidgetId;
} }
// 返回摘要
public String getSnippet() { public String getSnippet() {
return mSnippet; 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) { public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN); return cursor.getInt(TYPE_COLUMN);
} }
} }

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * <url id="d0s4geb67ti966oe1310" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -79,125 +79,114 @@ import java.io.InputStreamReader;
import java.util.HashSet; import java.util.HashSet;
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
// 定义查询标记
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;
private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int FOLDER_LIST_QUERY_TOKEN = 1;
// 定义菜单项 ID
private static final int MENU_FOLDER_DELETE = 0; private static final int MENU_FOLDER_DELETE = 0;
private static final int MENU_FOLDER_VIEW = 1; private static final int MENU_FOLDER_VIEW = 1;
private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final int MENU_FOLDER_CHANGE_NAME = 2;
// 定义偏好设置键
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";
// 定义列表编辑状态枚举
private enum ListEditState { private enum ListEditState {
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
}; };
// 定义当前列表编辑状态
private ListEditState mState; private ListEditState mState;
// 定义异步查询处理器
private BackgroundQueryHandler mBackgroundQueryHandler; private BackgroundQueryHandler mBackgroundQueryHandler;
// 定义笔记列表适配器
private NotesListAdapter mNotesListAdapter; private NotesListAdapter mNotesListAdapter;
// 定义笔记列表视图
private ListView mNotesListView; private ListView mNotesListView;
// 定义新建笔记按钮
private Button mAddNewNote; private Button mAddNewNote;
// 定义是否正在分发触摸事件的标志
private boolean mDispatch; private boolean mDispatch;
// 定义触摸事件的原始 Y 坐标和分发 Y 坐标
private int mOriginY; private int mOriginY;
private int mDispatchY; private int mDispatchY;
// 定义标题栏视图
private TextView mTitleBar; private TextView mTitleBar;
// 定义当前文件夹 ID
private long mCurrentFolderId; private long mCurrentFolderId;
// 定义内容解析器
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
// 定义多选模式回调
private ModeCallback mModeCallBack; private ModeCallback mModeCallBack;
// 定义日志标签
private static final String TAG = "NotesListActivity"; private static final String TAG = "NotesListActivity";
// 定义列表视图滚动速率
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;
// 定义焦点笔记数据项
private NoteItemData mFocusNoteDataItem; private NoteItemData mFocusNoteDataItem;
// 定义查询选择条件
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)";
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" // 定义请求码
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)";
private final static int REQUEST_CODE_OPEN_NODE = 102; private final static int REQUEST_CODE_OPEN_NODE = 102;
private final static int REQUEST_CODE_NEW_NODE = 103; private final static int REQUEST_CODE_NEW_NODE = 103;
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.note_list); setContentView(R.layout.note_list); // 设置布局文件为 note_list
initResources(); initResources(); // 初始化资源
/** /**
* Insert an introduction when user firstly use this application * 使
*/ */
setAppInfoFromRawRes(); setAppInfoFromRawRes(); // 从原始资源文件中读取介绍信息并创建笔记
} }
@Override @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK if (resultCode == RESULT_OK && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { mNotesListAdapter.changeCursor(null); // 更改游标以刷新列表
mNotesListAdapter.changeCursor(null);
} else { } else {
super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); // 调用父类的方法
} }
} }
private void setAppInfoFromRawRes() { private void setAppInfoFromRawRes() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); // 获取默认偏好设置
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { // 如果未添加介绍
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(); // 创建字符串构建器
InputStream in = null; InputStream in = null;
try { try {
in = getResources().openRawResource(R.raw.introduction); in = getResources().openRawResource(R.raw.introduction); // 打开原始资源文件
if (in != null) { if (in != null) {
InputStreamReader isr = new InputStreamReader(in); InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr); BufferedReader br = new BufferedReader(isr);
char [] buf = new char[1024]; char[] buf = new char[1024];
int len = 0; int len = 0;
while ((len = br.read(buf)) > 0) { while ((len = br.read(buf)) > 0) {
sb.append(buf, 0, len); sb.append(buf, 0, len); // 将读取的内容追加到字符串构建器
} }
} else { } else {
Log.e(TAG, "Read introduction file error"); Log.e(TAG, "读取介绍文件错误");
return; return;
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} finally { } finally {
if(in != null) { if (in != null) {
try { try {
in.close(); in.close(); // 关闭输入流
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }
} }
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, ResourceParser.RED); // 创建空笔记
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, note.setWorkingText(sb.toString()); // 设置笔记内容
ResourceParser.RED); if (note.saveNote()) { // 保存笔记
note.setWorkingText(sb.toString()); sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); // 更新偏好设置
if (note.saveNote()) {
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
} else { } else {
Log.e(TAG, "Save introduction note error"); Log.e(TAG, "保存介绍笔记错误");
return; return;
} }
} }
@ -206,29 +195,28 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
startAsyncNotesListQuery(); startAsyncNotesListQuery(); // 开始异步查询笔记列表
} }
private void initResources() { private void initResources() {
mContentResolver = this.getContentResolver(); mContentResolver = this.getContentResolver(); // 获取内容解析器
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); // 创建异步查询处理器
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER; // 设置当前文件夹 ID 为根文件夹
mNotesListView = (ListView) findViewById(R.id.notes_list); mNotesListView = (ListView) findViewById(R.id.notes_list); // 获取笔记列表视图
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), null, false); // 添加页脚视图
null, false); mNotesListView.setOnItemClickListener(new OnListItemClickListener()); // 设置项点击监听器
mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemLongClickListener(this); // 设置项长按监听器
mNotesListView.setOnItemLongClickListener(this); mNotesListAdapter = new NotesListAdapter(this); // 创建笔记列表适配器
mNotesListAdapter = new NotesListAdapter(this); mNotesListView.setAdapter(mNotesListAdapter); // 设置适配器
mNotesListView.setAdapter(mNotesListAdapter); mAddNewNote = (Button) findViewById(R.id.btn_new_note); // 获取新建笔记按钮
mAddNewNote = (Button) findViewById(R.id.btn_new_note); mAddNewNote.setOnClickListener(this); // 设置点击监听器
mAddNewNote.setOnClickListener(this); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); // 设置触摸监听器
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
mDispatch = false; mDispatch = false;
mDispatchY = 0; mDispatchY = 0;
mOriginY = 0; mOriginY = 0;
mTitleBar = (TextView) findViewById(R.id.tv_title_bar); mTitleBar = (TextView) findViewById(R.id.tv_title_bar); // 获取标题栏视图
mState = ListEditState.NOTE_LIST; mState = ListEditState.NOTE_LIST; // 设置列表编辑状态为笔记列表
mModeCallBack = new ModeCallback(); mModeCallBack = new ModeCallback(); // 创建多选模式回调
} }
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
@ -237,85 +225,76 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private MenuItem mMoveMenu; private MenuItem mMoveMenu;
public boolean onCreateActionMode(ActionMode mode, Menu menu) { public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.note_list_options, menu); getMenuInflater().inflate(R.menu.note_list_options, menu); // 加载菜单资源
menu.findItem(R.id.delete).setOnMenuItemClickListener(this); menu.findItem(R.id.delete).setOnMenuItemClickListener(this); // 设置菜单项点击监听器
mMoveMenu = menu.findItem(R.id.move); mMoveMenu = menu.findItem(R.id.move);
if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER || DataUtils.getUserFolderCount(mContentResolver) == 0) {
|| DataUtils.getUserFolderCount(mContentResolver) == 0) { mMoveMenu.setVisible(false); // 如果是通话记录文件夹或没有用户文件夹,则隐藏移动菜单项
mMoveMenu.setVisible(false);
} else { } else {
mMoveMenu.setVisible(true); mMoveMenu.setVisible(true);
mMoveMenu.setOnMenuItemClickListener(this); mMoveMenu.setOnMenuItemClickListener(this); // 设置菜单项点击监听器
} }
mActionMode = mode; mActionMode = mode;
mNotesListAdapter.setChoiceMode(true); mNotesListAdapter.setChoiceMode(true); // 设置适配器为选择模式
mNotesListView.setLongClickable(false); mNotesListView.setLongClickable(false); // 禁用长按事件
mAddNewNote.setVisibility(View.GONE); mAddNewNote.setVisibility(View.GONE); // 隐藏新建笔记按钮
View customView = LayoutInflater.from(NotesListActivity.this).inflate( View customView = LayoutInflater.from(NotesListActivity.this).inflate(R.layout.note_list_dropdown_menu, null); // 加载自定义视图
R.layout.note_list_dropdown_menu, null); mode.setCustomView(customView); // 设置自定义视图
mode.setCustomView(customView); mDropDownMenu = new DropdownMenu(NotesListActivity.this, (Button) customView.findViewById(R.id.selection_menu), R.menu.note_list_dropdown); // 创建下拉菜单
mDropDownMenu = new DropdownMenu(NotesListActivity.this, mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
(Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown);
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); // 选择或取消选择所有项
updateMenu(); updateMenu(); // 更新菜单
return true; return true;
} }
}); });
return true; return true;
} }
private void updateMenu() { private void updateMenu() {
int selectedCount = mNotesListAdapter.getSelectedCount(); int selectedCount = mNotesListAdapter.getSelectedCount(); // 获取已选择的项数
// Update dropdown menu // 更新下拉菜单
String format = getResources().getString(R.string.menu_select_title, selectedCount); String format = getResources().getString(R.string.menu_select_title, selectedCount);
mDropDownMenu.setTitle(format); mDropDownMenu.setTitle(format);
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
if (item != null) { if (item != null) {
if (mNotesListAdapter.isAllSelected()) { if (mNotesListAdapter.isAllSelected()) {
item.setChecked(true); item.setChecked(true);
item.setTitle(R.string.menu_deselect_all); item.setTitle(R.string.menu_deselect_all); // 设置为取消选择全部
} else { } else {
item.setChecked(false); item.setChecked(false);
item.setTitle(R.string.menu_select_all); item.setTitle(R.string.menu_select_all); // 设置为选择全部
} }
} }
} }
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false; return false;
} }
public boolean onActionItemClicked(ActionMode mode, MenuItem item) { public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
return false; return false;
} }
public void onDestroyActionMode(ActionMode mode) { public void onDestroyActionMode(ActionMode mode) {
mNotesListAdapter.setChoiceMode(false); mNotesListAdapter.setChoiceMode(false); // 退出选择模式
mNotesListView.setLongClickable(true); mNotesListView.setLongClickable(true); // 恢复长按事件
mAddNewNote.setVisibility(View.VISIBLE); mAddNewNote.setVisibility(View.VISIBLE); // 显示新建笔记按钮
} }
public void finishActionMode() { public void finishActionMode() {
mActionMode.finish(); mActionMode.finish(); // 结束多选模式
} }
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
boolean checked) { mNotesListAdapter.setCheckedItem(position, checked); // 设置选中状态
mNotesListAdapter.setCheckedItem(position, checked); updateMenu(); // 更新菜单
updateMenu();
} }
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
if (mNotesListAdapter.getSelectedCount() == 0) { if (mNotesListAdapter.getSelectedCount() == 0) {
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), Toast.LENGTH_SHORT).show(); // 显示未选择任何项的提示
Toast.LENGTH_SHORT).show();
return true; return true;
} }
@ -324,20 +303,17 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_notes, builder.setMessage(getString(R.string.alert_message_delete_notes, mNotesListAdapter.getSelectedCount())); // 设置删除确认对话框
mNotesListAdapter.getSelectedCount())); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
builder.setPositiveButton(android.R.string.ok, public void onClick(DialogInterface dialog, int which) {
new DialogInterface.OnClickListener() { batchDelete(); // 批量删除
public void onClick(DialogInterface dialog, }
int which) { });
batchDelete();
}
});
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();
break; break;
case R.id.move: case R.id.move:
startQueryDestinationFolders(); startQueryDestinationFolders(); // 开始查询目标文件夹
break; break;
default: default:
return false; return false;
@ -347,36 +323,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
private class NewNoteOnTouchListener implements OnTouchListener { private class NewNoteOnTouchListener implements OnTouchListener {
public boolean onTouch(View v, MotionEvent event) { public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) { switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: { case MotionEvent.ACTION_DOWN:
Display display = getWindowManager().getDefaultDisplay(); Display display = getWindowManager().getDefaultDisplay();
int screenHeight = display.getHeight(); int screenHeight = display.getHeight();
int newNoteViewHeight = mAddNewNote.getHeight(); int newNoteViewHeight = mAddNewNote.getHeight();
int start = screenHeight - newNoteViewHeight; int start = screenHeight - newNoteViewHeight;
int eventY = start + (int) event.getY(); int eventY = start + (int) event.getY();
/**
* Minus TitleBar's height
*/
if (mState == ListEditState.SUB_FOLDER) { if (mState == ListEditState.SUB_FOLDER) {
eventY -= mTitleBar.getHeight(); eventY -= mTitleBar.getHeight();
start -= mTitleBar.getHeight(); start -= mTitleBar.getHeight();
} }
/**
* HACKME:When click the transparent part of "New Note" button, dispatch
* the event to the list view behind this button. The transparent part of
* "New Note" button could be expressed by formula y=-0.12x+94Unit:pixel
* and the line top of the button. The coordinate based on left of the "New
* Note" button. The 94 represents maximum height of the transparent part.
* Notice that, if the background of the button changes, the formula should
* also change. This is very bad, just for the UI designer's strong requirement.
*/
if (event.getY() < (event.getX() * (-0.12) + 94)) { if (event.getY() < (event.getX() * (-0.12) + 94)) {
View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 - mNotesListView.getFooterViewsCount());
- mNotesListView.getFooterViewsCount()); if (view != null && view.getBottom() > start && (view.getTop() < (start + 94))) {
if (view != null && view.getBottom() > start
&& (view.getTop() < (start + 94))) {
mOriginY = (int) event.getY(); mOriginY = (int) event.getY();
mDispatchY = eventY; mDispatchY = eventY;
event.setLocation(event.getX(), mDispatchY); event.setLocation(event.getX(), mDispatchY);
@ -385,36 +346,28 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
} }
break; break;
} case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_MOVE: {
if (mDispatch) { if (mDispatch) {
mDispatchY += (int) event.getY() - mOriginY; mDispatchY += (int) event.getY() - mOriginY;
event.setLocation(event.getX(), mDispatchY); event.setLocation(event.getX(), mDispatchY);
return mNotesListView.dispatchTouchEvent(event); return mNotesListView.dispatchTouchEvent(event);
} }
break; break;
} default:
default: {
if (mDispatch) { if (mDispatch) {
event.setLocation(event.getX(), mDispatchY); event.setLocation(event.getX(), mDispatchY);
mDispatch = false; mDispatch = false;
return mNotesListView.dispatchTouchEvent(event); return mNotesListView.dispatchTouchEvent(event);
} }
break; break;
}
} }
return false; return false;
} }
}
};
private void startAsyncNotesListQuery() { private void startAsyncNotesListQuery() {
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION : NORMAL_SELECTION;
: NORMAL_SELECTION; mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { String.valueOf(mCurrentFolderId) }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
} }
private final class BackgroundQueryHandler extends AsyncQueryHandler { private final class BackgroundQueryHandler extends AsyncQueryHandler {
@ -426,13 +379,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
protected void onQueryComplete(int token, Object cookie, Cursor cursor) { protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
switch (token) { switch (token) {
case FOLDER_NOTE_LIST_QUERY_TOKEN: case FOLDER_NOTE_LIST_QUERY_TOKEN:
mNotesListAdapter.changeCursor(cursor); mNotesListAdapter.changeCursor(cursor); // 更改游标以更新列表
break; break;
case FOLDER_LIST_QUERY_TOKEN: case FOLDER_LIST_QUERY_TOKEN:
if (cursor != null && cursor.getCount() > 0) { if (cursor != null && cursor.getCount() > 0) {
showFolderListMenu(cursor); showFolderListMenu(cursor); // 显示文件夹列表菜单
} else { } else {
Log.e(TAG, "Query folder failed"); Log.e(TAG, "查询文件夹失败");
} }
break; break;
default: default:
@ -446,17 +399,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
builder.setTitle(R.string.menu_title_select_folder); builder.setTitle(R.string.menu_title_select_folder);
final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
builder.setAdapter(adapter, new DialogInterface.OnClickListener() { builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
DataUtils.batchMoveToFolder(mContentResolver, DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); // 批量移动到文件夹
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); Toast.makeText(NotesListActivity.this, getString(R.string.format_move_notes_to_folder, mNotesListAdapter.getSelectedCount(), adapter.getFolderName(NotesListActivity.this, which)), Toast.LENGTH_SHORT).show(); // 显示移动成功的提示
Toast.makeText( mModeCallBack.finishActionMode(); // 结束多选模式
NotesListActivity.this,
getString(R.string.format_move_notes_to_folder,
mNotesListAdapter.getSelectedCount(),
adapter.getFolderName(NotesListActivity.this, which)),
Toast.LENGTH_SHORT).show();
mModeCallBack.finishActionMode();
} }
}); });
builder.show(); builder.show();
@ -466,26 +412,21 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); // 启动新建笔记活动
} }
private void batchDelete() { private void batchDelete() {
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); // 获取选中的小部件属性
if (!isSyncMode()) { if (!isSyncMode()) {
// if not synced, delete notes directly if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter.getSelectedItemIds())) { // 批量删除笔记
if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
.getSelectedItemIds())) {
} else { } else {
Log.e(TAG, "Delete notes error, should not happens"); Log.e(TAG, "删除笔记错误,不应该发生");
} }
} else { } else {
// in sync mode, we'll move the deleted note into the trash if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter.getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { // 批量移动到回收站文件夹
// folder Log.e(TAG, "移动笔记到回收站文件夹错误,不应该发生");
if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
.getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
Log.e(TAG, "Move notes to trash folder error, should not happens");
} }
} }
return widgets; return widgets;
@ -495,39 +436,34 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) { protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {
if (widgets != null) { if (widgets != null) {
for (AppWidgetAttribute widget : widgets) { for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { updateWidget(widget.widgetId, widget.widgetType); // 更新小部件
updateWidget(widget.widgetId, widget.widgetType);
} }
} }
} }
mModeCallBack.finishActionMode(); mModeCallBack.finishActionMode(); // 结束多选模式
} }
}.execute(); }.execute();
} }
private void deleteFolder(long folderId) { private void deleteFolder(long folderId) {
if (folderId == Notes.ID_ROOT_FOLDER) { if (folderId == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Wrong folder id, should not happen " + folderId); Log.e(TAG, "错误的文件夹 ID不应该发生 " + folderId);
return; return;
} }
HashSet<Long> ids = new HashSet<Long>(); HashSet<Long> ids = new HashSet<Long>();
ids.add(folderId); ids.add(folderId);
HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver, HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver, folderId);
folderId);
if (!isSyncMode()) { if (!isSyncMode()) {
// if not synced, delete folder directly DataUtils.batchDeleteNotes(mContentResolver, ids); // 批量删除笔记
DataUtils.batchDeleteNotes(mContentResolver, ids);
} else { } else {
// in sync mode, we'll move the deleted folder into the trash folder DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); // 批量移动到回收站文件夹
DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
} }
if (widgets != null) { if (widgets != null) {
for (AppWidgetAttribute widget : widgets) { for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { updateWidget(widget.widgetId, widget.widgetType); // 更新小部件
updateWidget(widget.widgetId, widget.widgetType);
} }
} }
} }
@ -537,30 +473,30 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
Intent intent = new Intent(this, NoteEditActivity.class); Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, data.getId()); intent.putExtra(Intent.EXTRA_UID, data.getId());
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); // 启动查看笔记活动
} }
private void openFolder(NoteItemData data) { private void openFolder(NoteItemData data) {
mCurrentFolderId = data.getId(); mCurrentFolderId = data.getId();
startAsyncNotesListQuery(); startAsyncNotesListQuery(); // 开始异步查询笔记列表
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mState = ListEditState.CALL_RECORD_FOLDER; mState = ListEditState.CALL_RECORD_FOLDER;
mAddNewNote.setVisibility(View.GONE); mAddNewNote.setVisibility(View.GONE); // 隐藏新建笔记按钮
} else { } else {
mState = ListEditState.SUB_FOLDER; mState = ListEditState.SUB_FOLDER;
} }
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mTitleBar.setText(R.string.call_record_folder_name); mTitleBar.setText(R.string.call_record_folder_name); // 设置标题栏文本为通话记录文件夹名称
} else { } else {
mTitleBar.setText(data.getSnippet()); mTitleBar.setText(data.getSnippet()); // 设置标题栏文本为文件夹名称
} }
mTitleBar.setVisibility(View.VISIBLE); mTitleBar.setVisibility(View.VISIBLE); // 显示标题栏
} }
public void onClick(View v) { public void onClick(View v) {
switch (v.getId()) { switch (v.getId()) {
case R.id.btn_new_note: case R.id.btn_new_note:
createNewNote(); createNewNote(); // 创建新笔记
break; break;
default: default:
break; break;
@ -570,13 +506,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private void showSoftInput() { private void showSoftInput() {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) { if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); // 显示软键盘
} }
} }
private void hideSoftInput(View view) { private void hideSoftInput(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); // 隐藏软键盘
} }
private void showCreateOrModifyFolderDialog(final boolean create) { private void showCreateOrModifyFolderDialog(final boolean create) {
@ -586,15 +522,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
showSoftInput(); showSoftInput();
if (!create) { if (!create) {
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
etName.setText(mFocusNoteDataItem.getSnippet()); etName.setText(mFocusNoteDataItem.getSnippet()); // 设置文件夹名称
builder.setTitle(getString(R.string.menu_folder_change_name)); builder.setTitle(getString(R.string.menu_folder_change_name)); // 设置对话框标题为更改文件夹名称
} else { } else {
Log.e(TAG, "The long click data item is null"); Log.e(TAG, "长按的数据项为空");
return; return;
} }
} else { } else {
etName.setText(""); etName.setText("");
builder.setTitle(this.getString(R.string.menu_create_folder)); builder.setTitle(this.getString(R.string.menu_create_folder)); // 设置对话框标题为创建文件夹
} }
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
@ -605,14 +541,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
}); });
final Dialog dialog = builder.setView(view).show(); final Dialog dialog = builder.setView(view).show();
final Button positive = (Button)dialog.findViewById(android.R.id.button1); final Button positive = (Button) dialog.findViewById(android.R.id.button1);
positive.setOnClickListener(new OnClickListener() { positive.setOnClickListener(new OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
hideSoftInput(etName); hideSoftInput(etName);
String name = etName.getText().toString(); String name = etName.getText().toString();
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.LENGTH_LONG).show(); // 显示文件夹已存在的提示
Toast.LENGTH_LONG).show();
etName.setSelection(0, etName.length()); etName.setSelection(0, etName.length());
return; return;
} }
@ -622,16 +557,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + "=?", new String[] { String.valueOf(mFocusNoteDataItem.getId()) }); // 更新文件夹名称
+ "=?", new String[] {
String.valueOf(mFocusNoteDataItem.getId())
});
} }
} else if (!TextUtils.isEmpty(name)) { } else if (!TextUtils.isEmpty(name)) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.SNIPPET, name);
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); // 插入新文件夹
} }
dialog.dismiss(); dialog.dismiss();
} }
@ -640,13 +572,8 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
if (TextUtils.isEmpty(etName.getText())) { if (TextUtils.isEmpty(etName.getText())) {
positive.setEnabled(false); positive.setEnabled(false);
} }
/**
* When the name edit text is null, disable the positive button
*/
etName.addTextChangedListener(new TextWatcher() { etName.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
} }
public void onTextChanged(CharSequence s, int start, int before, int count) { public void onTextChanged(CharSequence s, int start, int before, int count) {
@ -658,8 +585,6 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
public void afterTextChanged(Editable s) { public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
} }
}); });
} }
@ -670,18 +595,18 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
case SUB_FOLDER: case SUB_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST; mState = ListEditState.NOTE_LIST;
startAsyncNotesListQuery(); startAsyncNotesListQuery(); // 返回根文件夹
mTitleBar.setVisibility(View.GONE); mTitleBar.setVisibility(View.GONE); // 隐藏标题栏
break; break;
case CALL_RECORD_FOLDER: case CALL_RECORD_FOLDER:
mCurrentFolderId = Notes.ID_ROOT_FOLDER; mCurrentFolderId = Notes.ID_ROOT_FOLDER;
mState = ListEditState.NOTE_LIST; mState = ListEditState.NOTE_LIST;
mAddNewNote.setVisibility(View.VISIBLE); mAddNewNote.setVisibility(View.VISIBLE); // 显示新建笔记按钮
mTitleBar.setVisibility(View.GONE); mTitleBar.setVisibility(View.GONE); // 隐藏标题栏
startAsyncNotesListQuery(); startAsyncNotesListQuery(); // 返回根文件夹
break; break;
case NOTE_LIST: case NOTE_LIST:
super.onBackPressed(); super.onBackPressed(); // 调用父类的返回键处理方法
break; break;
default: default:
break; break;
@ -695,13 +620,11 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} else if (appWidgetType == Notes.TYPE_WIDGET_4X) { } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
intent.setClass(this, NoteWidgetProvider_4x.class); intent.setClass(this, NoteWidgetProvider_4x.class);
} else { } else {
Log.e(TAG, "Unspported widget type"); Log.e(TAG, "不支持的小部件类型");
return; return;
} }
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });
appWidgetId
});
sendBroadcast(intent); sendBroadcast(intent);
setResult(RESULT_OK, intent); setResult(RESULT_OK, intent);
@ -710,10 +633,10 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (mFocusNoteDataItem != null) { if (mFocusNoteDataItem != null) {
menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); // 设置上下文菜单标题为文件夹名称
menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); // 添加查看文件夹菜单项
menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); // 添加删除文件夹菜单项
menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); // 添加更改文件夹名称菜单项
} }
} }
}; };
@ -721,7 +644,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
public void onContextMenuClosed(Menu menu) { public void onContextMenuClosed(Menu menu) {
if (mNotesListView != null) { if (mNotesListView != null) {
mNotesListView.setOnCreateContextMenuListener(null); mNotesListView.setOnCreateContextMenuListener(null); // 移除上下文菜单创建监听器
} }
super.onContextMenuClosed(menu); super.onContextMenuClosed(menu);
} }
@ -729,29 +652,28 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
public boolean onContextItemSelected(MenuItem item) { public boolean onContextItemSelected(MenuItem item) {
if (mFocusNoteDataItem == null) { if (mFocusNoteDataItem == null) {
Log.e(TAG, "The long click data item is null"); Log.e(TAG, "长按的数据项为空");
return false; return false;
} }
switch (item.getItemId()) { switch (item.getItemId()) {
case MENU_FOLDER_VIEW: case MENU_FOLDER_VIEW:
openFolder(mFocusNoteDataItem); openFolder(mFocusNoteDataItem); // 打开文件夹
break; break;
case MENU_FOLDER_DELETE: case MENU_FOLDER_DELETE:
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.alert_title_delete)); builder.setTitle(getString(R.string.alert_title_delete));
builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setMessage(getString(R.string.alert_message_delete_folder)); // 设置删除文件夹确认对话框
builder.setPositiveButton(android.R.string.ok, builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) {
public void onClick(DialogInterface dialog, int which) { deleteFolder(mFocusNoteDataItem.getId()); // 删除文件夹
deleteFolder(mFocusNoteDataItem.getId()); }
} });
});
builder.setNegativeButton(android.R.string.cancel, null); builder.setNegativeButton(android.R.string.cancel, null);
builder.show(); builder.show();
break; break;
case MENU_FOLDER_CHANGE_NAME: case MENU_FOLDER_CHANGE_NAME:
showCreateOrModifyFolderDialog(false); showCreateOrModifyFolderDialog(false); // 显示创建或修改文件夹对话框
break; break;
default: default:
break; break;
@ -765,15 +687,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
menu.clear(); menu.clear();
if (mState == ListEditState.NOTE_LIST) { if (mState == ListEditState.NOTE_LIST) {
getMenuInflater().inflate(R.menu.note_list, menu); getMenuInflater().inflate(R.menu.note_list, menu);
// set sync or sync_cancel menu.findItem(R.id.menu_sync).setTitle(GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); // 设置同步菜单项标题
menu.findItem(R.id.menu_sync).setTitle(
GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
} else if (mState == ListEditState.SUB_FOLDER) { } else if (mState == ListEditState.SUB_FOLDER) {
getMenuInflater().inflate(R.menu.sub_folder, menu); getMenuInflater().inflate(R.menu.sub_folder, menu);
} else if (mState == ListEditState.CALL_RECORD_FOLDER) { } else if (mState == ListEditState.CALL_RECORD_FOLDER) {
getMenuInflater().inflate(R.menu.call_record_folder, menu); getMenuInflater().inflate(R.menu.call_record_folder, menu);
} else { } else {
Log.e(TAG, "Wrong state:" + mState); Log.e(TAG, "错误的状态:" + mState);
} }
return true; return true;
} }
@ -781,34 +701,29 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.menu_new_folder: { case R.id.menu_new_folder:
showCreateOrModifyFolderDialog(true); showCreateOrModifyFolderDialog(true); // 显示创建文件夹对话框
break; break;
} case R.id.menu_export_text:
case R.id.menu_export_text: { exportNoteToText(); // 导出笔记为文本文件
exportNoteToText();
break; break;
} case R.id.menu_sync:
case R.id.menu_sync: {
if (isSyncMode()) { if (isSyncMode()) {
if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
GTaskSyncService.startSync(this); GTaskSyncService.startSync(this); // 开始同步
} else { } else {
GTaskSyncService.cancelSync(this); GTaskSyncService.cancelSync(this); // 取消同步
} }
} else { } else {
startPreferenceActivity(); startPreferenceActivity(); // 启动偏好设置活动
} }
break; break;
} case R.id.menu_setting:
case R.id.menu_setting: { startPreferenceActivity(); // 启动偏好设置活动
startPreferenceActivity();
break; break;
} case R.id.menu_new_note:
case R.id.menu_new_note: { createNewNote(); // 创建新笔记
createNewNote();
break; break;
}
case R.id.menu_search: case R.id.menu_search:
onSearchRequested(); onSearchRequested();
break; break;
@ -820,7 +735,7 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
public boolean onSearchRequested() { public boolean onSearchRequested() {
startSearch(null, false, null /* appData */, false); startSearch(null, false, null, false);
return true; return true;
} }
@ -830,34 +745,27 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
return backup.exportToText(); return backup.exportToText(); // 导出笔记为文本文件
} }
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this.getString(R.string.failed_sdcard_export));
.getString(R.string.failed_sdcard_export)); builder.setMessage(NotesListActivity.this.getString(R.string.error_sdcard_unmounted));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_unmounted));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SUCCESS) { } else if (result == BackupUtils.STATE_SUCCESS) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this.getString(R.string.success_sdcard_export));
.getString(R.string.success_sdcard_export)); builder.setMessage(NotesListActivity.this.getString(R.string.format_exported_file_location, backup.getExportedTextFileName(), backup.getExportedTextFileDir()));
builder.setMessage(NotesListActivity.this.getString(
R.string.format_exported_file_location, backup
.getExportedTextFileName(), backup.getExportedTextFileDir()));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} else if (result == BackupUtils.STATE_SYSTEM_ERROR) { } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this builder.setTitle(NotesListActivity.this.getString(R.string.failed_sdcard_export));
.getString(R.string.failed_sdcard_export)); builder.setMessage(NotesListActivity.this.getString(R.string.error_sdcard_export));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_export));
builder.setPositiveButton(android.R.string.ok, null); builder.setPositiveButton(android.R.string.ok, null);
builder.show(); builder.show();
} }
@ -867,13 +775,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
} }
private boolean isSyncMode() { private boolean isSyncMode() {
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; // 判断是否为同步模式
} }
private void startPreferenceActivity() { private void startPreferenceActivity() {
Activity from = getParent() != null ? getParent() : this; Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, NotesPreferenceActivity.class); Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1); from.startActivityIfNeeded(intent, -1); // 启动偏好设置活动
} }
private class OnListItemClickListener implements OnItemClickListener { private class OnListItemClickListener implements OnItemClickListener {
@ -884,29 +792,27 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
if (mNotesListAdapter.isInChoiceMode()) { if (mNotesListAdapter.isInChoiceMode()) {
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
position = position - mNotesListView.getHeaderViewsCount(); position = position - mNotesListView.getHeaderViewsCount();
mModeCallBack.onItemCheckedStateChanged(null, position, id, mModeCallBack.onItemCheckedStateChanged(null, position, id, !mNotesListAdapter.isSelectedItem(position)); // 切换选中状态
!mNotesListAdapter.isSelectedItem(position));
} }
return; return;
} }
switch (mState) { switch (mState) {
case NOTE_LIST: case NOTE_LIST:
if (item.getType() == Notes.TYPE_FOLDER if (item.getType() == Notes.TYPE_FOLDER || item.getType() == Notes.TYPE_SYSTEM) {
|| item.getType() == Notes.TYPE_SYSTEM) { openFolder(item); // 打开文件夹
openFolder(item);
} else if (item.getType() == Notes.TYPE_NOTE) { } else if (item.getType() == Notes.TYPE_NOTE) {
openNode(item); openNode(item); // 打开笔记
} else { } else {
Log.e(TAG, "Wrong note type in NOTE_LIST"); Log.e(TAG, "笔记列表中的错误笔记类型");
} }
break; break;
case SUB_FOLDER: case SUB_FOLDER:
case CALL_RECORD_FOLDER: case CALL_RECORD_FOLDER:
if (item.getType() == Notes.TYPE_NOTE) { if (item.getType() == Notes.TYPE_NOTE) {
openNode(item); openNode(item); // 打开笔记
} else { } else {
Log.e(TAG, "Wrong note type in SUB_FOLDER"); Log.e(TAG, "子文件夹中的错误笔记类型");
} }
break; break;
default: default:
@ -919,20 +825,8 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
private void startQueryDestinationFolders() { private void startQueryDestinationFolders() {
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
selection = (mState == ListEditState.NOTE_LIST) ? selection: selection = (mState == ListEditState.NOTE_LIST) ? selection : "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
"(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, FoldersListAdapter.PROJECTION, selection, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER), String.valueOf(mCurrentFolderId) }, NoteColumns.MODIFIED_DATE + " DESC");
mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
null,
Notes.CONTENT_NOTE_URI,
FoldersListAdapter.PROJECTION,
selection,
new String[] {
String.valueOf(Notes.TYPE_FOLDER),
String.valueOf(Notes.ID_TRASH_FOLER),
String.valueOf(mCurrentFolderId)
},
NoteColumns.MODIFIED_DATE + " DESC");
} }
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
@ -940,15 +834,15 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
mFocusNoteDataItem = ((NotesListItem) view).getItemData(); mFocusNoteDataItem = ((NotesListItem) view).getItemData();
if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {
if (mNotesListView.startActionMode(mModeCallBack) != null) { if (mNotesListView.startActionMode(mModeCallBack) != null) {
mModeCallBack.onItemCheckedStateChanged(null, position, id, true); mModeCallBack.onItemCheckedStateChanged(null, position, id, true); // 进入多选模式并选中当前项
mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); // 执行触觉反馈
} else { } else {
Log.e(TAG, "startActionMode fails"); Log.e(TAG, "进入多选模式失败");
} }
} else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); // 设置上下文菜单创建监听器
} }
} }
return false; return false;
} }
} }

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * <url id="d0s4mbuf5ku6itl3bdkg" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -38,11 +38,13 @@ public class NotesListAdapter extends CursorAdapter {
private int mNotesCount; private int mNotesCount;
private boolean mChoiceMode; private boolean mChoiceMode;
// 定义应用小部件属性类
public static class AppWidgetAttribute { public static class AppWidgetAttribute {
public int widgetId; public int widgetId;
public int widgetType; public int widgetType;
}; };
// 构造函数
public NotesListAdapter(Context context) { public NotesListAdapter(Context context) {
super(context, null); super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>(); mSelectedIndex = new HashMap<Integer, Boolean>();
@ -52,43 +54,47 @@ public class NotesListAdapter extends CursorAdapter {
@Override @Override
public View newView(Context context, Cursor cursor, ViewGroup parent) { public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context); return new NotesListItem(context); // 创建新的笔记列表项视图
} }
@Override @Override
public void bindView(View view, Context context, Cursor cursor) { public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) { if (view instanceof NotesListItem) {
NoteItemData itemData = new NoteItemData(context, cursor); NoteItemData itemData = new NoteItemData(context, cursor); // 创建笔记项数据
((NotesListItem) view).bind(context, itemData, mChoiceMode, ((NotesListItem) view).bind(context, itemData, mChoiceMode, isSelectedItem(cursor.getPosition())); // 绑定数据到视图
isSelectedItem(cursor.getPosition()));
} }
} }
// 设置选中项
public void setCheckedItem(final int position, final boolean checked) { public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked); mSelectedIndex.put(position, checked); // 更新选中状态
notifyDataSetChanged(); notifyDataSetChanged(); // 通知数据已更改
} }
// 判断是否处于选择模式
public boolean isInChoiceMode() { public boolean isInChoiceMode() {
return mChoiceMode; return mChoiceMode;
} }
// 设置选择模式
public void setChoiceMode(boolean mode) { public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); mSelectedIndex.clear(); // 清除选中状态
mChoiceMode = mode; mChoiceMode = mode;
} }
// 选择所有项
public void selectAll(boolean checked) { public void selectAll(boolean checked) {
Cursor cursor = getCursor(); Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) { if (cursor.moveToPosition(i)) {
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) { // 如果是笔记类型
setCheckedItem(i, checked); setCheckedItem(i, checked); // 设置选中状态
} }
} }
} }
} }
// 获取选中的项 ID 集合
public HashSet<Long> getSelectedItemIds() { public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>(); HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
@ -97,7 +103,7 @@ public class NotesListAdapter extends CursorAdapter {
if (id == Notes.ID_ROOT_FOLDER) { if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen"); Log.d(TAG, "Wrong item id, should not happen");
} else { } else {
itemSet.add(id); itemSet.add(id); // 添加选中的项 ID
} }
} }
} }
@ -105,6 +111,7 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
// 获取选中的小部件属性集合
public HashSet<AppWidgetAttribute> getSelectedWidget() { public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>(); HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) { for (Integer position : mSelectedIndex.keySet()) {
@ -113,12 +120,9 @@ public class NotesListAdapter extends CursorAdapter {
if (c != null) { if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute(); AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c); NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId(); widget.widgetId = item.getWidgetId(); // 获取小部件 ID
widget.widgetType = item.getWidgetType(); widget.widgetType = item.getWidgetType(); // 获取小部件类型
itemSet.add(widget); itemSet.add(widget); // 添加小部件属性
/**
* Don't close cursor here, only the adapter could close it
*/
} else { } else {
Log.e(TAG, "Invalid cursor"); Log.e(TAG, "Invalid cursor");
return null; return null;
@ -128,6 +132,7 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet; return itemSet;
} }
// 获取选中的项数
public int getSelectedCount() { public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values(); Collection<Boolean> values = mSelectedIndex.values();
if (null == values) { if (null == values) {
@ -143,11 +148,13 @@ public class NotesListAdapter extends CursorAdapter {
return count; return count;
} }
// 判断是否全部选中
public boolean isAllSelected() { public boolean isAllSelected() {
int checkedCount = getSelectedCount(); int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount); return (checkedCount != 0 && checkedCount == mNotesCount); // 如果选中数等于笔记数,则全部选中
} }
// 判断项是否被选中
public boolean isSelectedItem(final int position) { public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) { if (null == mSelectedIndex.get(position)) {
return false; return false;
@ -158,21 +165,22 @@ public class NotesListAdapter extends CursorAdapter {
@Override @Override
protected void onContentChanged() { protected void onContentChanged() {
super.onContentChanged(); super.onContentChanged();
calcNotesCount(); calcNotesCount(); // 计算笔记数量
} }
@Override @Override
public void changeCursor(Cursor cursor) { public void changeCursor(Cursor cursor) {
super.changeCursor(cursor); super.changeCursor(cursor);
calcNotesCount(); calcNotesCount(); // 更改游标并计算笔记数量
} }
// 计算笔记数量
private void calcNotesCount() { private void calcNotesCount() {
mNotesCount = 0; mNotesCount = 0;
for (int i = 0; i < getCount(); i++) { for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i); Cursor c = (Cursor) getItem(i);
if (c != null) { if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) { // 如果是笔记类型
mNotesCount++; mNotesCount++;
} }
} else { } else {
@ -181,4 +189,4 @@ public class NotesListAdapter extends CursorAdapter {
} }
} }
} }
} }

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * <url id="d0s4nev37oq8u4isp1r0" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -31,77 +31,86 @@ import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout { public class NotesListItem extends LinearLayout {
private ImageView mAlert; private ImageView mAlert; // 提醒图标
private TextView mTitle; private TextView mTitle; // 标题文本视图
private TextView mTime; private TextView mTime; // 时间文本视图
private TextView mCallName; private TextView mCallName; // 通话名称文本视图
private NoteItemData mItemData; private NoteItemData mItemData; // 笔记项数据
private CheckBox mCheckBox; private CheckBox mCheckBox; // 复选框
public NotesListItem(Context context) { public NotesListItem(Context context) {
super(context); super(context);
inflate(context, R.layout.note_item, this); inflate(context, R.layout.note_item, this); // 加载布局文件
mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mAlert = (ImageView) findViewById(R.id.iv_alert_icon); // 获取提醒图标
mTitle = (TextView) findViewById(R.id.tv_title); mTitle = (TextView) findViewById(R.id.tv_title); // 获取标题文本视图
mTime = (TextView) findViewById(R.id.tv_time); mTime = (TextView) findViewById(R.id.tv_time); // 获取时间文本视图
mCallName = (TextView) findViewById(R.id.tv_name); mCallName = (TextView) findViewById(R.id.tv_name); // 获取通话名称文本视图
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); // 获取复选框
} }
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 如果启用了选择模式且是笔记类型,则显示复选框并设置选中状态
if (choiceMode && data.getType() == Notes.TYPE_NOTE) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked); mCheckBox.setChecked(checked);
} else { } else {
mCheckBox.setVisibility(View.GONE); mCheckBox.setVisibility(View.GONE); // 隐藏复选框
} }
mItemData = data; mItemData = data; // 保存笔记项数据
// 处理通话记录文件夹
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE); mCallName.setVisibility(View.GONE); // 隐藏通话名称
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE); // 显示提醒图标
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置标题文本外观
mTitle.setText(context.getString(R.string.call_record_folder_name) mTitle.setText(context.getString(R.string.call_record_folder_name) + context.getString(R.string.format_folder_files_count, data.getNotesCount())); // 设置标题文本
+ context.getString(R.string.format_folder_files_count, data.getNotesCount())); mAlert.setImageResource(R.drawable.call_record); // 设置提醒图标资源
mAlert.setImageResource(R.drawable.call_record); }
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { // 处理通话记录中的笔记
mCallName.setVisibility(View.VISIBLE); else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setText(data.getCallName()); mCallName.setVisibility(View.VISIBLE); // 显示通话名称
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mCallName.setText(data.getCallName()); // 设置通话名称
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem); // 设置标题文本外观
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置标题文本
// 如果有提醒,则显示提醒图标
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE); // 隐藏提醒图标
} }
} else { }
mCallName.setVisibility(View.GONE); // 处理其他类型的笔记或文件夹
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); else {
mCallName.setVisibility(View.GONE); // 隐藏通话名称
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); // 设置标题文本外观
// 如果是文件夹类型
if (data.getType() == Notes.TYPE_FOLDER) { if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet() mTitle.setText(data.getSnippet() + context.getString(R.string.format_folder_files_count, data.getNotesCount())); // 设置标题文本
+ context.getString(R.string.format_folder_files_count, mAlert.setVisibility(View.GONE); // 隐藏提醒图标
data.getNotesCount())); }
mAlert.setVisibility(View.GONE); // 如果是笔记类型
} else { else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 设置标题文本
// 如果有提醒,则显示提醒图标
if (data.hasAlert()) { if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock); mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE); mAlert.setVisibility(View.VISIBLE);
} else { } else {
mAlert.setVisibility(View.GONE); mAlert.setVisibility(View.GONE); // 隐藏提醒图标
} }
} }
} }
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); // 设置时间文本
setBackground(data); setBackground(data); // 设置背景
} }
private void setBackground(NoteItemData data) { private void setBackground(NoteItemData data) {
int id = data.getBgColorId(); int id = data.getBgColorId(); // 获取背景颜色 ID
// 如果是笔记类型
if (data.getType() == Notes.TYPE_NOTE) { if (data.getType() == Notes.TYPE_NOTE) {
// 根据笔记的状态设置不同的背景资源
if (data.isSingle() || data.isOneFollowingFolder()) { if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) { } else if (data.isLast()) {
@ -111,12 +120,14 @@ public class NotesListItem extends LinearLayout {
} else { } else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
} }
} else { }
// 如果是文件夹类型
else {
setBackgroundResource(NoteItemBgResources.getFolderBgRes()); setBackgroundResource(NoteItemBgResources.getFolderBgRes());
} }
} }
public NoteItemData getItemData() { public NoteItemData getItemData() {
return mItemData; return mItemData; // 返回笔记项数据
} }
} }

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * <url id="d0s4q1f37oq8u4itada0" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -49,41 +49,48 @@ import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity { public class NotesPreferenceActivity extends PreferenceActivity {
// 定义偏好设置名称
public static final String PREFERENCE_NAME = "notes_preferences"; 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_SYNC_ACCOUNT_NAME = "pref_key_account_name";
// 定义最后同步时间偏好设置键
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time"; 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"; 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 PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
// 定义授权过滤键
private static final String AUTHORITIES_FILTER_KEY = "authorities"; private static final String AUTHORITIES_FILTER_KEY = "authorities";
// 定义账户类别偏好设置
private PreferenceCategory mAccountCategory; private PreferenceCategory mAccountCategory;
// 定义同步服务广播接收器
private GTaskReceiver mReceiver; private GTaskReceiver mReceiver;
// 定义原始账户数组
private Account[] mOriAccounts; private Account[] mOriAccounts;
// 定义是否已添加账户的标志
private boolean mHasAddedAccount; private boolean mHasAddedAccount;
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
super.onCreate(icicle); super.onCreate(icicle);
/* using the app icon for navigation */ // 设置操作栏回家按钮可用
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
// 添加偏好设置资源
addPreferencesFromResource(R.xml.preferences); addPreferencesFromResource(R.xml.preferences);
// 获取账户类别偏好设置
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY); mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
// 创建广播接收器
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
// 创建意图过滤器并添加同步服务广播名称
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
// 注册广播接收器
registerReceiver(mReceiver, filter); registerReceiver(mReceiver, filter);
mOriAccounts = null; // 加载设置头部布局并添加到列表视图
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true); getListView().addHeaderView(header, null, true);
} }
@ -92,20 +99,23 @@ public class NotesPreferenceActivity extends PreferenceActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
// need to set sync account automatically if user has added a new // 如果用户添加了新账户,则自动设置同步账户
// account
if (mHasAddedAccount) { if (mHasAddedAccount) {
// 获取谷歌账户
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) { if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
for (Account accountNew : accounts) { for (Account accountNew : accounts) {
boolean found = false; boolean found = false;
for (Account accountOld : mOriAccounts) { for (Account accountOld : mOriAccounts) {
// 如果找到匹配的账户名称
if (TextUtils.equals(accountOld.name, accountNew.name)) { if (TextUtils.equals(accountOld.name, accountNew.name)) {
found = true; found = true;
break; break;
} }
} }
// 如果未找到匹配的账户名称
if (!found) { if (!found) {
// 设置同步账户
setSyncAccount(accountNew.name); setSyncAccount(accountNew.name);
break; break;
} }
@ -113,53 +123,67 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
// 刷新 UI
refreshUI(); refreshUI();
} }
@Override @Override
protected void onDestroy() { protected void onDestroy() {
// 注销广播接收器
if (mReceiver != null) { if (mReceiver != null) {
unregisterReceiver(mReceiver); unregisterReceiver(mReceiver);
} }
super.onDestroy(); super.onDestroy();
} }
// 加载账户偏好设置
private void loadAccountPreference() { private void loadAccountPreference() {
// 移除所有账户偏好设置
mAccountCategory.removeAll(); mAccountCategory.removeAll();
// 创建新的账户偏好设置
Preference accountPref = new Preference(this); Preference accountPref = new Preference(this);
// 获取默认同步账户名称
final String defaultAccount = getSyncAccountName(this); final String defaultAccount = getSyncAccountName(this);
// 设置账户偏好设置的标题和摘要
accountPref.setTitle(getString(R.string.preferences_account_title)); accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary)); accountPref.setSummary(getString(R.string.preferences_account_summary));
// 设置账户偏好设置的点击监听器
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
// 如果同步服务未运行
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
// 如果默认账户名称为空
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // 显示选择账户对话框
showSelectAccountAlertDialog(); showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // 显示更改账户确认对话框
// user about the risk
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
} }
} else { } else {
// 显示无法更改账户的提示
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show(); .show();
} }
return true; return true;
} }
}); });
// 添加账户偏好设置到账户类别
mAccountCategory.addPreference(accountPref); mAccountCategory.addPreference(accountPref);
} }
// 加载同步按钮
private void loadSyncButton() { private void loadSyncButton() {
// 获取同步按钮和最后同步时间文本视图
Button syncButton = (Button) findViewById(R.id.preference_sync_button); Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state // 设置同步按钮状态
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
// 如果同步服务正在运行,设置按钮文本为取消同步
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
@ -167,6 +191,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} else { } else {
// 如果同步服务未运行,设置按钮文本为立即同步
syncButton.setText(getString(R.string.preferences_button_sync_immediately)); syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
@ -174,13 +199,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}); });
} }
// 设置同步按钮可用状态
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this))); syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time // 设置最后同步时间文本视图
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
// 如果同步服务正在运行,显示同步进度
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); lastSyncTimeView.setVisibility(View.VISIBLE);
} else { } else {
// 如果同步服务未运行,显示最后同步时间
long lastSyncTime = getLastSyncTime(this); long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) { if (lastSyncTime != 0) {
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time, lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
@ -193,29 +221,35 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
} }
// 刷新 UI
private void refreshUI() { private void refreshUI() {
// 加载账户偏好设置和同步按钮
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
} }
// 显示选择账户对话框
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
// 创建对话框构建器
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 加载对话框标题布局
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title)); titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips)); subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null);
// 获取谷歌账户
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this); String defAccount = getSyncAccountName(this);
// 保存原始账户数组并重置添加账户标志
mOriAccounts = accounts; mOriAccounts = accounts;
mHasAddedAccount = false; mHasAddedAccount = false;
// 如果有谷歌账户,设置单选按钮
if (accounts.length > 0) { if (accounts.length > 0) {
CharSequence[] items = new CharSequence[accounts.length]; CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items; final CharSequence[] itemMapping = items;
@ -230,6 +264,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.setSingleChoiceItems(items, checkedItem, dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
// 设置同步账户并关闭对话框
setSyncAccount(itemMapping[which].toString()); setSyncAccount(itemMapping[which].toString());
dialog.dismiss(); dialog.dismiss();
refreshUI(); refreshUI();
@ -237,6 +272,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}); });
} }
// 加载添加账户布局并设置点击监听器
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null); View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView); dialogBuilder.setView(addAccountView);
@ -245,18 +281,19 @@ public class NotesPreferenceActivity extends PreferenceActivity {
public void onClick(View v) { public void onClick(View v) {
mHasAddedAccount = true; mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { "gmail-ls" });
"gmail-ls"
});
startActivityForResult(intent, -1); startActivityForResult(intent, -1);
dialog.dismiss(); dialog.dismiss();
} }
}); });
} }
// 显示更改账户确认对话框
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
// 创建对话框构建器
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 加载对话框标题布局
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
@ -265,6 +302,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
// 设置菜单项
CharSequence[] menuItemArray = new CharSequence[] { CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
@ -283,13 +321,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
dialogBuilder.show(); dialogBuilder.show();
} }
// 获取谷歌账户
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
// 设置同步账户
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) { if (!getSyncAccountName(this).equals(account)) {
// 保存同步账户名称到偏好设置
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
if (account != null) { if (account != null) {
@ -299,10 +340,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
editor.commit(); editor.commit();
// clean up last sync time // 清除最后同步时间
setLastSyncTime(this, 0); setLastSyncTime(this, 0);
// clean up local gtask related info // 清除本地与同步相关的数据
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -312,13 +353,16 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
}).start(); }).start();
// 显示设置账户成功的提示
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT).show();
} }
} }
// 移除同步账户
private void removeSyncAccount() { private void removeSyncAccount() {
// 移除同步账户名称和最后同步时间
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
@ -329,7 +373,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {
} }
editor.commit(); editor.commit();
// clean up local gtask related info // 清除本地与同步相关的数据
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -340,43 +384,44 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}).start(); }).start();
} }
// 获取同步账户名称
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, ""); return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
// 设置最后同步时间
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time); editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit(); editor.commit();
} }
// 获取最后同步时间
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0); return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
// 定义同步服务广播接收器
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
// 刷新 UI 并更新同步状态文本
refreshUI(); refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent syncStatus.setText(intent.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
} }
} }
} }
// 处理菜单项点击事件
public boolean onOptionsItemSelected(MenuItem item) { public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case android.R.id.home: case android.R.id.home:
// 返回笔记列表活动
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);
@ -385,4 +430,4 @@ public class NotesPreferenceActivity extends PreferenceActivity {
return false; return false;
} }
} }
} }

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * <url id="d0s4va13om1vt58e9vr0" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -15,6 +15,7 @@
*/ */
package net.micode.notes.widget; package net.micode.notes.widget;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider; import android.appwidget.AppWidgetProvider;
@ -33,30 +34,34 @@ import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
public abstract class NoteWidgetProvider extends AppWidgetProvider { public abstract class NoteWidgetProvider extends AppWidgetProvider {
public static final String [] PROJECTION = new String [] { // 定义查询投影,指定要查询的列
NoteColumns.ID, public static final String[] PROJECTION = new String[] {
NoteColumns.BG_COLOR_ID, NoteColumns.ID, // 笔记 ID
NoteColumns.SNIPPET NoteColumns.BG_COLOR_ID, // 背景颜色 ID
NoteColumns.SNIPPET // 摘要
}; };
public static final int COLUMN_ID = 0; // 定义各列在查询结果中的索引
public static final int COLUMN_BG_COLOR_ID = 1; public static final int COLUMN_ID = 0;
public static final int COLUMN_SNIPPET = 2; public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
private static final String TAG = "NoteWidgetProvider"; private static final String TAG = "NoteWidgetProvider"; // 日志标签
@Override @Override
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
// 当小部件被删除时,更新数据库中的相关记录
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
context.getContentResolver().update(Notes.CONTENT_NOTE_URI, context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values, values,
NoteColumns.WIDGET_ID + "=?", NoteColumns.WIDGET_ID + "=?",
new String[] { String.valueOf(appWidgetIds[i])}); new String[] { String.valueOf(appWidgetIds[i]) });
} }
} }
// 获取与小部件相关的笔记信息
private Cursor getNoteWidgetInfo(Context context, int widgetId) { private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
@ -65,17 +70,19 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
null); null);
} }
// 更新小部件
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false); update(context, appWidgetManager, appWidgetIds, false);
} }
// 更新小部件,支持隐私模式
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) { boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) { for (int i = 0; i < appWidgetIds.length; i++) {
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
int bgId = ResourceParser.getDefaultBgId(context); int bgId = ResourceParser.getDefaultBgId(context); // 获取默认背景颜色 ID
String snippet = ""; String snippet = ""; // 笔记摘要
Intent intent = new Intent(context, NoteEditActivity.class); Intent intent = new Intent(context, NoteEditActivity.class); // 创建编辑笔记的意图
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());
@ -87,8 +94,8 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
c.close(); c.close();
return; return;
} }
snippet = c.getString(COLUMN_SNIPPET); snippet = c.getString(COLUMN_SNIPPET); // 获取笔记摘要
bgId = c.getInt(COLUMN_BG_COLOR_ID); bgId = c.getInt(COLUMN_BG_COLOR_ID); // 获取背景颜色 ID
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
intent.setAction(Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW);
} else { } else {
@ -100,33 +107,31 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
c.close(); c.close();
} }
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId()); // 创建远程视图
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); 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; PendingIntent pendingIntent = null;
if (privacyMode) { if (privacyMode) {
rv.setTextViewText(R.id.widget_text, rv.setTextViewText(R.id.widget_text, context.getString(R.string.widget_under_visit_mode)); // 设置隐私模式下的文本
context.getString(R.string.widget_under_visit_mode)); pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
} else { } else {
rv.setTextViewText(R.id.widget_text, snippet); rv.setTextViewText(R.id.widget_text, snippet); // 设置笔记摘要文本
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent.FLAG_UPDATE_CURRENT);
} }
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); // 设置点击事件的待处理意图
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); appWidgetManager.updateAppWidget(appWidgetIds[i], rv); // 更新小部件
} }
} }
} }
// 获取背景颜色资源 ID由子类实现
protected abstract int getBgResourceId(int bgId); protected abstract int getBgResourceId(int bgId);
// 获取布局 ID由子类实现
protected abstract int getLayoutId(); protected abstract int getLayoutId();
// 获取小部件类型,由子类实现
protected abstract int getWidgetType(); protected abstract int getWidgetType();
} }

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * <url id="d0s510qj4egu9ar0mmmg" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -25,23 +25,27 @@ import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_2x extends NoteWidgetProvider { public class NoteWidgetProvider_2x extends NoteWidgetProvider {
// 当小部件更新时调用
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds); // 调用基类的更新方法
} }
// 获取小部件的布局资源 ID
@Override @Override
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_2x; return R.layout.widget_2x; // 返回 2x2 小部件的布局资源 ID
} }
// 获取背景颜色资源 ID
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); // 获取 2x2 小部件的背景颜色资源 ID
} }
// 获取小部件类型
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X; return Notes.TYPE_WIDGET_2X; // 返回 2x2 小部件的类型
} }
} }

@ -5,7 +5,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * <url id="d0s5240u8ld6ib5i11c0" type="url" status="parsed" title="Apache License, Version 2.0" wc="10467">http://www.apache.org/licenses/LICENSE-2.0</url>
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -25,22 +25,27 @@ import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_4x extends NoteWidgetProvider { public class NoteWidgetProvider_4x extends NoteWidgetProvider {
// 当小部件更新时调用
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds); // 调用基类的更新方法
} }
// 获取小部件的布局资源 ID
@Override
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_4x; return R.layout.widget_4x; // 返回 4x4 小部件的布局资源 ID
} }
// 获取背景颜色资源 ID
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); // 获取 4x4 小部件的背景颜色资源 ID
} }
// 获取小部件类型
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; return Notes.TYPE_WIDGET_4X; // 返回 4x4 小部件的类型
} }
} }

@ -24,64 +24,37 @@ import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
* Google Task
* TaskID
*/
public class MetaData extends Task { public class MetaData extends Task {
// 日志标签
private final static String TAG = MetaData.class.getSimpleName(); private final static String TAG = MetaData.class.getSimpleName();
// 关联的Google Task服务器ID
private String mRelatedGid = null; private String mRelatedGid = null;
/**
*
* @param gid Google TaskID
* @param metaInfo JSON
* gidmetaInfonotes
*
*/
public void setMeta(String gid, JSONObject metaInfo) { public void setMeta(String gid, JSONObject metaInfo) {
try { try {
// 将关联的GTask ID注入元数据头部
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid); metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) { } catch (JSONException e) {
Log.e(TAG, "failed to put related gid"); Log.e(TAG, "failed to put related gid");
} }
// 序列化元数据到笔记内容字段
setNotes(metaInfo.toString()); setNotes(metaInfo.toString());
// 设置固定名称标识为元数据笔记
setName(GTaskStringUtils.META_NOTE_NAME); setName(GTaskStringUtils.META_NOTE_NAME);
} }
/**
* GTask ID
*/
public String getRelatedGid() { public String getRelatedGid() {
return mRelatedGid; return mRelatedGid;
} }
/**
* notes
*/
@Override @Override
public boolean isWorthSaving() { public boolean isWorthSaving() {
return getNotes() != null; return getNotes() != null;
} }
/**
* JSON
* notesGTask ID
*/
@Override @Override
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js); super.setContentByRemoteJSON(js);
if (getNotes() != null) { if (getNotes() != null) {
try { try {
// 反序列化notes字段内容
JSONObject metaInfo = new JSONObject(getNotes().trim()); JSONObject metaInfo = new JSONObject(getNotes().trim());
// 提取关联的GTask ID
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID); mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) { } catch (JSONException e) {
Log.w(TAG, "failed to get related gid"); Log.w(TAG, "failed to get related gid");
@ -90,32 +63,20 @@ public class MetaData extends Task {
} }
} }
// 以下方法在元数据管理中不应被调用,直接抛出异常
/**
* JSON
* @throws IllegalAccessError
*/
@Override @Override
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called"); throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
} }
/**
* JSON
* @throws IllegalAccessError
*/
@Override @Override
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called"); throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
} }
/**
*
* @throws IllegalAccessError
*/
@Override @Override
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called"); throw new IllegalAccessError("MetaData:getSyncAction should not be called");
} }
}
}

@ -17,48 +17,36 @@
package net.micode.notes.gtask.data; package net.micode.notes.gtask.data;
import android.database.Cursor; import android.database.Cursor;
import org.json.JSONObject; import org.json.JSONObject;
/**
*
*
*
*/
public abstract class Node { public abstract class Node {
// 同步动作类型常量
/** 无需同步操作 */
public static final int SYNC_ACTION_NONE = 0; public static final int SYNC_ACTION_NONE = 0;
/** 需要在远程服务器创建新条目 */
public static final int SYNC_ACTION_ADD_REMOTE = 1; public static final int SYNC_ACTION_ADD_REMOTE = 1;
/** 需要在本地数据库创建新条目 */
public static final int SYNC_ACTION_ADD_LOCAL = 2; public static final int SYNC_ACTION_ADD_LOCAL = 2;
/** 需要删除远程服务器条目 */
public static final int SYNC_ACTION_DEL_REMOTE = 3; public static final int SYNC_ACTION_DEL_REMOTE = 3;
/** 需要删除本地数据库条目 */
public static final int SYNC_ACTION_DEL_LOCAL = 4; public static final int SYNC_ACTION_DEL_LOCAL = 4;
/** 需要更新远程服务器条目 */
public static final int SYNC_ACTION_UPDATE_REMOTE = 5; public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
/** 需要更新本地数据库条目 */
public static final int SYNC_ACTION_UPDATE_LOCAL = 6; public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
/** 检测到数据冲突需要处理 */
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7; public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
/** 同步过程发生错误 */
public static final int SYNC_ACTION_ERROR = 8; public static final int SYNC_ACTION_ERROR = 8;
// 节点基础属性
/** Google Task服务器分配的唯一标识符 */
private String mGid; private String mGid;
/** 节点显示名称 */
private String mName; private String mName;
/** 最后修改时间戳(毫秒级) */
private long mLastModified; private long mLastModified;
/** 删除标记(逻辑删除) */
private boolean mDeleted; private boolean mDeleted;
/**
*
* gid=null, 0
*/
public Node() { public Node() {
mGid = null; mGid = null;
mName = ""; mName = "";
@ -66,86 +54,48 @@ public abstract class Node {
mDeleted = false; mDeleted = false;
} }
// 抽象方法定义(需子类实现)
/**
* JSON
* @param actionId
* @return JSON
*/
public abstract JSONObject getCreateAction(int actionId); public abstract JSONObject getCreateAction(int actionId);
/**
* JSON
* @param actionId
* @return JSON
*/
public abstract JSONObject getUpdateAction(int actionId); public abstract JSONObject getUpdateAction(int actionId);
/**
* JSON
* @param js JSON
*/
public abstract void setContentByRemoteJSON(JSONObject js); public abstract void setContentByRemoteJSON(JSONObject js);
/**
* JSON
* @param js JSON
*/
public abstract void setContentByLocalJSON(JSONObject js); public abstract void setContentByLocalJSON(JSONObject js);
/**
* JSON
* @return JSON
*/
public abstract JSONObject getLocalJSONFromContent(); public abstract JSONObject getLocalJSONFromContent();
/**
*
* @param c
* @return SYNC_ACTION
*/
public abstract int getSyncAction(Cursor c); public abstract int getSyncAction(Cursor c);
// 属性访问方法
/** 设置Google Task服务器ID */
public void setGid(String gid) { public void setGid(String gid) {
this.mGid = gid; this.mGid = gid;
} }
/** 设置节点名称 */
public void setName(String name) { public void setName(String name) {
this.mName = name; this.mName = name;
} }
/** 设置最后修改时间戳 */
public void setLastModified(long lastModified) { public void setLastModified(long lastModified) {
this.mLastModified = lastModified; this.mLastModified = lastModified;
} }
/** 设置删除标记 */
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
this.mDeleted = deleted; this.mDeleted = deleted;
} }
/** 获取Google Task服务器ID */
public String getGid() { public String getGid() {
return this.mGid; return this.mGid;
} }
/** 获取节点名称 */
public String getName() { public String getName() {
return this.mName; return this.mName;
} }
/** 获取最后修改时间戳 */
public long getLastModified() { public long getLastModified() {
return this.mLastModified; return this.mLastModified;
} }
/** 获取删除状态 */
public boolean getDeleted() { public boolean getDeleted() {
return this.mDeleted; return this.mDeleted;
} }
}
}

@ -34,65 +34,54 @@ import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
/**
*
* 便DataCRUD
*
*/
public class SqlData { public class SqlData {
// 日志标签
private static final String TAG = SqlData.class.getSimpleName(); private static final String TAG = SqlData.class.getSimpleName();
// 无效ID标识用于新建条目
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
// 数据表查询字段投影对应DATA表的列
public static final String[] PROJECTION_DATA = new String[] { public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, // 0:数据ID DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.MIME_TYPE, // 1:MIME类型 DataColumns.DATA3
DataColumns.CONTENT, // 2:内容主体JSON格式
DataColumns.DATA1, // 3:扩展数据1长整型
DataColumns.DATA3 // 4:扩展数据3字符串
}; };
// 投影字段索引常量
public static final int DATA_ID_COLUMN = 0; public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1; public static final int DATA_MIME_TYPE_COLUMN = 1;
public static final int DATA_CONTENT_COLUMN = 2; public static final int DATA_CONTENT_COLUMN = 2;
public static final int DATA_CONTENT_DATA_1_COLUMN = 3; public static final int DATA_CONTENT_DATA_1_COLUMN = 3;
public static final int DATA_CONTENT_DATA_3_COLUMN = 4; public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
// 成员变量 private ContentResolver mContentResolver;
private ContentResolver mContentResolver; // 内容解析器(用于数据库操作)
private boolean mIsCreate; // 新建数据条目标识 private boolean mIsCreate;
private long mDataId; // 当前数据ID
private String mDataMimeType; // MIME类型默认NOTE类型 private long mDataId;
private String mDataContent; // 内容主体
private long mDataContentData1; // 扩展数据1长整型字段 private String mDataMimeType;
private String mDataContentData3; // 扩展数据3字符串字段
private ContentValues mDiffDataValues; // 差异字段集合(用于批量更新) private String mDataContent;
/** private long mDataContentData1;
*
* @param context ContentResolver private String mDataContentData3;
*/
private ContentValues mDiffDataValues;
public SqlData(Context context) { public SqlData(Context context) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = true; mIsCreate = true;
// 初始化默认值
mDataId = INVALID_ID; mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE; // 默认MIME类型为便笺 mDataMimeType = DataConstants.NOTE;
mDataContent = ""; mDataContent = "";
mDataContentData1 = 0; mDataContentData1 = 0;
mDataContentData3 = ""; mDataContentData3 = "";
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
*
* @param context
* @param c
*/
public SqlData(Context context, Cursor c) { public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
mIsCreate = false; mIsCreate = false;
@ -100,10 +89,6 @@ public class SqlData {
mDiffDataValues = new ContentValues(); mDiffDataValues = new ContentValues();
} }
/**
*
* @param c
*/
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN); mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN); mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -112,21 +97,13 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN); mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
} }
/**
* JSON
* @param js JSON
* @throws JSONException JSON
*
*/
public void setContent(JSONObject js) throws JSONException { public void setContent(JSONObject js) throws JSONException {
// 处理数据ID字段
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID; long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) { if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId); mDiffDataValues.put(DataColumns.ID, dataId);
} }
mDataId = dataId; mDataId = dataId;
// 处理MIME类型字段
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE) String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE; : DataConstants.NOTE;
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) { if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
@ -134,21 +111,18 @@ public class SqlData {
} }
mDataMimeType = dataMimeType; mDataMimeType = dataMimeType;
// 处理内容主体字段
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : ""; String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) { if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent); mDiffDataValues.put(DataColumns.CONTENT, dataContent);
} }
mDataContent = dataContent; mDataContent = dataContent;
// 处理扩展数据1长整型
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0; long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;
if (mIsCreate || mDataContentData1 != dataContentData1) { if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1); mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
} }
mDataContentData1 = dataContentData1; mDataContentData1 = dataContentData1;
// 处理扩展数据3字符串
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : ""; String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) { if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3); mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
@ -156,12 +130,6 @@ public class SqlData {
mDataContentData3 = dataContentData3; mDataContentData3 = dataContentData3;
} }
/**
* JSON
* @return JSON
* @throws JSONException JSON
* null
*/
public JSONObject getContent() throws JSONException { public JSONObject getContent() throws JSONException {
if (mIsCreate) { if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet"); Log.e(TAG, "it seems that we haven't created this in database yet");
@ -176,59 +144,34 @@ public class SqlData {
return js; return js;
} }
/**
*
* @param noteId 便ID
* @param validateVersion
* @param version
* @throws ActionFailureException
*
*
* 1. ID
* 2.
* -
*/
public void commit(long noteId, boolean validateVersion, long version) { public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) { if (mIsCreate) {
// 新建数据处理
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) { if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID); // 移除无效ID mDiffDataValues.remove(DataColumns.ID);
} }
// 添加关联便笺ID
mDiffDataValues.put(DataColumns.NOTE_ID, noteId); mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
// 执行插入操作
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues); Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);
try { try {
// 从返回URI中解析新分配的ID
mDataId = Long.valueOf(uri.getPathSegments().get(1)); mDataId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString()); Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed"); throw new ActionFailureException("create note failed");
} }
} else { } else {
// 更新数据处理
if (mDiffDataValues.size() > 0) { if (mDiffDataValues.size() > 0) {
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
// 普通更新 result = mContentResolver.update(ContentUris.withAppendedId(
result = mContentResolver.update( Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mDataId),
mDiffDataValues,
null,
null
);
} else { } else {
// 带版本验证的更新(防止同步冲突) result = mContentResolver.update(ContentUris.withAppendedId(
result = mContentResolver.update( Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, mDataId),
mDiffDataValues,
// 使用子查询确保版本匹配
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE " ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", + " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
new String[] { String.valueOf(noteId), String.valueOf(version) } String.valueOf(noteId), String.valueOf(version)
); });
} }
if (result == 0) { if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing"); Log.w(TAG, "there is no update. maybe user updates note when syncing");
@ -236,15 +179,10 @@ public class SqlData {
} }
} }
// 重置状态
mDiffDataValues.clear(); mDiffDataValues.clear();
mIsCreate = false; mIsCreate = false;
} }
/**
* ID
* @return IDINVALID_ID
*/
public long getId() { public long getId() {
return mDataId; return mDataId;
} }

@ -37,15 +37,12 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
// SqlNote类用于处理便签数据的存储和操作包括数据的加载、设置、获取和提交等操作。
public class SqlNote { public class SqlNote {
// 日志标签,用于调试和日志记录
private static final String TAG = SqlNote.class.getSimpleName(); private static final String TAG = SqlNote.class.getSimpleName();
// 无效ID的常量值
private static final int INVALID_ID = -99999; private static final int INVALID_ID = -99999;
// 定义查询便签时需要的列
public static final String[] PROJECTION_NOTE = new String[] { public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID, NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE, NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
@ -55,80 +52,76 @@ public class SqlNote {
NoteColumns.VERSION NoteColumns.VERSION
}; };
// 定义PROJECTION_NOTE中各列的索引
public static final int ID_COLUMN = 0; public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1; public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2; public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3; public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4; public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5; public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6; public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7; public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8; public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9; public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10; public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11; public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12; public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13; public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14; public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15; public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16; public static final int VERSION_COLUMN = 16;
// 上下文环境,用于访问应用程序资源和数据库
private Context mContext; private Context mContext;
// 内容解析器,用于与内容提供器进行交互
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
// 标志位,表示该便签是否是新创建的
private boolean mIsCreate; private boolean mIsCreate;
// 便签的唯一标识符
private long mId; private long mId;
// 便签的提醒日期
private long mAlertDate; private long mAlertDate;
// 便签的背景颜色标识符
private int mBgColorId; private int mBgColorId;
// 便签的创建日期
private long mCreatedDate; private long mCreatedDate;
// 标志位,表示便签是否包含附件
private int mHasAttachment; private int mHasAttachment;
// 便签的最后修改日期
private long mModifiedDate; private long mModifiedDate;
// 便签的父便签标识符
private long mParentId; private long mParentId;
// 便签的简短摘要或标题
private String mSnippet; private String mSnippet;
// 便签的类型(如普通便签、文件夹、系统文件夹等)
private int mType; private int mType;
// 与便签关联的小部件标识符
private int mWidgetId; private int mWidgetId;
// 便签的小部件类型
private int mWidgetType; private int mWidgetType;
// 便签的原始父便签标识符
private long mOriginParent; private long mOriginParent;
// 便签的版本号,用于数据同步和冲突检测
private long mVersion; private long mVersion;
// 用于存储便签属性的更改,以便后续提交到数据库
private ContentValues mDiffNoteValues; private ContentValues mDiffNoteValues;
// 存储与便签相关的数据内容列表
private ArrayList<SqlData> mDataList; private ArrayList<SqlData> mDataList;
// 构造方法创建一个新的SqlNote对象初始化成员变量并设置默认值
public SqlNote(Context context) { public SqlNote(Context context) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -150,7 +143,6 @@ public class SqlNote {
mDataList = new ArrayList<SqlData>(); mDataList = new ArrayList<SqlData>();
} }
// 构造方法从数据库游标中加载便签数据初始化SqlNote对象
public SqlNote(Context context, Cursor c) { public SqlNote(Context context, Cursor c) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -162,7 +154,6 @@ public class SqlNote {
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
// 构造方法根据便签ID从数据库中加载便签数据初始化SqlNote对象
public SqlNote(Context context, long id) { public SqlNote(Context context, long id) {
mContext = context; mContext = context;
mContentResolver = context.getContentResolver(); mContentResolver = context.getContentResolver();
@ -172,15 +163,15 @@ public class SqlNote {
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
mDiffNoteValues = new ContentValues(); mDiffNoteValues = new ContentValues();
} }
// 根据便签ID从数据库中查询便签数据并加载到当前对象中
private void loadFromCursor(long id) { private void loadFromCursor(long id) {
Cursor c = null; Cursor c = null;
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
String.valueOf(id) String.valueOf(id)
}, null); }, null);
if (c != null) { if (c != null) {
c.moveToNext(); c.moveToNext();
@ -194,7 +185,6 @@ public class SqlNote {
} }
} }
// 从数据库游标中加载便签数据到当前对象中
private void loadFromCursor(Cursor c) { private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN); mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN); mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
@ -210,14 +200,13 @@ public class SqlNote {
mVersion = c.getLong(VERSION_COLUMN); mVersion = c.getLong(VERSION_COLUMN);
} }
// 加载与当前便签相关的数据内容
private void loadDataContent() { private void loadDataContent() {
Cursor c = null; Cursor c = null;
mDataList.clear(); mDataList.clear();
try { try {
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA, c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] { "(note_id=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
}, null); }, null);
if (c != null) { if (c != null) {
if (c.getCount() == 0) { if (c.getCount() == 0) {
@ -237,14 +226,13 @@ public class SqlNote {
} }
} }
// 从JSON对象中设置便签的内容和属性
public boolean setContent(JSONObject js) { public boolean setContent(JSONObject js) {
try { try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system folder"); Log.w(TAG, "cannot set system folder");
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
// 对于文件夹,我们只能更新摘要和类型 // for folder we can only update the snnipet and type
String snippet = note.has(NoteColumns.SNIPPET) ? note String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : ""; .getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) { if (mIsCreate || !mSnippet.equals(snippet)) {
@ -260,8 +248,7 @@ public class SqlNote {
mType = type; mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) { if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id); mDiffNoteValues.put(NoteColumns.ID, id);
} }
@ -372,7 +359,6 @@ public class SqlNote {
return true; return true;
} }
// 将便签的内容和属性转换为JSON对象
public JSONObject getContent() { public JSONObject getContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
@ -421,48 +407,39 @@ public class SqlNote {
return null; return null;
} }
// 设置便签的父便签标识符
public void setParentId(long id) { public void setParentId(long id) {
mParentId = id; mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id); mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
} }
// 设置便签的Gtask ID
public void setGtaskId(String gid) { public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid); mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
} }
// 设置便签的同步ID
public void setSyncId(long syncId) { public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId); mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
} }
// 重置便签的本地修改标志
public void resetLocalModified() { public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0); mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
} }
// 获取便签的唯一标识符
public long getId() { public long getId() {
return mId; return mId;
} }
// 获取便签的父便签标识符
public long getParentId() { public long getParentId() {
return mParentId; return mParentId;
} }
// 获取便签的简短摘要或标题
public String getSnippet() { public String getSnippet() {
return mSnippet; return mSnippet;
} }
// 判断便签是否为普通便签类型
public boolean isNoteType() { public boolean isNoteType() {
return mType == Notes.TYPE_NOTE; return mType == Notes.TYPE_NOTE;
} }
// 将便签的更改提交到数据库,包括插入新便签或更新现有便签,并处理数据同步和冲突检测
public void commit(boolean validateVersion) { public void commit(boolean validateVersion) {
if (mIsCreate) { if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) { if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
@ -491,16 +468,16 @@ public class SqlNote {
throw new IllegalStateException("Try to update note with invalid id"); throw new IllegalStateException("Try to update note with invalid id");
} }
if (mDiffNoteValues.size() > 0) { if (mDiffNoteValues.size() > 0) {
mVersion++; mVersion ++;
int result = 0; int result = 0;
if (!validateVersion) { if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] { + NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId) String.valueOf(mId)
}); });
} else { } else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "(" result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)", + NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] { new String[] {
String.valueOf(mId), String.valueOf(mVersion) String.valueOf(mId), String.valueOf(mVersion)
}); });
@ -517,7 +494,7 @@ public class SqlNote {
} }
} }
// 刷新本地信息 // refresh local info
loadFromCursor(mId); loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE) if (mType == Notes.TYPE_NOTE)
loadDataContent(); loadDataContent();
@ -525,4 +502,4 @@ public class SqlNote {
mDiffNoteValues.clear(); mDiffNoteValues.clear();
mIsCreate = false; mIsCreate = false;
} }
} }

@ -31,27 +31,20 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
// Task类继承自Node类用于处理任务相关的操作包括创建、更新、同步等
public class Task extends Node { public class Task extends Node {
// 日志标签,用于调试和日志记录
private static final String TAG = Task.class.getSimpleName(); private static final String TAG = Task.class.getSimpleName();
// 标志位,表示任务是否已完成
private boolean mCompleted; private boolean mCompleted;
// 任务的备注信息
private String mNotes; private String mNotes;
// 任务的元数据信息
private JSONObject mMetaInfo; private JSONObject mMetaInfo;
// 任务的前一个兄弟任务
private Task mPriorSibling; private Task mPriorSibling;
// 任务所属的任务列表
private TaskList mParent; private TaskList mParent;
// 构造方法,初始化任务对象
public Task() { public Task() {
super(); super();
mCompleted = false; mCompleted = false;
@ -61,22 +54,21 @@ public class Task extends Node {
mMetaInfo = null; mMetaInfo = null;
} }
// 生成创建任务的JSON对象用于与服务器交互
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// 设置操作类型为创建 // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// 设置操作ID // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 设置任务在父任务列表中的索引 // index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this)); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));
// 设置任务的基本信息 // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
@ -87,17 +79,17 @@ public class Task extends Node {
} }
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity); js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
// 设置父任务列表的ID // parent_id
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());
// 设置目标父类型 // dest_parent_type
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE, js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP); GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
// 设置列表ID // list_id
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid()); js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());
// 设置前一个兄弟任务的ID如果存在 // prior_sibling_id
if (mPriorSibling != null) { if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid()); js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
} }
@ -111,22 +103,21 @@ public class Task extends Node {
return js; return js;
} }
// 生成更新任务的JSON对象用于与服务器交互
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// 设置操作类型为更新 // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// 设置操作ID // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 设置任务ID // id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// 设置任务的更新信息 // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
if (getNotes() != null) { if (getNotes() != null) {
@ -144,36 +135,35 @@ public class Task extends Node {
return js; return js;
} }
// 从远程JSON对象中设置任务内容
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// 设置任务ID // id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// 设置最后修改时间 // last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// 设置任务名称 // name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
// 设置任务备注 // notes
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) { if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES)); setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
} }
// 设置任务是否已删除 // deleted
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED)); setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
} }
// 设置任务是否已完成 // completed
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) { if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED)); setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
} }
@ -185,25 +175,21 @@ public class Task extends Node {
} }
} }
// 从本地JSON对象中设置任务内容
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) { || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is available"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
} }
try { try {
// 获取任务的元数据
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 检查任务类型是否为普通任务
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type"); Log.e(TAG, "invalid type");
return; return;
} }
// 设置任务内容
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
@ -218,18 +204,16 @@ public class Task extends Node {
} }
} }
// 从任务内容生成本地JSON对象
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
String name = getName(); String name = getName();
try { try {
if (mMetaInfo == null) { if (mMetaInfo == null) {
// 新创建的任务 // new task created from web
if (name == null) { if (name == null) {
Log.w(TAG, "the note seems to be an empty one"); Log.w(TAG, "the note seems to be an empty one");
return null; return null;
} }
// 创建JSON对象
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject note = new JSONObject(); JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray(); JSONArray dataArray = new JSONArray();
@ -241,11 +225,10 @@ public class Task extends Node {
js.put(GTaskStringUtils.META_HEAD_NOTE, note); js.put(GTaskStringUtils.META_HEAD_NOTE, note);
return js; return js;
} else { } else {
// 已同步的任务 // synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA); JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
// 更新任务内容
for (int i = 0; i < dataArray.length(); i++) { for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i); JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
@ -264,7 +247,6 @@ public class Task extends Node {
} }
} }
// 设置任务的元数据信息
public void setMetaInfo(MetaData metaData) { public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) { if (metaData != null && metaData.getNotes() != null) {
try { try {
@ -276,7 +258,6 @@ public class Task extends Node {
} }
} }
// 根据游标数据确定同步操作类型
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
JSONObject noteInfo = null; JSONObject noteInfo = null;
@ -294,32 +275,31 @@ public class Task extends Node {
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
// 验证任务ID是否匹配 // validate the note id now
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) { if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match"); Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// 本地没有修改 // there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 两边都没有更新 // no update both side
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// 应用远程到本地 // apply remote to local
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// 验证Gtask ID是否匹配 // validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 只有本地修改 // local modification only
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// 同步冲突
return SYNC_ACTION_UPDATE_CONFLICT; return SYNC_ACTION_UPDATE_CONFLICT;
} }
} }
@ -331,49 +311,41 @@ public class Task extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
// 判断任务是否值得保存
public boolean isWorthSaving() { public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0) return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0); || (getNotes() != null && getNotes().trim().length() > 0);
} }
// 设置任务是否已完成
public void setCompleted(boolean completed) { public void setCompleted(boolean completed) {
this.mCompleted = completed; this.mCompleted = completed;
} }
// 设置任务备注
public void setNotes(String notes) { public void setNotes(String notes) {
this.mNotes = notes; this.mNotes = notes;
} }
// 设置任务的前一个兄弟任务
public void setPriorSibling(Task priorSibling) { public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling; this.mPriorSibling = priorSibling;
} }
// 设置任务所属的任务列表
public void setParent(TaskList parent) { public void setParent(TaskList parent) {
this.mParent = parent; this.mParent = parent;
} }
// 获取任务是否已完成
public boolean getCompleted() { public boolean getCompleted() {
return this.mCompleted; return this.mCompleted;
} }
// 获取任务备注
public String getNotes() { public String getNotes() {
return this.mNotes; return this.mNotes;
} }
// 获取任务的前一个兄弟任务
public Task getPriorSibling() { public Task getPriorSibling() {
return this.mPriorSibling; return this.mPriorSibling;
} }
// 获取任务所属的任务列表
public TaskList getParent() { public TaskList getParent() {
return this.mParent; return this.mParent;
} }
}
}

@ -29,40 +29,35 @@ import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
// TaskList类继承自Node类用于管理任务列表及其子任务
public class TaskList extends Node { public class TaskList extends Node {
// 日志标签,用于调试和日志记录
private static final String TAG = TaskList.class.getSimpleName(); private static final String TAG = TaskList.class.getSimpleName();
// 任务列表的索引
private int mIndex; private int mIndex;
// 子任务列表
private ArrayList<Task> mChildren; private ArrayList<Task> mChildren;
// 构造方法,初始化任务列表
public TaskList() { public TaskList() {
super(); super();
mChildren = new ArrayList<Task>(); mChildren = new ArrayList<Task>();
mIndex = 1; mIndex = 1;
} }
// 生成创建任务列表的JSON对象用于与服务器交互
public JSONObject getCreateAction(int actionId) { public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// 设置操作类型为创建 // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);
// 设置操作ID // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 设置任务列表的索引 // index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex); js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);
// 设置任务列表的基本信息 // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null"); entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
@ -79,22 +74,21 @@ public class TaskList extends Node {
return js; return js;
} }
// 生成更新任务列表的JSON对象用于与服务器交互
public JSONObject getUpdateAction(int actionId) { public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
try { try {
// 设置操作类型为更新 // action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// 设置操作ID // action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId); js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// 设置任务列表ID // id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid()); js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// 设置任务列表的更新信息 // entity_delta
JSONObject entity = new JSONObject(); JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName()); entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted()); entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
@ -109,21 +103,20 @@ public class TaskList extends Node {
return js; return js;
} }
// 从远程JSON对象中设置任务列表内容
public void setContentByRemoteJSON(JSONObject js) { public void setContentByRemoteJSON(JSONObject js) {
if (js != null) { if (js != null) {
try { try {
// 设置任务列表ID // id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) { if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID)); setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
} }
// 设置最后修改时间 // last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) { if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)); setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
} }
// 设置任务列表名称 // name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) { if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME)); setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
} }
@ -136,17 +129,14 @@ public class TaskList extends Node {
} }
} }
// 从本地JSON对象中设置任务列表内容
public void setContentByLocalJSON(JSONObject js) { public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is available"); Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
} }
try { try {
// 获取任务列表的元数据
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
// 根据任务列表类型设置名称
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET); String name = folder.getString(NoteColumns.SNIPPET);
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name); setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
@ -167,13 +157,11 @@ public class TaskList extends Node {
} }
} }
// 从任务列表内容生成本地JSON对象
public JSONObject getLocalJSONFromContent() { public JSONObject getLocalJSONFromContent() {
try { try {
JSONObject js = new JSONObject(); JSONObject js = new JSONObject();
JSONObject folder = new JSONObject(); JSONObject folder = new JSONObject();
// 获取任务列表名称
String folderName = getName(); String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)) if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(), folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
@ -195,29 +183,28 @@ public class TaskList extends Node {
} }
} }
// 根据游标数据确定同步操作类型
public int getSyncAction(Cursor c) { public int getSyncAction(Cursor c) {
try { try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) { if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// 本地没有修改 // there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 两边都没有更新 // no update both side
return SYNC_ACTION_NONE; return SYNC_ACTION_NONE;
} else { } else {
// 应用远程到本地 // apply remote to local
return SYNC_ACTION_UPDATE_LOCAL; return SYNC_ACTION_UPDATE_LOCAL;
} }
} else { } else {
// 验证Gtask ID是否匹配 // validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) { if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match"); Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) { if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// 只有本地修改 // local modification only
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} else { } else {
// 对于文件夹冲突,仅应用本地修改 // for folder conflicts, just apply local modification
return SYNC_ACTION_UPDATE_REMOTE; return SYNC_ACTION_UPDATE_REMOTE;
} }
} }
@ -229,18 +216,16 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR; return SYNC_ACTION_ERROR;
} }
// 获取子任务数量
public int getChildTaskCount() { public int getChildTaskCount() {
return mChildren.size(); return mChildren.size();
} }
// 添加子任务到任务列表
public boolean addChildTask(Task task) { public boolean addChildTask(Task task) {
boolean ret = false; boolean ret = false;
if (task != null && !mChildren.contains(task)) { if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task); ret = mChildren.add(task);
if (ret) { if (ret) {
// 设置子任务的前一个兄弟任务和父任务列表 // need to set prior sibling and parent
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1)); .get(mChildren.size() - 1));
task.setParent(this); task.setParent(this);
@ -249,7 +234,6 @@ public class TaskList extends Node {
return ret; return ret;
} }
// 在指定位置添加子任务
public boolean addChildTask(Task task, int index) { public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) { if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index"); Log.e(TAG, "add child task: invalid index");
@ -260,7 +244,7 @@ public class TaskList extends Node {
if (task != null && pos == -1) { if (task != null && pos == -1) {
mChildren.add(index, task); mChildren.add(index, task);
// 更新子任务列表 // update the task list
Task preTask = null; Task preTask = null;
Task afterTask = null; Task afterTask = null;
if (index != 0) if (index != 0)
@ -276,7 +260,6 @@ public class TaskList extends Node {
return true; return true;
} }
// 从任务列表中移除子任务
public boolean removeChildTask(Task task) { public boolean removeChildTask(Task task) {
boolean ret = false; boolean ret = false;
int index = mChildren.indexOf(task); int index = mChildren.indexOf(task);
@ -284,11 +267,11 @@ public class TaskList extends Node {
ret = mChildren.remove(task); ret = mChildren.remove(task);
if (ret) { if (ret) {
// 重置子任务的前一个兄弟任务和父任务列表 // reset prior sibling and parent
task.setPriorSibling(null); task.setPriorSibling(null);
task.setParent(null); task.setParent(null);
// 更新子任务列表 // update the task list
if (index != mChildren.size()) { if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling( mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1)); index == 0 ? null : mChildren.get(index - 1));
@ -298,7 +281,6 @@ public class TaskList extends Node {
return ret; return ret;
} }
// 移动子任务到指定位置
public boolean moveChildTask(Task task, int index) { public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
@ -317,7 +299,6 @@ public class TaskList extends Node {
return (removeChildTask(task) && addChildTask(task, index)); return (removeChildTask(task) && addChildTask(task, index));
} }
// 根据GID查找子任务
public Task findChildTaskByGid(String gid) { public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) { for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i); Task t = mChildren.get(i);
@ -328,12 +309,10 @@ public class TaskList extends Node {
return null; return null;
} }
// 获取子任务在列表中的索引
public int getChildTaskIndex(Task task) { public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task); return mChildren.indexOf(task);
} }
// 根据索引获取子任务
public Task getChildTaskByIndex(int index) { public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) { if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index"); Log.e(TAG, "getTaskByIndex: invalid index");
@ -342,7 +321,6 @@ public class TaskList extends Node {
return mChildren.get(index); return mChildren.get(index);
} }
// 根据GID获取子任务
public Task getChilTaskByGid(String gid) { public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) { for (Task task : mChildren) {
if (task.getGid().equals(gid)) if (task.getGid().equals(gid))
@ -351,18 +329,15 @@ public class TaskList extends Node {
return null; return null;
} }
// 获取子任务列表
public ArrayList<Task> getChildTaskList() { public ArrayList<Task> getChildTaskList() {
return this.mChildren; return this.mChildren;
} }
// 设置任务列表的索引
public void setIndex(int index) { public void setIndex(int index) {
this.mIndex = index; this.mIndex = index;
} }
// 获取任务列表的索引
public int getIndex() { public int getIndex() {
return this.mIndex; return this.mIndex;
} }
} }

@ -16,23 +16,18 @@
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
// ActionFailureException类用于表示任务操作失败的异常情况
public class ActionFailureException extends RuntimeException { public class ActionFailureException extends RuntimeException {
// 序列化ID用于标识类的版本
private static final long serialVersionUID = 4425249765923293627L; private static final long serialVersionUID = 4425249765923293627L;
// 构造方法,无参数
public ActionFailureException() { public ActionFailureException() {
super(); super();
} }
// 构造方法,带错误消息参数
public ActionFailureException(String paramString) { public ActionFailureException(String paramString) {
super(paramString); super(paramString);
} }
// 构造方法,带错误消息和异常原因参数
public ActionFailureException(String paramString, Throwable paramThrowable) { public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }

@ -16,23 +16,18 @@
package net.micode.notes.gtask.exception; package net.micode.notes.gtask.exception;
// NetworkFailureException类用于表示网络操作失败的异常情况
public class NetworkFailureException extends Exception { public class NetworkFailureException extends Exception {
// 序列化ID用于标识类的版本
private static final long serialVersionUID = 2107610287180234136L; private static final long serialVersionUID = 2107610287180234136L;
// 构造方法,无参数
public NetworkFailureException() { public NetworkFailureException() {
super(); super();
} }
// 构造方法,带错误消息参数
public NetworkFailureException(String paramString) { public NetworkFailureException(String paramString) {
super(paramString); super(paramString);
} }
// 构造方法,带错误消息和异常原因参数
public NetworkFailureException(String paramString, Throwable paramThrowable) { public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable); super(paramString, paramThrowable);
} }
} }

@ -1,3 +1,4 @@
/* /*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
* *
@ -27,29 +28,23 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity; import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 通知ID用于同步任务的通知
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
// 定义任务完成后的回调接口
public interface OnCompleteListener { public interface OnCompleteListener {
void onComplete(); void onComplete();
} }
// 上下文环境,用于访问应用程序资源
private Context mContext; private Context mContext;
// 通知管理器,用于显示同步通知
private NotificationManager mNotifiManager; private NotificationManager mNotifiManager;
// GTask管理器用于处理任务同步
private GTaskManager mTaskManager; private GTaskManager mTaskManager;
// 任务完成后的回调监听器
private OnCompleteListener mOnCompleteListener; private OnCompleteListener mOnCompleteListener;
// 构造方法,初始化任务所需的资源
public GTaskASyncTask(Context context, OnCompleteListener listener) { public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context; mContext = context;
mOnCompleteListener = listener; mOnCompleteListener = listener;
@ -58,19 +53,35 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager = GTaskManager.getInstance(); mTaskManager = GTaskManager.getInstance();
} }
// 取消同步操作
public void cancelSync() { public void cancelSync() {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
// 发布进度信息
public void publishProgess(String message) { public void publishProgess(String message) {
publishProgress(new String[] { publishProgress(new String[] {
message 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;
// 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);
// }
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent; PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {
@ -87,11 +98,10 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
.setContentIntent(pendingIntent) .setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis()) .setWhen(System.currentTimeMillis())
.setOngoing(true); .setOngoing(true);
Notification notification = builder.getNotification(); Notification notification=builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
} }
// 后台执行任务
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
@ -99,7 +109,6 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
// 更新进度
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
@ -108,7 +117,6 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
} }
// 任务完成后执行的操作
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
@ -132,4 +140,4 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}).start(); }).start();
} }
} }
} }

@ -44,6 +44,7 @@ import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams; import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams; import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -59,50 +60,36 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
public class GTaskClient { public class GTaskClient {
// 日志标签,用于调试和日志记录
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
// Google Tasks 的基础URL
private static final String GTASK_URL = "https://mail.google.com/tasks/"; 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"; 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 final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 单例实例
private static GTaskClient mInstance = null; private static GTaskClient mInstance = null;
// HTTP客户端用于网络请求
private DefaultHttpClient mHttpClient; private DefaultHttpClient mHttpClient;
// 获取数据的URL
private String mGetUrl; private String mGetUrl;
// 提交数据的URL
private String mPostUrl; private String mPostUrl;
// 客户端版本号
private long mClientVersion; private long mClientVersion;
// 登录状态
private boolean mLoggedin; private boolean mLoggedin;
// 最后登录时间
private long mLastLoginTime; private long mLastLoginTime;
// 操作ID
private int mActionId; private int mActionId;
// 当前账户
private Account mAccount; private Account mAccount;
// 更新数组
private JSONArray mUpdateArray; private JSONArray mUpdateArray;
// 私有构造方法,用于单例模式
private GTaskClient() { private GTaskClient() {
mHttpClient = null; mHttpClient = null;
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
@ -115,7 +102,6 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
// 获取单例实例
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
@ -123,18 +109,18 @@ public class GTaskClient {
return mInstance; return mInstance;
} }
// 登录Google账户
public boolean login(Activity activity) { public boolean login(Activity activity) {
// 检查是否需要重新登录 // we suppose that the cookie would expire after 5 minutes
// then we need to re-login
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// 检查账户是否切换 // need to re-login after account switch
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
@ -150,7 +136,7 @@ public class GTaskClient {
return false; return false;
} }
// 登录自定义域名 // login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) { .endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
@ -165,7 +151,7 @@ public class GTaskClient {
} }
} }
// 登录官方URL // try to login with google official url
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -178,7 +164,6 @@ public class GTaskClient {
return true; return true;
} }
// 登录Google账户并获取认证令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; String authToken;
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);
@ -204,6 +189,7 @@ public class GTaskClient {
return null; return null;
} }
// get the token now
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
try { try {
@ -221,10 +207,10 @@ public class GTaskClient {
return authToken; return authToken;
} }
// 尝试登录Google Tasks
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// 如果认证令牌过期,重新获取并再次尝试登录 // maybe the auth token is out of date, now let's invalidate the
// token and try again
authToken = loginGoogleAccount(activity, true); authToken = loginGoogleAccount(activity, true);
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
@ -239,7 +225,6 @@ public class GTaskClient {
return true; return true;
} }
// 登录Google Tasks
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;
@ -251,13 +236,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// 获取登录后的Cookie // get the cookie now
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -269,7 +255,7 @@ public class GTaskClient {
Log.w(TAG, "it seems that there is no auth cookie"); Log.w(TAG, "it seems that there is no auth cookie");
} }
// 获取客户端版本号 // get the client version
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -286,6 +272,7 @@ public class GTaskClient {
e.printStackTrace(); e.printStackTrace();
return false; return false;
} catch (Exception e) { } catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed"); Log.e(TAG, "httpget gtask_url failed");
return false; return false;
} }
@ -293,12 +280,10 @@ public class GTaskClient {
return true; return true;
} }
// 获取操作ID
private int getActionId() { private int getActionId() {
return mActionId++; return mActionId++;
} }
// 创建HTTP POST请求
private HttpPost createHttpPost() { private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl); HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -306,7 +291,6 @@ public class GTaskClient {
return httpPost; return httpPost;
} }
// 获取HTTP响应内容
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
@ -339,7 +323,6 @@ public class GTaskClient {
} }
} }
// 发送POST请求
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -353,6 +336,7 @@ public class GTaskClient {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity); httpPost.setEntity(entity);
// execute the post
HttpResponse response = mHttpClient.execute(httpPost); HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity()); String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString); return new JSONObject(jsString);
@ -376,18 +360,20 @@ public class GTaskClient {
} }
} }
// 创建任务
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list
actionList.put(task.getCreateAction(getActionId())); actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -400,18 +386,20 @@ public class GTaskClient {
} }
} }
// 创建任务列表
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list
actionList.put(tasklist.getCreateAction(getActionId())); actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0); GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
@ -424,14 +412,15 @@ public class GTaskClient {
} }
} }
// 提交更新
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
// action_list
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost);
@ -444,9 +433,10 @@ public class GTaskClient {
} }
} }
// 添加更新节点
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) { if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate(); commitUpdate();
} }
@ -457,7 +447,6 @@ public class GTaskClient {
} }
} }
// 移动任务
public void moveTask(Task task, TaskList preParent, TaskList curParent) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
@ -466,21 +455,26 @@ public class GTaskClient {
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) { if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling()); action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
} }
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) { if (preParent != curParent) {
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid()); action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
} }
actionList.put(action); actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost);
@ -492,17 +486,18 @@ public class GTaskClient {
} }
} }
// 删除节点
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
JSONObject jsPost = new JSONObject(); JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
// action_list
node.setDeleted(true); node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId())); actionList.put(node.getUpdateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost); postRequest(jsPost);
@ -514,7 +509,6 @@ public class GTaskClient {
} }
} }
// 获取任务列表
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -526,6 +520,7 @@ public class GTaskClient {
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the task list
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -552,7 +547,6 @@ public class GTaskClient {
} }
} }
// 获取任务列表中的任务
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -560,6 +554,7 @@ public class GTaskClient {
JSONArray actionList = new JSONArray(); JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject(); JSONObject action = new JSONObject();
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
@ -568,6 +563,7 @@ public class GTaskClient {
actionList.put(action); actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost); JSONObject jsResponse = postRequest(jsPost);
@ -579,13 +575,11 @@ public class GTaskClient {
} }
} }
// 获取同步账户
public Account getSyncAccount() { public Account getSyncAccount() {
return mAccount; return mAccount;
} }
// 重置更新数组
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }
} }

@ -47,57 +47,46 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
public class GTaskManager { public class GTaskManager {
// 日志标签,用于调试和日志记录
private static final String TAG = GTaskManager.class.getSimpleName(); private static final String TAG = GTaskManager.class.getSimpleName();
// 同步状态常量
public static final int STATE_SUCCESS = 0; public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1; public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_INTERNAL_ERROR = 2; public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_SYNC_IN_PROGRESS = 3; public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4; public static final int STATE_SYNC_CANCELLED = 4;
// 单例实例
private static GTaskManager mInstance = null; private static GTaskManager mInstance = null;
// 当前活动的Activity
private Activity mActivity; private Activity mActivity;
// 上下文环境
private Context mContext; private Context mContext;
// 内容解析器
private ContentResolver mContentResolver; private ContentResolver mContentResolver;
// 同步状态
private boolean mSyncing; private boolean mSyncing;
// 是否取消同步
private boolean mCancelled; private boolean mCancelled;
// GTask列表映射
private HashMap<String, TaskList> mGTaskListHashMap; private HashMap<String, TaskList> mGTaskListHashMap;
// GTask映射
private HashMap<String, Node> mGTaskHashMap; private HashMap<String, Node> mGTaskHashMap;
// 元数据映射
private HashMap<String, MetaData> mMetaHashMap; private HashMap<String, MetaData> mMetaHashMap;
// 元数据列表
private TaskList mMetaList; private TaskList mMetaList;
// 本地删除ID集合
private HashSet<Long> mLocalDeleteIdMap; private HashSet<Long> mLocalDeleteIdMap;
// GID到NID的映射
private HashMap<String, Long> mGidToNid; private HashMap<String, Long> mGidToNid;
// NID到GID的映射
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
// 私有构造方法,用于单例模式
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false;
mCancelled = false; mCancelled = false;
@ -110,7 +99,6 @@ public class GTaskManager {
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>();
} }
// 获取单例实例
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskManager(); mInstance = new GTaskManager();
@ -118,12 +106,11 @@ public class GTaskManager {
return mInstance; return mInstance;
} }
// 设置活动的Activity
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken
mActivity = activity; mActivity = activity;
} }
// 执行同步操作
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
@ -144,18 +131,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance(); GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray(); client.resetUpdateArray();
// 登录Google Tasks // login google task
if (!mCancelled) { if (!mCancelled) {
if (!client.login(mActivity)) { if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed"); throw new NetworkFailureException("login google task failed");
} }
} }
// 初始化GTask列表 // get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); initGTaskList();
// 执行内容同步 // do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent(); syncContent();
} catch (NetworkFailureException e) { } catch (NetworkFailureException e) {
@ -181,7 +168,6 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
// 初始化GTask列表
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
if (mCancelled) if (mCancelled)
return; return;
@ -189,7 +175,7 @@ public class GTaskManager {
try { try {
JSONArray jsTaskLists = client.getTaskLists(); JSONArray jsTaskLists = client.getTaskLists();
// 初始化元数据列表 // init meta list first
mMetaList = null; mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
@ -201,7 +187,7 @@ public class GTaskManager {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object); mMetaList.setContentByRemoteJSON(object);
// 加载元数据 // load meta data
JSONArray jsMetas = client.getTaskList(gid); JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) { for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j); object = (JSONObject) jsMetas.getJSONObject(j);
@ -217,7 +203,7 @@ public class GTaskManager {
} }
} }
// 创建元数据列表(如果不存在) // create meta list if not existed
if (mMetaList == null) { if (mMetaList == null) {
mMetaList = new TaskList(); mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -225,7 +211,7 @@ public class GTaskManager {
GTaskClient.getInstance().createTaskList(mMetaList); GTaskClient.getInstance().createTaskList(mMetaList);
} }
// 初始化任务列表 // init task list
for (int i = 0; i < jsTaskLists.length(); i++) { for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
@ -233,13 +219,13 @@ public class GTaskManager {
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDERMETA)) { + GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList(); TaskList tasklist = new TaskList();
tasklist.setContentByRemoteJSON(object); tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist); mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist); mGTaskHashMap.put(gid, tasklist);
// 加载任务 // load tasks
JSONArray jsTasks = client.getTaskList(gid); JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) { for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j); object = (JSONObject) jsTasks.getJSONObject(j);
@ -261,7 +247,6 @@ public class GTaskManager {
} }
} }
// 执行内容同步
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType;
Cursor c = null; Cursor c = null;
@ -274,7 +259,7 @@ public class GTaskManager {
return; return;
} }
// 同步本地删除的便签 // for local deleted note
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] { "(type<>? AND parent_id=?)", new String[] {
@ -301,10 +286,10 @@ public class GTaskManager {
} }
} }
// 同步文件夹 // sync folder first
syncFolder(); syncFolder();
// 同步便签 // for note existing in database
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -321,8 +306,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
@ -339,7 +326,7 @@ public class GTaskManager {
} }
} }
// 同步剩余项目 // go through remaining items
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator(); Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next(); Map.Entry<String, Node> entry = iter.next();
@ -347,21 +334,23 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null); doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
} }
// 清除本地删除表 // mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
if (!mCancelled) { if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) { if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes"); throw new ActionFailureException("failed to batch-delete local deleted notes");
} }
} }
// 刷新本地同步ID // refresh local sync id
if (!mCancelled) { if (!mCancelled) {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId(); refreshLocalSyncId();
} }
} }
// 同步文件夹
private void syncFolder() throws NetworkFailureException { private void syncFolder() throws NetworkFailureException {
Cursor c = null; Cursor c = null;
String gid; String gid;
@ -372,7 +361,7 @@ public class GTaskManager {
return; return;
} }
// 同步根文件夹 // for root folder
try { try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null); Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -384,6 +373,7 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER); mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
@ -400,11 +390,11 @@ public class GTaskManager {
} }
} }
// 同步通话记录文件夹 // for call-note folder
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)", c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] { new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER) String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null); }, null);
if (c != null) { if (c != null) {
if (c.moveToNext()) { if (c.moveToNext()) {
@ -414,6 +404,8 @@ public class GTaskManager {
mGTaskHashMap.remove(gid); mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER); mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
if (!node.getName().equals( if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE)) + GTaskStringUtils.FOLDER_CALL_NOTE))
@ -432,7 +424,7 @@ public class GTaskManager {
} }
} }
// 同步本地现有文件夹 // for local existing folders
try { try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] { "(type=? AND parent_id<>?)", new String[] {
@ -449,8 +441,10 @@ public class GTaskManager {
syncType = node.getSyncAction(c); syncType = node.getSyncAction(c);
} else { } else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) { if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE; syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else { } else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL; syncType = Node.SYNC_ACTION_DEL_LOCAL;
} }
} }
@ -466,7 +460,7 @@ public class GTaskManager {
} }
} }
// 同步远程添加的文件夹 // for remote add folders
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator(); Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next(); Map.Entry<String, TaskList> entry = iter.next();
@ -482,7 +476,6 @@ public class GTaskManager {
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
} }
// 执行内容同步操作
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -517,17 +510,18 @@ public class GTaskManager {
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_UPDATE_CONFLICT: case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
updateRemoteNode(node, c); updateRemoteNode(node, c);
break; break;
case Node.SYNC_ACTION_NONE: case Node.SYNC_ACTION_NONE:
break; break;
case Node.SYNC_ACTION_ERROR: case Node.SYNC_ACTION_ERROR:
default: default:
throw new ActionFailureException("unknown sync action type"); throw new ActionFailureException("unkown sync action type");
} }
} }
// 添加本地节点
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -555,6 +549,7 @@ public class GTaskManager {
if (note.has(NoteColumns.ID)) { if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID); long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) { if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
note.remove(NoteColumns.ID); note.remove(NoteColumns.ID);
} }
} }
@ -567,6 +562,8 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) { if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID); long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) { if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
data.remove(DataColumns.ID); data.remove(DataColumns.ID);
} }
} }
@ -587,22 +584,26 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
} }
// create the local node
sqlNote.setGtaskId(node.getGid()); sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false); sqlNote.commit(false);
// update gid-nid mapping
mGidToNid.put(node.getGid(), sqlNote.getId()); mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid()); mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
// 更新本地节点
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote;
// update the note locally
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent()); sqlNote.setContent(node.getLocalJSONFromContent());
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid()) Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
@ -614,10 +615,10 @@ public class GTaskManager {
sqlNote.setParentId(parentId.longValue()); sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true); sqlNote.commit(true);
// update meta info
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
// 添加远程节点
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -626,6 +627,7 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
Node n; Node n;
// update remotely
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = new Task(); Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent()); task.setContentByLocalJSON(sqlNote.getContent());
@ -640,10 +642,12 @@ public class GTaskManager {
GTaskClient.getInstance().createTask(task); GTaskClient.getInstance().createTask(task);
n = (Node) task; n = (Node) task;
// add meta
updateRemoteMeta(task.getGid(), sqlNote); updateRemoteMeta(task.getGid(), sqlNote);
} else { } else {
TaskList tasklist = null; TaskList tasklist = null;
// we need to skip folder if it has already existed
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX; String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER) if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT; folderName += GTaskStringUtils.FOLDER_DEFAULT;
@ -667,6 +671,7 @@ public class GTaskManager {
} }
} }
// no match we can add now
if (tasklist == null) { if (tasklist == null) {
tasklist = new TaskList(); tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent()); tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -676,16 +681,17 @@ public class GTaskManager {
n = (Node) tasklist; n = (Node) tasklist;
} }
// update local note
sqlNote.setGtaskId(n.getGid()); sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false); sqlNote.commit(false);
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
// gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
// 更新远程节点
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -693,11 +699,14 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c); SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
node.setContentByLocalJSON(sqlNote.getContent()); node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node); GTaskClient.getInstance().addUpdateNode(node);
// update meta
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
if (sqlNote.isNoteType()) { if (sqlNote.isNoteType()) {
Task task = (Task) node; Task task = (Task) node;
TaskList preParentList = task.getParent(); TaskList preParentList = task.getParent();
@ -716,11 +725,11 @@ public class GTaskManager {
} }
} }
// clear local modified flag
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
} }
// 更新远程元数据
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
@ -737,12 +746,12 @@ public class GTaskManager {
} }
} }
// 刷新本地同步ID
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
} }
// get the latest gtask list
mGTaskHashMap.clear(); mGTaskHashMap.clear();
mGTaskListHashMap.clear(); mGTaskListHashMap.clear();
mMetaHashMap.clear(); mMetaHashMap.clear();
@ -781,13 +790,11 @@ public class GTaskManager {
} }
} }
// 获取同步账户名称
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }
// 取消同步
public void cancelSync() { public void cancelSync() {
mCancelled = true; mCancelled = true;
} }
} }

@ -24,28 +24,24 @@ import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
// 广播操作类型
public final static String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
// 同步操作类型常量
public final static int ACTION_START_SYNC = 0; public final static int ACTION_START_SYNC = 0;
public final static int ACTION_CANCEL_SYNC = 1; public final static int ACTION_CANCEL_SYNC = 1;
public final static int ACTION_INVALID = 2; 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_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_IS_SYNCING = "isSyncing";
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg"; public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
// 同步任务实例
private static GTaskASyncTask mSyncTask = null; private static GTaskASyncTask mSyncTask = null;
// 同步进度信息
private static String mSyncProgress = ""; private static String mSyncProgress = "";
// 开始同步
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -60,20 +56,17 @@ public class GTaskSyncService extends Service {
} }
} }
// 取消同步
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
} }
} }
// 服务创建时调用
@Override @Override
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
// 处理启动命令
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
@ -93,7 +86,6 @@ public class GTaskSyncService extends Service {
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
// 低内存时调用
@Override @Override
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) {
@ -101,12 +93,10 @@ public class GTaskSyncService extends Service {
} }
} }
// 返回绑定的IBinder对象
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
// 发送广播
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -115,7 +105,6 @@ public class GTaskSyncService extends Service {
sendBroadcast(intent); sendBroadcast(intent);
} }
// 静态方法,用于启动同步
public static void startSync(Activity activity) { public static void startSync(Activity activity) {
GTaskManager.getInstance().setActivityContext(activity); GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class); Intent intent = new Intent(activity, GTaskSyncService.class);
@ -123,20 +112,17 @@ public class GTaskSyncService extends Service {
activity.startService(intent); activity.startService(intent);
} }
// 静态方法,用于取消同步
public static void cancelSync(Context context) { public static void cancelSync(Context context) {
Intent intent = new Intent(context, GTaskSyncService.class); Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);
} }
// 静态方法,用于检查是否正在同步
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }
// 静态方法,用于获取同步进度信息
public static String getProgressString() { public static String getProgressString() {
return mSyncProgress; return mSyncProgress;
} }
} }

@ -13,9 +13,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
<<<<<<< HEAD
//test
package net.micode.notes.ui;
=======
package net.micode.notes.ui; package net.micode.notes.ui;
>>>>>>> ea0ba46500536be46ebbdf4516f38b38518ccdaa
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.Context; import android.content.Context;

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 186 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 606 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 194 KiB

@ -18,8 +18,8 @@
<FrameLayout <FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="fill_parent"> android:layout_height="fill_parent"
<!-- android:background="@drawable/list_background">--> android:background="@drawable/list_background">
<LinearLayout <LinearLayout
android:layout_width="fill_parent" android:layout_width="fill_parent"

@ -36,16 +36,4 @@
<item <item
android:id="@+id/menu_search" android:id="@+id/menu_search"
android:title="@string/menu_search"/> android:title="@string/menu_search"/>
<item
android:id="@+id/menu_graygoo"
android:title="@string/menu_graygoo"/>
<item
android:id="@+id/menu_miku"
android:title="@string/menu_miku"/>
<item
android:id="@+id/menu_hutao"
android:title="@string/menu_hutao"/>
</menu> </menu>

@ -39,10 +39,6 @@
<string name="file_path">/MIUI/notes/</string> <string name="file_path">/MIUI/notes/</string>
<string name="file_name_txt_format">notes_%s.txt</string> <string name="file_name_txt_format">notes_%s.txt</string>
<!-- notes list string --> <!-- notes list string -->
<string name="menu_graygoo">Background: graygoo</string>
<string name="menu_miku">Background: miku</string>
<string name="menu_hutao">Background: hutao</string>
<string name="format_folder_files_count">(%d)</string> <string name="format_folder_files_count">(%d)</string>
<string name="menu_create_folder">New Folder</string> <string name="menu_create_folder">New Folder</string>
<string name="menu_export_text">Export text</string> <string name="menu_export_text">Export text</string>

Loading…
Cancel
Save