pull/10/head
fangzheng 7 hours ago
parent 061de96ae5
commit 642fba3a05

@ -1,203 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import java.io.IOException;
/**
* 便便
*
*/
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {
// 提醒的便签ID
private long mNoteId;
// 便签内容摘要(用于提醒对话框展示)
private String mSnippet;
// 摘要最大显示长度(超出部分用省略号处理)
private static final int SNIPPET_PREW_MAX_LEN = 60;
// 媒体播放器,用于播放闹钟声音
MediaPlayer mPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 去除标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
final Window win = getWindow();
// 允许在锁屏时显示窗口
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// 如果屏幕处于关闭状态,添加额外窗口标志:保持屏幕常亮、点亮屏幕、允许锁屏时显示、布局适配
if (!isScreenOn()) {
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
}
// 获取启动当前Activity的Intent由AlarmReceiver传递
Intent intent = getIntent();
try {
// 从Intent的Data中解析便签IDData格式为content://.../notes/{id}取路径的第2段
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));
// 通过便签ID获取内容摘要用于提醒展示
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);
// 处理摘要长度:超过最大长度时截断并添加省略提示
mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
: mSnippet;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
}
// 初始化媒体播放器
mPlayer = new MediaPlayer();
// 检查便签是否存在且可见(未被删除)
if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) {
// 显示提醒对话框
showActionDialog();
// 播放闹钟声音
playAlarmSound();
} else {
// 便签不存在则直接结束活动
finish();
}
}
/**
*
* @return truefalse
*/
private boolean isScreenOn() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
return pm.isScreenOn();
}
/**
*
*/
private void playAlarmSound() {
// 获取系统默认闹钟铃声的Uri
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
// 获取系统静音模式影响的音频流(判断闹钟是否被静音)
int silentModeStreams = Settings.System.getInt(getContentResolver(),
Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);
// 设置媒体播放器的音频流类型:若闹钟流被静音模式影响,则使用该流;否则默认使用闹钟流
if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
mPlayer.setAudioStreamType(silentModeStreams);
} else {
mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
try {
// 设置铃声数据源并准备播放
mPlayer.setDataSource(this, url);
mPlayer.prepare();
// 设置为循环播放(直到用户操作停止)
mPlayer.setLooping(true);
mPlayer.start();
} catch (IllegalArgumentException | SecurityException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
/**
* 便
*/
private void showActionDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
// 设置对话框标题为应用名称(小米便签)
dialog.setTitle(R.string.app_name);
// 显示便签摘要内容
dialog.setMessage(mSnippet);
// 确定按钮:关闭提醒(默认行为)
dialog.setPositiveButton(R.string.notealert_ok, this);
// 若屏幕亮着,添加“进入”按钮(跳转到便签编辑页)
if (isScreenOn()) {
dialog.setNegativeButton(R.string.notealert_enter, this);
}
// 显示对话框,并设置消失监听(用于停止铃声)
dialog.show().setOnDismissListener(this);
}
/**
*
* @param dialog
* @param which BUTTON_POSITIVE/BUTTON_NEGATIVE
*/
public void onClick(DialogInterface dialog, int which) {
switch (which) {
// 点击“进入”按钮:跳转到便签编辑页查看完整内容
case DialogInterface.BUTTON_NEGATIVE:
Intent intent = new Intent(this, NoteEditActivity.class);
intent.setAction(Intent.ACTION_VIEW); // 动作:查看便签
intent.putExtra(Intent.EXTRA_UID, mNoteId); // 传递便签ID
startActivity(intent);
break;
// 点击“确定”按钮:默认不做额外操作,对话框消失后会停止铃声并结束活动
default:
break;
}
}
/**
*
* @param dialog
*/
public void onDismiss(DialogInterface dialog) {
stopAlarmSound();
finish();
}
/**
*
*/
private void stopAlarmSound() {
if (mPlayer != null) {
mPlayer.stop(); // 停止播放
mPlayer.release(); // 释放资源
mPlayer = null;
}
}
}

@ -1,100 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便
* 便
* 便
*/
public class AlarmInitReceiver extends BroadcastReceiver {
/**
* 便ID
*
*/
private static final String [] PROJECTION = new String [] {
NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE // 提醒时间戳
};
// 字段索引常量用于快速访问Cursor中的数据
private static final int COLUMN_ID = 0; // 便签ID在投影中的索引
private static final int COLUMN_ALERTED_DATE = 1; // 提醒时间在投影中的索引
/**
* 广
* 便AlarmManager
* @param context
* @param intent 广
*/
@Override
public void onReceive(Context context, Intent intent) {
// 获取当前系统时间,用于筛选未过期的提醒
long currentDate = System.currentTimeMillis();
// 查询数据库中所有未过期的便签提醒
// 条件:提醒时间 > 当前时间 且 便签类型为普通便签TYPE_NOTE
Cursor c = context.getContentResolver().query(
Notes.CONTENT_NOTE_URI, // 查询的内容URI指向便签表
PROJECTION, // 需要查询的字段
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,
new String[] { String.valueOf(currentDate) }, // 筛选条件参数(当前时间)
null // 排序方式(无需排序)
);
if (c != null) {
// 遍历查询结果,为每个未过期的提醒注册闹钟
if (c.moveToFirst()) {
do {
// 获取便签的提醒时间
long alertDate = c.getLong(COLUMN_ALERTED_DATE);
// 创建触发提醒时的意图指向AlarmReceiver
Intent sender = new Intent(context, AlarmReceiver.class);
// 为意图附加便签ID便于后续定位具体便签
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(COLUMN_ID)));
// 创建延迟执行的PendingIntent用于触发提醒
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, 0, sender, 0);
// 获取AlarmManager服务用于设置系统闹钟
AlarmManager alermManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// 注册闹钟在指定时间alertDate唤醒设备并发送广播
// RTC_WAKEUP模式确保在设备休眠时也能触发
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);
} while (c.moveToNext()); // 继续处理下一个便签
}
// 关闭Cursor释放资源
c.close();
}
}
}

@ -1,46 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* 便广广
* 便
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
* 广
* @param context Activity
* @param intent 便便ID
*/
@Override
public void onReceive(Context context, Intent intent) {
// 将意图的目标组件设置为AlarmAlertActivity便签提醒展示界面
// 确保广播中携带的便签信息如Data中的便签ID被传递给目标界面
intent.setClass(context, AlarmAlertActivity.class);
// 添加FLAG_ACTIVITY_NEW_TASK标志在BroadcastReceiver中启动Activity必须设置此标志
// 因为BroadcastReceiver本身没有任务栈需要为启动的Activity创建新任务栈
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// 启动AlarmAlertActivity展示便签提醒对话框并播放铃声
context.startActivity(intent);
}
}

@ -1,576 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import net.micode.notes.R;
import android.content.Context;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
/**
*
* 便12/24
*/
public class DateTimePicker extends FrameLayout {
// 默认启用状态
private static final boolean DEFAULT_ENABLE_STATE = true;
// 时间计算常量定义
private static final int HOURS_IN_HALF_DAY = 12; // 半天的小时数
private static final int HOURS_IN_ALL_DAY = 24; // 一天的小时数
private static final int DAYS_IN_ALL_WEEK = 7; // 一周的天数
private static final int DATE_SPINNER_MIN_VAL = 0; // 日期选择器最小值
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1; // 日期选择器最大值
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0; // 24小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23; // 24小时制小时最大值
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1; // 12小时制小时最小值
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12; // 12小时制小时最大值
private static final int MINUT_SPINNER_MIN_VAL = 0; // 分钟选择器最小值
private static final int MINUT_SPINNER_MAX_VAL = 59; // 分钟选择器最大值
private static final int AMPM_SPINNER_MIN_VAL = 0; // 上下午选择器最小值
private static final int AMPM_SPINNER_MAX_VAL = 1; // 上下午选择器最大值
// 选择器组件
private final NumberPicker mDateSpinner; // 日期选择器(显示近一周日期)
private final NumberPicker mHourSpinner; // 小时选择器
private final NumberPicker mMinuteSpinner; // 分钟选择器
private final NumberPicker mAmPmSpinner; // 上下午选择器12小时制用
private Calendar mDate; // 日期时间计算工具
// 日期显示值数组(存储近一周的日期文本)
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
// 时间状态变量
private boolean mIsAm; // 是否为上午12小时制
private boolean mIs24HourView; // 是否为24小时制显示
private boolean mIsEnabled = DEFAULT_ENABLE_STATE; // 组件是否启用
private boolean mInitialising; // 是否处于初始化状态
// 日期时间变更监听器
private OnDateTimeChangedListener mOnDateTimeChangedListener;
/**
*
*
*/
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
// 计算日期偏移量并更新
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);
updateDateControl();
onDateTimeChanged();
}
};
/**
*
* 23012/24
*/
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
if (!mIs24HourView) {
// 12小时制处理跨天情况如11PM到12AM需加一天12AM到11PM需减一天
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
// 12点和11点切换时切换上下午状态
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}
} else {
// 24小时制处理跨天情况如23点到0点加一天0点到23点减一天
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
// 更新小时并触发事件
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();
// 若日期变更,同步更新年月日
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
}
};
/**
*
* 5901
*/
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
// 判断是否跨小时59->0加1小时0->59减1小时
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
if (offset != 0) {
// 调整小时并更新相关控件
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
updateDateControl();
// 更新上下午状态12小时制
int newHour = getCurrentHourOfDay();
if (newHour >= HOURS_IN_HALF_DAY) {
mIsAm = false;
} else {
mIsAm = true;
}
updateAmPmControl();
}
// 更新分钟并触发事件
mDate.set(Calendar.MINUTE, newVal);
onDateTimeChanged();
}
};
/**
*
* /12
*/
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
// 切换上下午时调整小时上午转下午加12小时反之减12小时
if (mIsAm) {
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {
mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY);
}
updateAmPmControl();
onDateTimeChanged();
}
};
/**
*
*
*/
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
}
/**
* 使使12/24
* @param context
*/
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}
/**
* 使使12/24
* @param context
* @param date
*/
public DateTimePicker(Context context, long date) {
this(context, date, DateFormat.is24HourFormat(context));
}
/**
* 使
* @param context
* @param date
* @param is24HourView 使24
*/
public DateTimePicker(Context context, long date, boolean is24HourView) {
super(context);
mDate = Calendar.getInstance();
mInitialising = true;
mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; // 初始化上下午状态
// 加载布局
inflate(context, R.layout.datetime_picker, this);
// 初始化日期选择器
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
mDateSpinner.setOnValueChangedListener(mOnDateChangedListener);
// 初始化小时选择器
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
// 初始化分钟选择器
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100); // 长按更新间隔(毫秒)
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
// 初始化上下午选择器使用系统本地化的AM/PM文本
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// 更新控件到初始状态
updateDateControl();
updateHourControl();
updateAmPmControl();
// 设置时间格式12/24小时制
set24HourView(is24HourView);
// 设置初始时间
setCurrentDate(date);
// 设置启用状态
setEnabled(isEnabled());
// 初始化完成
mInitialising = false;
}
/**
*
* @param enabled
*/
@Override
public void setEnabled(boolean enabled) {
if (mIsEnabled == enabled) {
return;
}
super.setEnabled(enabled);
mDateSpinner.setEnabled(enabled);
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled;
}
/**
*
* @return
*/
@Override
public boolean isEnabled() {
return mIsEnabled;
}
/**
*
* @return
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}
/**
*
* @param date
*/
public void setCurrentDate(long date) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date);
setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
}
/**
*
* @param year
* @param month 0-11
* @param dayOfMonth
* @param hourOfDay 240-23
* @param minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}
/**
*
* @return
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
/**
*
* @param year
*/
public void setCurrentYear(int year) {
if (!mInitialising && year == getCurrentYear()) {
return;
}
mDate.set(Calendar.YEAR, year);
updateDateControl();
onDateTimeChanged();
}
/**
* 0-11
* @return
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}
/**
*
* @param month 0-11
*/
public void setCurrentMonth(int month) {
if (!mInitialising && month == getCurrentMonth()) {
return;
}
mDate.set(Calendar.MONTH, month);
updateDateControl();
onDateTimeChanged();
}
/**
*
* @return
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}
/**
*
* @param dayOfMonth
*/
public void setCurrentDay(int dayOfMonth) {
if (!mInitialising && dayOfMonth == getCurrentDay()) {
return;
}
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateDateControl();
onDateTimeChanged();
}
/**
* 240-23
* @return
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}
/**
* 12/24
* @return
*/
private int getCurrentHour() {
if (mIs24HourView){
return getCurrentHourOfDay();
} else {
int hour = getCurrentHourOfDay();
// 12小时制转换13->10->12
if (hour > HOURS_IN_HALF_DAY) {
return hour - HOURS_IN_HALF_DAY;
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
}
}
}
/**
* 24
* @param hourOfDay 0-23
*/
public void setCurrentHour(int hourOfDay) {
if (!mInitialising && hourOfDay == getCurrentHourOfDay()) {
return;
}
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
if (!mIs24HourView) {
// 12小时制处理更新上下午状态和小时显示值
if (hourOfDay >= HOURS_IN_HALF_DAY) {
mIsAm = false;
if (hourOfDay > HOURS_IN_HALF_DAY) {
hourOfDay -= HOURS_IN_HALF_DAY;
}
} else {
mIsAm = true;
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
}
}
updateAmPmControl();
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
}
/**
*
* @return
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}
/**
*
* @param minute 0-59
*/
public void setCurrentMinute(int minute) {
if (!mInitialising && minute == getCurrentMinute()) {
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);
onDateTimeChanged();
}
/**
* 24
* @return 24
*/
public boolean is24HourView () {
return mIs24HourView;
}
/**
* 24/12
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
// 24小时制隐藏上下午选择器12小时制显示
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);
int hour = getCurrentHourOfDay();
updateHourControl();
setCurrentHour(hour);
updateAmPmControl();
}
/**
* .
*/
private void updateDateControl() {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(mDate.getTimeInMillis());
// 计算起始日期当前日期减去3天用于显示近一周
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
mDateSpinner.setDisplayedValues(null);
// 生成近一周的日期文本
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
cal.add(Calendar.DAY_OF_YEAR, 1);
mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
}
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); // 默认选中当前日期
mDateSpinner.invalidate();
}
/**
* 12
*/
private void updateAmPmControl() {
if (mIs24HourView) {
mAmPmSpinner.setVisibility(View.GONE);
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}
}
/**
* 12/24
*/
private void updateHourControl() {
if (mIs24HourView) {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}
}
/**
*
* @param callback
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {
mOnDateTimeChangedListener = callback;
}
/**
*
*/
private void onDateTimeChanged() {
if (mOnDateTimeChangedListener != null) {
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}

@ -1,137 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import java.util.Calendar;
import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
/**
* 便
* AlertDialogDateTimePicker
*/
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
// 用于维护当前选中的日期时间
private Calendar mDate = Calendar.getInstance();
// 是否采用24小时制显示时间
private boolean mIs24HourView;
// 日期时间选择完成后的回调监听器由调用者实现如NoteEditActivity
private OnDateTimeSetListener mOnDateTimeSetListener;
// 自定义的日期时间选择器视图,负责用户选择交互
private DateTimePicker mDateTimePicker;
/**
*
* "确定"
*/
public interface OnDateTimeSetListener {
void OnDateTimeSet(AlertDialog dialog, long date);
}
/**
*
* @param context NoteEditActivity
* @param date 便
*/
public DateTimePickerDialog(Context context, long date) {
super(context);
// 初始化自定义的日期时间选择器
mDateTimePicker = new DateTimePicker(context);
// 将选择器设置为对话框的内容视图
setView(mDateTimePicker);
// 为日期时间选择器设置变化监听器:当用户选择的日期或时间变化时触发
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
// 更新内部维护的日期时间
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
// 根据新选择的时间更新对话框标题
updateTitle(mDate.getTimeInMillis());
}
});
// 设置初始日期时间(忽略秒数,确保提醒时间精确到分钟)
mDate.setTimeInMillis(date);
mDate.set(Calendar.SECOND, 0);
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
// 设置对话框按钮:"确定"按钮触发onClick方法"取消"按钮不执行操作
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
// 根据系统设置初始化24小时制显示模式
set24HourView(DateFormat.is24HourFormat(this.getContext()));
// 初始化对话框标题为初始日期时间
updateTitle(mDate.getTimeInMillis());
}
/**
* 24/12
* @param is24HourView true24false12
*/
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}
/**
*
* @param callBack OnDateTimeSetListenerActivity
*/
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}
/**
*
* @param date
*/
private void updateTitle(long date) {
// 定义日期时间的显示格式:包含年、月、日、时间
int flag = DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME;
// 根据24小时制模式调整显示格式
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_12HOUR;
// 格式化时间并设置为对话框标题
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}
/**
* "确定"
*
*/
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
// 回调传递选中的时间(毫秒级时间戳)
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -1,92 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
/**
* 便
*
*/
public class DropdownMenu {
// 触发下拉菜单的按钮
private Button mButton;
// 系统提供的弹出式菜单组件,负责显示下拉选项
private PopupMenu mPopupMenu;
// 菜单容器,存储从资源文件加载的菜单项
private Menu mMenu;
/**
*
* @param context 访
* @param button
* @param menuId IDres/menu
*/
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button;
// 设置按钮背景为下拉图标(箭头图标)
mButton.setBackgroundResource(R.drawable.dropdown_icon);
// 初始化PopupMenu绑定到触发按钮
mPopupMenu = new PopupMenu(context, mButton);
// 获取菜单容器
mMenu = mPopupMenu.getMenu();
// 从资源文件加载菜单项到菜单容器
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
// 设置按钮点击事件:点击时显示下拉菜单
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
});
}
/**
*
* @param listener
*/
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
/**
* ID
* @param id ID
* @return MenuItem
*/
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
/**
*
* @param title "已选择3项"
*/
public void setTitle(CharSequence title) {
mButton.setText(title);
}
}

@ -1,130 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
/**
* 便便
* CursorAdapter
*/
public class FoldersListAdapter extends CursorAdapter {
/**
*
* IDSNIPPET
*/
public static final String [] PROJECTION = {
NoteColumns.ID, // 文件夹ID
NoteColumns.SNIPPET // 文件夹名称(小米便签中文件夹名称存储在此字段)
};
/**
* Cursor
*/
public static final int ID_COLUMN = 0; // PROJECTION中ID字段的索引
public static final int NAME_COLUMN = 1; // PROJECTION中SNIPPET名称字段的索引
/**
*
* @param context Activity
* @param c
*/
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
/**
*
* @param context
* @param cursor 使
* @param parent ListView
* @return FolderListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
}
/**
*
* @param view FolderListItem
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
// 处理根文件夹的特殊名称根文件夹ID为Notes.ID_ROOT_FOLDER显示为“移动到父文件夹”
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
// 将文件夹名称绑定到列表项视图
((FolderListItem) view).bind(folderName);
}
}
/**
*
* @param context
* @param position
* @return
*/
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
// 根文件夹特殊处理其他文件夹直接取SNIPPET字段值
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
/**
* LinearLayout
*/
private class FolderListItem extends LinearLayout {
private TextView mName; // 用于显示文件夹名称的文本控件
/**
*
* @param context
*/
public FolderListItem(Context context) {
super(context);
// 加载文件夹列表项的布局文件folder_list_item.xml
inflate(context, R.layout.folder_list_item, this);
// 获取布局中的文本控件,用于显示文件夹名称
mName = (TextView) findViewById(R.id.tv_folder_name);
}
/**
*
* @param name
*/
public void bind(String name) {
mName.setText(name);
}
}
}

File diff suppressed because it is too large Load Diff

@ -1,288 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.graphics.Rect;
import android.text.Layout;
import android.text.Selection;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.URLSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.widget.EditText;
import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
/**
* 便EditText便
*
*/
public class NoteEditText extends EditText {
private static final String TAG = "NoteEditText";
// 当前输入框在多输入框列表中的索引(用于区分不同输入框)
private int mIndex;
// 记录删除键按下前的光标起始位置(用于判断是否删除当前输入框)
private int mSelectionStartBeforeDelete;
// 支持的链接协议常量
private static final String SCHEME_TEL = "tel:" ; // 电话协议(如"tel:10086"
private static final String SCHEME_HTTP = "http:" ; // 网页协议(如"http://www.micode.net"
private static final String SCHEME_EMAIL = "mailto:" ; // 邮件协议(如"mailto:test@micode.net"
// 链接协议与对应菜单资源的映射(用于上下文菜单显示对应操作文字)
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();
static {
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); // 电话链接对应"拨打"菜单
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); // 网页链接对应"打开网页"菜单
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); // 邮件链接对应"发送邮件"菜单
}
/**
* {@link NoteEditActivity}
*/
public interface OnTextViewChangeListener {
/**
*
* @param index
* @param text
*/
void onEditTextDelete(int index, String text);
/**
*
* @param index +1
* @param text
*/
void onEditTextEnter(int index, String text);
/**
*
* @param index
* @param hasText /
*/
void onTextChange(int index, boolean hasText);
}
// 文本变化监听器实例由NoteEditActivity设置
private OnTextViewChangeListener mOnTextViewChangeListener;
/**
*
* @param context NoteEditActivity
*/
public NoteEditText(Context context) {
super(context, null);
mIndex = 0; // 默认索引为0
}
/**
*
* @param index
*/
public void setIndex(int index) {
mIndex = index;
}
/**
* NoteEditActivity
* @param listener OnTextViewChangeListener
*/
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {
mOnTextViewChangeListener = listener;
}
/**
* +
* @param context
* @param attrs
*/
public NoteEditText(Context context, AttributeSet attrs) {
super(context, attrs, android.R.attr.editTextStyle);
}
/**
* ++
* @param context
* @param attrs
* @param defStyle
*/
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
/**
*
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 计算触摸点在文本中的实际坐标(扣除内边距并加上滚动偏移)
int x = (int) event.getX();
int y = (int) event.getY();
x -= getTotalPaddingLeft();
y -= getTotalPaddingTop();
x += getScrollX();
y += getScrollY();
// 根据坐标获取对应的文本行和偏移量,设置光标位置
Layout layout = getLayout();
int line = layout.getLineForVertical(y); // 触摸点所在的文本行
int off = layout.getOffsetForHorizontal(line, x); // 行内的水平偏移(光标位置)
Selection.setSelection(getText(), off); // 设置光标
break;
}
return super.onTouchEvent(event);
}
/**
*
* @param keyCode KEYCODE_DELKEYCODE_ENTER
* @param event
* @return
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_ENTER:
// 回车键事件由onKeyUp处理此处返回false让事件继续传递
if (mOnTextViewChangeListener != null) {
return false;
}
break;
case KeyEvent.KEYCODE_DEL:
// 记录删除键按下前的光标起始位置,用于判断是否需要删除输入框
mSelectionStartBeforeDelete = getSelectionStart();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
/**
*
* @param keyCode
* @param event
* @return
*/
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch(keyCode) {
case KeyEvent.KEYCODE_DEL:
if (mOnTextViewChangeListener != null) {
// 若光标在起始位置且不是第一个输入框,通知删除当前输入框
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());
return true;
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
break;
case KeyEvent.KEYCODE_ENTER:
if (mOnTextViewChangeListener != null) {
// 处理回车键:将光标后的文本移至新输入框
int selectionStart = getSelectionStart();
String text = getText().subSequence(selectionStart, length()).toString(); // 光标后文本
setText(getText().subSequence(0, selectionStart)); // 保留光标前文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); // 通知新增输入框
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");
}
break;
default:
break;
}
return super.onKeyUp(keyCode, event);
}
/**
*
* @param focused
* @param direction
* @param previouslyFocusedRect
*/
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if (mOnTextViewChangeListener != null) {
// 失去焦点且文本为空时,通知无文本;否则通知有文本
if (!focused && TextUtils.isEmpty(getText())) {
mOnTextViewChangeListener.onTextChange(mIndex, false);
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);
}
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
/**
*
* @param menu
*/
@Override
protected void onCreateContextMenu(ContextMenu menu) {
// 仅处理富文本中的链接
if (getText() instanceof Spanned) {
int selStart = getSelectionStart();
int selEnd = getSelectionEnd();
int min = Math.min(selStart, selEnd);
int max = Math.max(selStart, selEnd);
// 获取选中区域内的链接
final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);
if (urls.length == 1) { // 仅处理单个链接的情况
int defaultResId = 0;
// 识别链接协议,匹配对应的菜单资源
for(String schema: sSchemaActionResMap.keySet()) {
if(urls[0].getURL().indexOf(schema) >= 0) {
defaultResId = sSchemaActionResMap.get(schema);
break;
}
}
// 未匹配到已知协议时,使用默认菜单文本
if (defaultResId == 0) {
defaultResId = R.string.note_link_other;
}
// 向菜单添加链接操作项,点击后触发链接的默认行为(如拨号、打开浏览器)
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(
new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
urls[0].onClick(NoteEditText.this); // 触发URLSpan的点击事件
return true;
}
});
}
}
super.onCreateContextMenu(menu);
}
}

@ -1,319 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
/**
* 便便UI
*/
public class NoteItemData {
// 数据库查询的列名数组,对应便签表的核心字段
static final String [] PROJECTION = new String [] {
NoteColumns.ID, // 便签ID
NoteColumns.ALERTED_DATE, // 提醒时间
NoteColumns.BG_COLOR_ID, // 背景色ID
NoteColumns.CREATED_DATE, // 创建时间
NoteColumns.HAS_ATTACHMENT, // 是否有附件
NoteColumns.MODIFIED_DATE, // 修改时间
NoteColumns.NOTES_COUNT, // 文件夹包含的便签数量(仅文件夹类型有效)
NoteColumns.PARENT_ID, // 父文件夹ID
NoteColumns.SNIPPET, // 内容摘要(文件夹名或便签内容片段)
NoteColumns.TYPE, // 类型(便签/文件夹/系统文件夹)
NoteColumns.WIDGET_ID, // 桌面插件ID
NoteColumns.WIDGET_TYPE, // 桌面插件类型
};
// 上述PROJECTION数组中各列的索引常量用于从Cursor中提取数据
private static final int ID_COLUMN = 0; // 便签ID索引
private static final int ALERTED_DATE_COLUMN = 1; // 提醒时间索引
private static final int BG_COLOR_ID_COLUMN = 2; // 背景色ID索引
private static final int CREATED_DATE_COLUMN = 3; // 创建时间索引
private static final int HAS_ATTACHMENT_COLUMN = 4; // 是否有附件索引
private static final int MODIFIED_DATE_COLUMN = 5; // 修改时间索引
private static final int NOTES_COUNT_COLUMN = 6; // 文件夹便签数量索引
private static final int PARENT_ID_COLUMN = 7; // 父文件夹ID索引
private static final int SNIPPET_COLUMN = 8; // 内容摘要索引
private static final int TYPE_COLUMN = 9; // 类型索引
private static final int WIDGET_ID_COLUMN = 10; // 桌面插件ID索引
private static final int WIDGET_TYPE_COLUMN = 11; // 桌面插件类型索引
// 便签核心数据字段
private long mId; // 便签唯一ID
private long mAlertDate; // 提醒时间(毫秒时间戳)
private int mBgColorId; // 背景色ID对应资源文件
private long mCreatedDate; // 创建时间(毫秒时间戳)
private boolean mHasAttachment; // 是否有附件(如图片等)
private long mModifiedDate; // 最后修改时间(毫秒时间戳)
private int mNotesCount; // 文件夹包含的便签数量(仅文件夹类型使用)
private long mParentId; // 所属文件夹ID
private String mSnippet; // 内容摘要(文件夹名或便签内容的简短展示)
private int mType; // 类型Notes.TYPE_NOTE便签TYPE_FOLDER文件夹等
private int mWidgetId; // 关联的桌面插件ID无则为无效值
private int mWidgetType; // 桌面插件类型(无则为无效值)
private String mName; // 通话记录便签的联系人姓名(非通话记录则为空)
private String mPhoneNumber; // 通话记录便签的电话号码(非通话记录则为空)
// 列表位置属性用于UI背景样式适配
private boolean mIsLastItem; // 是否为列表最后一项
private boolean mIsFirstItem; // 是否为列表第一项
private boolean mIsOnlyOneItem; // 是否为列表中唯一一项
private boolean mIsOneNoteFollowingFolder; // 是否为文件夹后的唯一便签项
private boolean mIsMultiNotesFollowingFolder; // 是否为文件夹后的多个便签项之一
/**
* 便
* @param context
* @param cursor 便
*/
public NoteItemData(Context context, Cursor cursor) {
// 从游标中提取核心数据字段
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = cursor.getLong(CREATED_DATE_COLUMN);
mHasAttachment = (cursor.getInt(HAS_ATTACHMENT_COLUMN) > 0) ? true : false;
mModifiedDate = cursor.getLong(MODIFIED_DATE_COLUMN);
mNotesCount = cursor.getInt(NOTES_COUNT_COLUMN);
mParentId = cursor.getLong(PARENT_ID_COLUMN);
mSnippet = cursor.getString(SNIPPET_COLUMN);
// 移除检查列表标记(用于纯文本展示)
mSnippet = mSnippet.replace(NoteEditActivity.TAG_CHECKED, "").replace(
NoteEditActivity.TAG_UNCHECKED, "");
mType = cursor.getInt(TYPE_COLUMN);
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
// 处理通话记录便签:提取电话号码并关联联系人姓名
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) { // 若属于通话记录文件夹
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber); // 获取联系人姓名
if (mName == null) {
mName = mPhoneNumber; // 无联系人时显示电话号码
}
}
}
if (mName == null) {
mName = "";
}
// 计算当前项在列表中的位置属性
checkPostion(cursor);
}
/**
* UI
* @param cursor
*/
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false; // 是否为最后一项
mIsFirstItem = cursor.isFirst() ? true : false; // 是否为第一项
mIsOnlyOneItem = (cursor.getCount() == 1); // 是否为唯一一项
// 初始化文件夹后便签的位置属性
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
// 若当前是便签项且不是第一项,检查前一项是否为文件夹
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) { // 移动到前一项
// 前一项是文件夹或系统文件夹
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
// 若游标总数大于当前位置+1说明文件夹后有多个便签
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;
} else {
// 否则文件夹后只有当前一个便签
mIsOneNoteFollowingFolder = true;
}
}
// 移回原位置,避免游标错乱
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
/**
* 便
*/
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
/**
* 便
*/
public boolean isMultiFollowingFolder() {
return mIsMultiNotesFollowingFolder;
}
/**
*
*/
public boolean isLast() {
return mIsLastItem;
}
/**
* 便
*/
public String getCallName() {
return mName;
}
/**
*
*/
public boolean isFirst() {
return mIsFirstItem;
}
/**
*
*/
public boolean isSingle() {
return mIsOnlyOneItem;
}
/**
* 便ID
*/
public long getId() {
return mId;
}
/**
*
*/
public long getAlertDate() {
return mAlertDate;
}
/**
*
*/
public long getCreatedDate() {
return mCreatedDate;
}
/**
*
*/
public boolean hasAttachment() {
return mHasAttachment;
}
/**
*
*/
public long getModifiedDate() {
return mModifiedDate;
}
/**
* ID
*/
public int getBgColorId() {
return mBgColorId;
}
/**
* ID
*/
public long getParentId() {
return mParentId;
}
/**
* 便
*/
public int getNotesCount() {
return mNotesCount;
}
/**
* IDgetParentId
*/
public long getFolderId () {
return mParentId;
}
/**
* 便//
*/
public int getType() {
return mType;
}
/**
*
*/
public int getWidgetType() {
return mWidgetType;
}
/**
* ID
*/
public int getWidgetId() {
return mWidgetId;
}
/**
* 便
*/
public String getSnippet() {
return mSnippet;
}
/**
* >0
*/
public boolean hasAlert() {
return (mAlertDate > 0);
}
/**
* 便
*/
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
/**
* 便
* @param cursor
* @return 便Notes.TYPE_NOTE
*/
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}

File diff suppressed because it is too large Load Diff

@ -1,259 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
/**
* 便便
* CursorAdapterCursor便
*/
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter";
private Context mContext; // 上下文对象
private HashMap<Integer, Boolean> mSelectedIndex; // 存储选中项的位置和状态
private int mNotesCount; // 便签总数(不包含文件夹)
private boolean mChoiceMode; // 是否处于选择模式
/**
*
*
*/
public static class AppWidgetAttribute {
public int widgetId; // 插件ID
public int widgetType; // 插件类型
};
/**
*
* @param context
*/
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context;
mNotesCount = 0;
}
/**
*
* @param context
* @param cursor
* @param parent
* @return NotesListItem
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
}
/**
*
* @param view
* @param context
* @param cursor
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
// 从游标中解析便签数据
NoteItemData itemData = new NoteItemData(context, cursor);
// 绑定数据到视图,设置选择模式和选中状态
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
/**
*
* @param position
* @param checked
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged(); // 通知列表刷新
}
/**
*
* @return
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/**
*
* @param mode
*/
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear(); // 清除选中状态
mChoiceMode = mode;
}
/**
* 便便
* @param checked
*/
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
// 仅处理类型为普通便签的项
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
}
}
}
/**
* ID
* @return IDHashSet
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
// 过滤根文件夹ID不应被选中
if (id == Notes.ID_ROOT_FOLDER) {
Log.d(TAG, "Wrong item id, should not happen");
} else {
itemSet.add(id);
}
}
}
return itemSet;
}
/**
*
* @return HashSet
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
if (c != null) {
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);
// 注意:此处不关闭游标,游标由适配器管理
} else {
Log.e(TAG, "Invalid cursor");
return null;
}
}
}
return itemSet;
}
/**
*
* @return
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
return 0;
}
Iterator<Boolean> iter = values.iterator();
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
count++;
}
}
return count;
}
/**
* 便
* @return
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
}
/**
*
* @param position
* @return
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
}
return mSelectedIndex.get(position);
}
/**
* 便
*/
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
}
/**
* 便
* @param cursor
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
}
/**
* 便
*/
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
Cursor c = (Cursor) getItem(i);
if (c != null) {
// 仅统计类型为普通便签的项
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
}
}
}

@ -1,169 +0,0 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
/**
* 便
* 便
*/
public class NotesListItem extends LinearLayout {
private ImageView mAlert; // 提醒图标(显示闹钟或通话记录图标)
private TextView mTitle; // 标题/内容文本(显示便签内容、文件夹名称等)
private TextView mTime; // 时间文本(显示最后修改时间)
private TextView mCallName; // 通话记录联系人名称(仅通话记录便签显示)
private NoteItemData mItemData; // 当前项对应的数据模型
private CheckBox mCheckBox; // 多选模式下的复选框
/**
*
* @param context
*/
public NotesListItem(Context context) {
super(context);
// 加载列表项布局文件
inflate(context, R.layout.note_item, this);
// 绑定UI控件
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
/**
*
* @param context
* @param data 便
* @param choiceMode
* @param checked
*/
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
// 处理多选模式:仅普通便签显示复选框并同步选中状态
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
mCheckBox.setVisibility(View.GONE);
}
mItemData = data;
// 处理通话记录文件夹(特殊系统文件夹)
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 显示文件夹名称和包含的便签数量
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record); // 显示通话记录图标
// 处理通话记录文件夹下的便签
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName()); // 显示联系人名称
mTitle.setTextAppearance(context, R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); // 显示便签内容片段
// 显示提醒图标(如有)
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
// 处理普通文件夹和普通便签
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
// 普通文件夹:显示名称和包含的便签数量
if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
// 普通便签:显示内容片段和提醒状态
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
// 显示最后修改时间(相对时间格式,如"1小时前"
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
// 设置项背景样式
setBackground(data);
}
/**
* 便
* @param data 便
*/
private void setBackground(NoteItemData data) {
int bgColorId = data.getBgColorId(); // 获取背景色ID
// 普通便签:根据位置(首项/末项/单项等)设置不同背景
if (data.getType() == Notes.TYPE_NOTE) {
if (data.isSingle() || data.isOneFollowingFolder()) {
// 单项或文件夹后的唯一便签
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(bgColorId));
} else if (data.isLast()) {
// 列表中的最后一项
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(bgColorId));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
// 首项或文件夹后的多个便签中的第一项
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(bgColorId));
} else {
// 中间项
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(bgColorId));
}
} else {
// 文件夹:使用固定的文件夹背景
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
/**
*
* @return 便
*/
public NoteItemData getItemData() {
return mItemData;
}
}

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