Compare commits

...

6 Commits

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

@ -0,0 +1,159 @@
/*
* 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;//引入notes.ui开发包
//以下import各种库文件后续需要使用
import android.app.Activity;//导入Activity包
import android.app.AlertDialog;//弹出警告对话框
import android.content.Context;//提供了有关应用程序的全局信息
//content主要是和数据库进行交互,对数据库进行增删改查操作
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;//调用以上三个类及一些android库函数
public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener {//继承拓展Activity类并实现两个接口
private long mNoteId;//声明存储在数据库中的便签ID号
private String mSnippet; //闹钟提示的文本内容
private static final int SNIPPET_PREW_MAX_LEN = 60;//声明文本摘要的最大长度为60
MediaPlayer mPlayer;//实例化一个多媒体播放器
@Override
protected void onCreate(Bundle savedInstanceState) {//重写onCreate方法
super.onCreate(savedInstanceState);//使用super调用父类的onCreate函数
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);//当使用这个flag时,window manager会报告插入window的矩形大小
}
Intent intent = getIntent();//通过getIntent()获得的Intent用于开启Activity
try {//语句块:异常处理,当要程序出现错误时可以不中断继续运行下去
mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1));//获取便签ID
mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId);//根据上一行获取的ID号来从数据库中读取该ID号的内容
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)) {//由该便签的id从数据库中获取其类型判断是否为需要提醒的便签
showActionDialog();//弹出对话框
playAlarmSound();//播放闹钟提示音
} else {
finish();//结束闹钟动作
}
}
private boolean isScreenOn() {//判断是否出现在屏幕上
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);//获得PowerManager的实例
return pm.isScreenOn();//判断屏幕是否打开
}
private void playAlarmSound() {//播放提示音
Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);//调用系统的铃声管理URI得到闹钟提示音
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);//设置播放器的数据源url
mPlayer.prepare();//进行播放器的准备
mPlayer.setLooping(true);//设置播放器循环播放
mPlayer.start();//开始播放
} catch (IllegalArgumentException e) {//异常处理:非法参数异常
// TODO Auto-generated catch block
e.printStackTrace();//打印出详细的异常信息,异常名称
} catch (SecurityException e) {//安全异常
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {//非法状态异常
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {//输入输出异常
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showActionDialog() {//显示提示框
AlertDialog.Builder dialog = new AlertDialog.Builder(this);//新建一个对话框
dialog.setTitle(R.string.app_name);//为对话框设置标题
dialog.setMessage(mSnippet);//设置对话框文本内容
dialog.setPositiveButton(R.string.notealert_ok, this);//设置“OK”按钮
if (isScreenOn()) {//若屏幕为开启状态
dialog.setNegativeButton(R.string.notealert_enter, this);//对话框添加不成功按钮
}
dialog.show().setOnDismissListener(this);//将对话框展示出来,并且设置一个监听器用来取消对话框
}
public void onClick(DialogInterface dialog, int which) {//根据点击执行对话框任务
switch (which) {
case DialogInterface.BUTTON_NEGATIVE://取消操作
Intent intent = new Intent(this, NoteEditActivity.class);//实现与NoteEditActivity类之间的数据传输
intent.setAction(Intent.ACTION_VIEW);//设置动作的属性
intent.putExtra(Intent.EXTRA_UID, mNoteId);//附加便签的id
startActivity(intent);//开始动作
break;
default:
break;
}
}
public void onDismiss(DialogInterface dialog) {//提示框消失事件处理
stopAlarmSound();//停止响铃
finish();
}
private void stopAlarmSound() {//关闭闹钟铃音
if (mPlayer != null) {//如果播放器仍然存在
mPlayer.stop();//停止播放
mPlayer.release();//释放
mPlayer = null;//清空播放器资源
}
}
}

@ -0,0 +1,65 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//提醒关于许可证使用的相关问题
package net.micode.notes.ui;
import android.app.AlarmManager;//引入闹钟提醒包
import android.app.PendingIntent;
import android.content.BroadcastReceiver;//监听开机广播
import android.content.ContentUris;//内容链接
import android.content.Context;//文本
import android.content.Intent;
import android.database.Cursor;//目的和光标
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;//便签栏
public class AlarmInitReceiver extends BroadcastReceiver {//实现接受闹铃启动消息的功能
private static final String [] PROJECTION = new String [] {//声明PROJECTION每个元素包括id和提醒日期
NoteColumns.ID,
NoteColumns.ALERTED_DATE
};
private static final int COLUMN_ID = 0;
private static final int COLUMN_ALERTED_DATE = 1;//设定ID和闹钟信息的初始值
@Override
public void onReceive(Context context, Intent intent) {//接收广播后的处理过程
long currentDate = System.currentTimeMillis();//通过系统函数获了当前时间存入currentDate变量。
Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI,//通过查找数据库中的标签内容,找到和当前系统时间相等的标签
PROJECTION,
NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE,//获取的时间如果大于设置的时间的提醒项目
new String[] { String.valueOf(currentDate) },
null);//类型转换将long类型的currentDate转变为String类
if (c != null) {
if (c.moveToFirst()) {//游标移动到开始位置
do {
long alertDate = c.getLong(COLUMN_ALERTED_DATE);//获取要提醒的日期
Intent sender = new Intent(context, AlarmReceiver.class);//新建一个intent类来指向alarmreceiver 来传输数据
sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));//设置数据为便签的uri和id
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0);//创建一个广播组件,可以在手机广播栏显示相应内容
AlarmManager alermManager = (AlarmManager) context//新建系统的闹钟服务
.getSystemService(Context.ALARM_SERVICE);
alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent);//设置一系列需要传输的数据
} while (c.moveToNext());//游标移动到下一位置
}
c.close();//关闭游标
}
}
}

@ -0,0 +1,30 @@
/*
* 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;//接收广播并启动 AlarmAlertActivity类
import android.content.Context;//环境
import android.content.Intent;//文本意向
public class AlarmReceiver extends BroadcastReceiver {//闹钟接收器,继承自广播接收器
@Override
public void onReceive(Context context, Intent intent) {//重载Onreceive()方法,实现对广播的侦听,由此实现对接受闹铃启动消息的功能
intent.setClass(context, AlarmAlertActivity.class);//从当前的Intent启动AlarmAlertActivity即组件之间的跳转
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//为该intent添加flag使其加入一个新的task栈中
context.startActivity(intent);//使用intent启动Activity
}
}

@ -0,0 +1,485 @@
/*
* 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;//引入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;//数字选择器
public class DateTimePicker extends FrameLayout {//继承FrameLayout类时间日期选择器
private static final boolean DEFAULT_ENABLE_STATE = true;
//以下设置时间参数与变量
private static final int HOURS_IN_HALF_DAY = 12;//半天12小时
private static final int HOURS_IN_ALL_DAY = 24;//一整天24小时
private static final int DAYS_IN_ALL_WEEK = 7;//一周七天
private static final int DATE_SPINNER_MIN_VAL = 0;//日期循环最小值为0
private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;//日期轮转最大值为6
private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;//24小时制小时最小值为0
private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;//24小时制小时最大值为23
private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;//12小时制最小为1
private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;//12小时制最大为12
private static final int MINUT_SPINNER_MIN_VAL = 0;//分钟数最小值为0
private static final int MINUT_SPINNER_MAX_VAL = 59;//分钟数最大值为59
private static final int AMPM_SPINNER_MIN_VAL = 0;//上午开始为0
private static final int AMPM_SPINNER_MAX_VAL = 1;//下午开始标志为1
private final NumberPicker mDateSpinner;//初始化控件
private final NumberPicker mHourSpinner;//数字选择器,用于让用户输入数值
private final NumberPicker mMinuteSpinner;//定义一个分钟挂件
private final NumberPicker mAmPmSpinner;//定义一个上下午转轮
private Calendar mDate;//定义一个日历类型的日期变量
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];//定义一个展示时间的字符串
private boolean mIsAm;//设置日期改变的监听器
private boolean mIs24HourView;//是否以24小时查看时间
private boolean mIsEnabled = DEFAULT_ENABLE_STATE;//变量表示是否已开启
private boolean mInitialising;//判断是否初始化
private OnDateTimeChangedListener mOnDateTimeChangedListener;//日期变化监听器
private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() {//监听日期变化传送给mDate并进行同步更新操作
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {//重写监听日期的变化语句
mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal);//根据日期新旧值,改变日历
updateDateControl();//更新日期控制
onDateTimeChanged();//监听日期时间变化
}
};
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {//以小时为单位的监听器
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {//小时变化进行更新,天数变化进行更新
boolean isDateChanged = false;//默认日期没有变化
Calendar cal = Calendar.getInstance();//创建一个日历
if (!mIs24HourView) {//不是24小时制
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {//对于12小时制11点和12点进行交替时的操作
cal.setTimeInMillis(mDate.getTimeInMillis());//将参数的值作为系统时间
cal.add(Calendar.DAY_OF_YEAR, 1);//日期值加1
isDateChanged = true;//日期变化标志置为true
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {// 在凌晨12时变化到前一天夜晚11时的时候
cal.setTimeInMillis(mDate.getTimeInMillis());//设定日期
cal.add(Calendar.DAY_OF_YEAR, -1);//日期值减1
isDateChanged = true;
}
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {//对于12小时制对am 和pm的操作
mIsAm = !mIsAm;//上下午标志转换
updateAmPmControl();//更新上下午标志
}
} else {
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {//对于24小时制时晚上11点和12点交替时对日期的更改
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);//日期值加1
isDateChanged = true;
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {//这里是对于12小时制时凌晨11点和12点交替时对日期的更改
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
}
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);//获取当前时间并转化为小时制
mDate.set(Calendar.HOUR_OF_DAY, newHour);
onDateTimeChanged();//设置新的小时数
if (isDateChanged) {//如果日期发生变化则设置新日期
setCurrentYear(cal.get(Calendar.YEAR));
setCurrentMonth(cal.get(Calendar.MONTH));
setCurrentDay(cal.get(Calendar.DAY_OF_MONTH));
}
}
};
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {//对分钟时间进行监听,并根据变化做出修改
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {//数值改变更新函数
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;//设置offset初始值为0
if (oldVal == maxValue && newVal == minValue) {//分钟数从最大变到最小
offset += 1;//加一
} else if (oldVal == minValue && newVal == maxValue) {//分钟数从最小变到最大
offset -= 1;//减一
}
if (offset != 0) {//如果存在时间偏移量,对时间进行修改
mDate.add(Calendar.HOUR_OF_DAY, offset);//修改小时数
mHourSpinner.setValue(getCurrentHour());//获取当前时间来确定小时轮转数
updateDateControl();
int newHour = getCurrentHourOfDay();//得到现在的小时数来决定是否修改am或是pm
if (newHour >= HOURS_IN_HALF_DAY) {//如果现在的时间大于或者等于12就设置为pm
mIsAm = false;
updateAmPmControl();
} else {//新时间在12点前为am
mIsAm = true;
updateAmPmControl();
}
}
mDate.set(Calendar.MINUTE, newVal);//更新分钟数
onDateTimeChanged();//监听时间变化
}
};
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {//监听上下午变化的监听器
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {//监听am与pm变化
mIsAm = !mIsAm;
if (mIsAm) {//下午变到上午小时数减12
mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY);
} else {//上午变到下午小时数加12
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);
}
public DateTimePicker(Context context) {
this(context, System.currentTimeMillis());
}//访问数据库,获取系统时间
public DateTimePicker(Context context, long date) {//将获得的系统时间转化为我们需要的数据
this(context, date, DateFormat.is24HourFormat(context));
}
public DateTimePicker(Context context, long date, boolean is24HourView) {//选择时间
super(context);
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);//设置监听长按时间间隔为100ms
mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener);
String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();//对24小时下的am与pm各属性值进行初始化
mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);//显示设置上下午的视图
mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);//设置组件最小值属性为上下午编码最小值
mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);
mAmPmSpinner.setDisplayedValues(stringsForAmPm);//设置显示上下午字符串的值
mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener);
// update controls to initial state
updateDateControl();//更新日期控制使其为初态
updateHourControl();//更新小时控制使其为初态
updateAmPmControl();//更新上下午控制使其为初态
set24HourView(is24HourView);//设置24小时制
// set to current time
setCurrentDate(date);//设置当前日期
setEnabled(isEnabled());//设置其使能值
// set the content descriptions
mInitialising = false;//表示初始化已经结束
}
@Override
public void setEnabled(boolean enabled) {//将转轮设置为使能状态
if (mIsEnabled == enabled) {//如果已经在使能状态,则返回
return;
}
super.setEnabled(enabled);
mDateSpinner.setEnabled(enabled);//分别对四个分部件设置使能
mMinuteSpinner.setEnabled(enabled);
mHourSpinner.setEnabled(enabled);
mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled;//修改使能标志变量
}
@Override
public boolean isEnabled() {
return mIsEnabled;
}//判断时间日期选择器是否处于使能状态
/**
* Get the current date in millis
*
* @return the current date in millis
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}//得到当前的秒数
/**
* Set the current date
*
* @param date The current date in millis
*/
public void setCurrentDate(long date) {//设置当前的时间参数是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));
}//设置当前日期
/**
* Set the current date
*
* @param year The current year
* @param month The current month
* @param dayOfMonth The current dayOfMonth
* @param hourOfDay The current hourOfDay
* @param minute The current minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {//设置当前的时间,参数是年月日、小时和分钟数
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}//获取当前年、月、日、时、分、12/24表示、AM/PM表示并修改
/**
* Get current year
*
* @return The current year
*/
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}//获取当前的年份
/**
* Set current year
*
* @param year The current year
*/
public void setCurrentYear(int year) {//设置当前年份
if (!mInitialising && year == getCurrentYear()) {//如果当前的年份是正确的并且已经初始化了,那么不需要在来设置年份
return;
}
mDate.set(Calendar.YEAR, year);//修改年份
updateDateControl();//更新日期控制
onDateTimeChanged();//监听时间日期的改变
}
/**
* Get current month in the year
*
* @return The current month in the year
*/
public int getCurrentMonth() {
return mDate.get(Calendar.MONTH);
}//获取当前月份
/**
* Set current month in the year
*
* @param month The month in the year
*/
public void setCurrentMonth(int month) {//设置当前月份
if (!mInitialising && month == getCurrentMonth()) {//若输入月份等于当前月份则不做修改
return;
}
mDate.set(Calendar.MONTH, month);//修改月份
updateDateControl();//更新控制日期
onDateTimeChanged();
}
/**
* Get current day of the month
*
* @return The day of the month
*/
public int getCurrentDay() {
return mDate.get(Calendar.DAY_OF_MONTH);
}//获取当前日期
/**
* Set current day of the month
*
* @param dayOfMonth The day of the month
*/
public void setCurrentDay(int dayOfMonth) {//设置当前日期
if (!mInitialising && dayOfMonth == getCurrentDay()) {//若输入日期等于当前日期则不做修改
return;
}
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);//修改日期
updateDateControl();
onDateTimeChanged();
}
/**
* Get current hour in 24 hour mode, in the range (0~23)
* @return The current hour in 24 hour mode
*/
public int getCurrentHourOfDay() {
return mDate.get(Calendar.HOUR_OF_DAY);
}//获取24小时下的小时数
private int getCurrentHour() {//获取当前小时数
if (mIs24HourView){//24小时下
return getCurrentHourOfDay();//返回24小时制的小时数
} else {//返回12小时制的小时数
int hour = getCurrentHourOfDay();
if (hour > HOURS_IN_HALF_DAY) {//与之前标注一样
return hour - HOURS_IN_HALF_DAY;
} else {
return hour == 0 ? HOURS_IN_HALF_DAY : hour;
}
}
}
/**
* Set current hour in 24 hour mode, in the range (0~23)
*
* @param hourOfDay
*/
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) {//如果大于12点
mIsAm = false;//pm
if (hourOfDay > HOURS_IN_HALF_DAY) {//晚上11点到第二天更改小时数
hourOfDay -= HOURS_IN_HALF_DAY;
}
} else {
mIsAm = true;
if (hourOfDay == 0) {
hourOfDay = HOURS_IN_HALF_DAY;
}
}
updateAmPmControl();
}
mHourSpinner.setValue(hourOfDay);
onDateTimeChanged();
}
/**
* Get currentMinute
*
* @return The Current Minute
*/
public int getCurrentMinute() {
return mDate.get(Calendar.MINUTE);
}//获取当前分钟数
/**
* Set current minute
*/
public void setCurrentMinute(int minute) {//设置当前分钟数
if (!mInitialising && minute == getCurrentMinute()) {//输入分钟数等于当前分钟数则不做修改
return;
}
mMinuteSpinner.setValue(minute);
mDate.set(Calendar.MINUTE, minute);//修改分钟数
onDateTimeChanged();
}
/**
* @return true if this is in 24 hour view else false.
*/
public boolean is24HourView () {
return mIs24HourView;
}//判断是否为24小时视图
/**
* Set whether in 24 hour or AM/PM mode.
*
* @param is24HourView True for 24 hour mode. False for AM/PM mode.
*/
public void set24HourView(boolean is24HourView) {//设置24小时视图
if (mIs24HourView == is24HourView) {
return;
}
mIs24HourView = is24HourView;
mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE);//如果是12小时制则显示上午还是下午
int hour = getCurrentHourOfDay();//定义hour为当前24小时下的小时数
updateHourControl();//更新小时操作
setCurrentHour(hour);//设置小时数
updateAmPmControl();//更新am和pm操作
}
private void updateDateControl() {//更新日期控制
Calendar cal = Calendar.getInstance();//获取当前日期实例
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);//加一天
mDateSpinner.setDisplayedValues(null);
for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {//循环当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();//使日期转轮失效
}
private void updateAmPmControl() {//更新上下午的控制
if (mIs24HourView) {//24小时视图下
mAmPmSpinner.setVisibility(View.GONE);//使上下午转轮不可见
} else {
int index = mIsAm ? Calendar.AM : Calendar.PM;//判断当前是上午还是下午
mAmPmSpinner.setValue(index);//设置上下午转轮的值
mAmPmSpinner.setVisibility(View.VISIBLE);//使上下午转轮可见
}
}
private void updateHourControl() {//更新小时控制
if (mIs24HourView) {//根据当前小时制设置时间
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW);//设置最小轮转为24小时
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW);//设置最大轮转为24小时
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);//设置最小轮转为12小时
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
*/
public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) {//根据参数设置时间日期监听器
mOnDateTimeChangedListener = callback;
}
private void onDateTimeChanged() {//监听日期时间变化
if (mOnDateTimeChangedListener != null) {//输入年月日时分秒
mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(),
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}

@ -0,0 +1,90 @@
/*
* 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;//引入ui包
import java.util.Calendar;//导入日历工具包
import net.micode.notes.R;//引入R包
import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;//日期选择器
import android.app.AlertDialog;//日期选择的对话框
import android.content.Context;
import android.content.DialogInterface;//对话框界面
import android.content.DialogInterface.OnClickListener;//点击监听器
import android.text.format.DateFormat;
import android.text.format.DateUtils;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {//时间日期选择器对话框
private Calendar mDate = Calendar.getInstance();//声明一个calendar类的对象用于操作日期
private boolean mIs24HourView;//判断当前设置是否为24小时模式
private OnDateTimeSetListener mOnDateTimeSetListener;//声明一个日期设置监听控件
private DateTimePicker mDateTimePicker;//声明日期选择器,运行时会产生数字的选择列表
public interface OnDateTimeSetListener {//设置一个接口当时期时间设置时进行的操作
void OnDateTimeSet(AlertDialog dialog, long date);//设置时间监听器
}
public DateTimePickerDialog(Context context, long date) {//实例化数字选择器对话框
super(context);//申请一个数字选择器
mDateTimePicker = new DateTimePicker(context);//为数字选择器申请一个子视图
setView(mDateTimePicker);//为日期时间选择器设置日期时间改变的监听器
mDateTimePicker.setOnDateTimeChangedListener(new OnDateTimeChangedListener() {//设置时间改变监听器
public void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute) {//将视图中的各选项设置为系统当前时间
mDate.set(Calendar.YEAR, year);//将year设置为mNote的年份
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);//将秒数设置为0
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());//根据从mdate中获取的当前时间设置现有时间
setButton(context.getString(R.string.datetime_dialog_ok), this);//设置按钮
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);//设置取消按钮
set24HourView(DateFormat.is24HourFormat(this.getContext()));//设置为24小时显示
updateTitle(mDate.getTimeInMillis());//更新标题时间
}
public void set24HourView(boolean is24HourView) {
mIs24HourView = is24HourView;
}//设置24小时视图
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {//设置一个时期时间设置的监听器
mOnDateTimeSetListener = callBack;//回收日期监听器
}
private void updateTitle(long date) {//根据时间更新标题
int flag =//通过DataUtils按照24时制显示
DateUtils.FORMAT_SHOW_YEAR |//根据date和显示格式设置标题
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;//是否为24小时
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));//设置标题
}
public void onClick(DialogInterface arg0, int arg1) {//arg0接收到点击事件的对话框arg1是该对话框上的按钮
if (mOnDateTimeSetListener != null) {//设置日期时间
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}
}

@ -0,0 +1,61 @@
/*
* 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;//导入ui包
import android.content.Context;//引入需要使用的Context、Menu等包
import android.view.Menu;
import android.view.MenuItem;//菜单条款
import android.view.View;
import android.view.View.OnClickListener;//监听点击
import android.widget.Button;//导入按钮工具
import android.widget.PopupMenu;//弹出菜单
import android.widget.PopupMenu.OnMenuItemClickListener;//菜单点击监听器
import net.micode.notes.R;
public class DropdownMenu {//声明一个下拉菜单
private Button mButton;//定义按钮控件
private PopupMenu mPopupMenu;//定义弹出式菜单
private Menu mMenu;//定义菜单
public DropdownMenu(Context context, Button button, int menuId) {//设置显示一个菜单
mButton = button;//设置按钮样式
mButton.setBackgroundResource(R.drawable.dropdown_icon);//设置其背景资源为下拉菜单的图标
mPopupMenu = new PopupMenu(context, mButton);//实例化一个弹出式菜单
mMenu = mPopupMenu.getMenu();//获得弹出式菜单的菜单项
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);//获得弹出式菜单的菜单项
mButton.setOnClickListener(new OnClickListener() {//当我们点击mButton时会弹出菜单
public void onClick(View v) {
mPopupMenu.show();
}//设点击显示菜单
});
}
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {//置下拉菜单的点击监听方法
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);//对非空的菜单的具体条目设置监听
}
}
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}//对于菜单选项的初始化,根据索引搜索菜单需要的选项
public void setTitle(CharSequence title) {
mButton.setText(title);
}//根据索引搜索菜单需要的选项
}

@ -0,0 +1,80 @@
/*
* 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;//导入ui包
//以下导入各种包
import android.content.Context;
import android.database.Cursor;//光标
import android.view.View;
import android.view.ViewGroup;//视图组
import android.widget.CursorAdapter;//光标适配器
import android.widget.LinearLayout;
import android.widget.TextView;//文本视图
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;//便签栏
public class FoldersListAdapter extends CursorAdapter {//文件夹列表配适器,用于显示文件夹的列表
public static final String [] PROJECTION = {//调用数据库中便签的ID和片段
NoteColumns.ID,
NoteColumns.SNIPPET
};
public static final int ID_COLUMN = 0;//定义常量文件夹ID栏编号
public static final int NAME_COLUMN = 1;//初始化常量NAME
public FoldersListAdapter(Context context, Cursor c) {//调用父类的构造函数
super(context, c);//引用父类方法
// TODO Auto-generated constructor stub
}//构造函数调用父类的构造器将c中的数据传输进该context
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {//创建一个文件夹并初始化子文件夹标签
return new FolderListItem(context);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {//将各个布局文件绑定起来
if (view instanceof FolderListItem) {//判断视图是否是文件夹列表的一项
String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);//移动对方的文件夹
((FolderListItem) view).bind(folderName);//绑定文件夹视图
}
}
public String getFolderName(Context context, int position) {//根据数据库中标签的ID得到标签的各项内容
Cursor cursor = (Cursor) getItem(position);//获取当前游标
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context//返回当前文件夹的名字
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);//获取对方的文件夹
}
private class FolderListItem extends LinearLayout {//设置文件夹项目列表的名称
private TextView mName;
public FolderListItem(Context context) {//文件夹项的构造函数
super(context);//操作数据库
inflate(context, R.layout.folder_list_item, this);//根据布局文件的名字等信息将其找出来
mName = (TextView) findViewById(R.id.tv_folder_name);//根据ID寻找文件的名字等信息
}
public void bind(String name) {
mName.setText(name);
}//绑定文件夹名称
}
}

@ -0,0 +1,932 @@
/*
* 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;//导入ui包
import android.app.Activity;
import android.app.AlarmManager;//安卓系统应用开发
import android.app.AlertDialog;// 闹钟管理器
import android.app.PendingIntent;
import android.app.SearchManager;//搜索管理器
import android.appwidget.AppWidgetManager;//App工具管理器
import android.content.ContentUris;//内容
import android.content.Context;//背景
import android.content.DialogInterface;//对话框界面
import android.content.Intent;//内容意图
import android.content.SharedPreferences;//内容偏好共享
import android.graphics.Paint;//引入绘画包
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;//偏好管理
import android.text.Spannable;//可跨度文本
import android.text.SpannableString;
import android.text.TextUtils;//文本单元
import android.text.format.DateUtils;//日期形式
import android.text.style.BackgroundColorSpan;//背景颜色风格
import android.util.Log;//日志工具
import android.view.LayoutInflater;//布局视图
import android.view.Menu;//菜单视图
import android.view.MenuItem;//菜单条款
import android.view.MotionEvent;//动态事件
import android.view.View;
import android.view.View.OnClickListener;//针对标签标记的设置,继承了许多有关监听的类
import android.view.WindowManager;//窗口管理
import android.widget.CheckBox;
import android.widget.CompoundButton;//合成按钮
import android.widget.CompoundButton.OnCheckedChangeListener;//变化监听器
import android.widget.EditText;
import android.widget.ImageView;//图像
import android.widget.LinearLayout;//线性布局
import android.widget.TextView;//文本视图
import android.widget.Toast;
import net.micode.notes.R;
import net.micode.notes.data.Notes;//便签数据
import net.micode.notes.data.Notes.TextNote;//小米便签文本
import net.micode.notes.model.WorkingNote;//便签运行模型
import net.micode.notes.model.WorkingNote.NoteSettingChangedListener;//便签设置变化监听器
import net.micode.notes.tool.DataUtils;//数据单元
import net.micode.notes.tool.ResourceParser;//资源解析器
import net.micode.notes.tool.ResourceParser.TextAppearanceResources;//文本资源显示
import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener;//日期设置监听器
import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener;//文本变化监听器
import net.micode.notes.widget.NoteWidgetProvider_2x;//便签宽度为2X
import net.micode.notes.widget.NoteWidgetProvider_4x;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {//继承Activity,实现了便签的编辑功能,同时对三个监听接口的方法进行实现
private class HeadViewHolder {//创建一个类用于显示文本与图片
public TextView tvModified;//当前文本视图
public ImageView ivAlertIcon;//提醒的图标
public TextView tvAlertDate;//设置的提醒的时间
public ImageView ibSetBgColor;//设置背景颜色
}
private static final Map<Integer, Integer> sBgSelectorBtnsMap = new HashMap<Integer, Integer>();//运用Hashmap类将颜色按钮和对应的资源解析器中的相应颜色关联
static {//对HashMap进行初始化主要是颜色的对应
sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);//黄
sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED);//红
sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);//蓝
sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN);//绿
sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);//白
}//各种颜色的对应
private static final Map<Integer, Integer> sBgSelectorSelectionMap = new HashMap<Integer, Integer>();//实现资源解析器中的颜色ID与背景颜色选择选择按钮已选择对应
static {
sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select);//将资源剖析器与选择器相连
sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select);
sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select);
sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select);
sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select);
}//提供了一个用户选择主界面颜色的功能
private static final Map<Integer, Integer> sFontSizeBtnsMap = new HashMap<Integer, Integer>();//将字体的大小与相对应的选择相连接
static {//提供各种大小字体的选择
sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE);//大
sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL);//小
sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM);//普通
sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER);//超大
}
private static final Map<Integer, Integer> sFontSelectorSelectionMap = new HashMap<Integer, Integer>();//实现资源解析器中字号ID与字体大小按钮已选择对应
static {//选择字体大小的界面
sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select);
sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select);
}
private static final String TAG = "NoteEditActivity";//编辑文本的activity
private HeadViewHolder mNoteHeaderHolder;//设置头部布局
private View mHeadViewPanel;//对表头的操作
private View mNoteBgColorSelector;//便签的背景色选择器
private View mFontSizeSelector;//便签的字体大小选择器
private EditText mNoteEditor;//便签编辑器
private View mNoteEditorPanel;//文本编辑控制板
private WorkingNote mWorkingNote;//对模板WorkingNote的初始化
private SharedPreferences mSharedPrefs;//私有化SharedPreferences的数据存储方式
private int mFontSizeId;//操作字体大小
private static final String PREFERENCE_FONT_SIZE = "pref_font_size";//字体大小设置
private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;//设置标题最大长度为10
public static final String TAG_CHECKED = String.valueOf('\u221A');//定义final字符串表明已标记
public static final String TAG_UNCHECKED = String.valueOf('\u25A1');//定义final字符串表明未标记
private LinearLayout mEditTextList;//线性布局,用于编辑文本
private String mUserQuery;//用户请求
private Pattern mPattern;//正则表达式模式
@Override
protected void onCreate(Bundle savedInstanceState) {//在界面创建时会调用的函数,用于在创建这样一个窗口时进行自定义操作
super.onCreate(savedInstanceState);//调用父类的onCreate()方法
this.setContentView(R.layout.note_edit);//设置活动的显示布局
if (savedInstanceState == null && !initActivityState(getIntent())) {
finish();
return;
}//如果未保存实例状态且当前Activity未初始化完成则结束当前Activity
initResources();//初始化资源
}
/**
* Current activity may be killed when the memory is low. Once it is killed, for another time
* user load this activity, we should restore the former state
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {//保存当前界面状态
super.onRestoreInstanceState(savedInstanceState);//调用父类函数
if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) {//如果保存了关闭前的实例状态且其中包含着便签标识符则将该标识符添加到初始化Activity的Intent中
Intent intent = new Intent(Intent.ACTION_VIEW);//新建一个intent
intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID));//利用此前的extra_uid初始化一个intent
if (!initActivityState(intent)) {//初始化活动状态失败则结束Activity
finish();
return;
}
Log.d(TAG, "Restoring from killed activity");//记录操作信息到日志中
}
}
private boolean initActivityState(Intent intent) {//初始化活动状态
/**
* If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
* then jump to the NotesListActivity
*///如果找不到便签则返回NotesListActivity并报错“便签不存在”//
mWorkingNote = null;// 初始化便签数据
if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {//触摸动作的原始32位信息包括事件的动作触控点信息
long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);//获取到便签id
mUserQuery = "";//
/**
* Starting from the searched result
*/
if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {//若intent中含有搜索的数据
noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));//获取便签ID
mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);//将用户请求的字符串保存在变量mUserQuery中
}
if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {//如果在数据库中查找不到
Intent jump = new Intent(this, NotesListActivity.class);//设置Intent目的组件为NotesListActivity
startActivity(jump);
showToast(R.string.error_note_not_exist);//设置Intent目的组件为NotesListActivity
finish();
return false;
} else {
mWorkingNote = WorkingNote.load(this, noteId);//加载对应id的便签项
if (mWorkingNote == null) {//如果活动便签为空,显示错误信息
Log.e(TAG, "load note failed with note id" + noteId);//导出信息失败
finish();
return false;
}
}
getWindow().setSoftInputMode(//设置软键盘输入模式
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN//将软键盘输入进行隐藏
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);//使Edit界面适应软键盘弹出
} else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {//通过 getAction得到的字符串来决定做什么
// New note
long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0);//获取intent中传入的父文件夹id默认为0
int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);//获取布局文件id默认返回参数为无效参数
int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE,
Notes.TYPE_WIDGET_INVALIDE);//获取布局文件类型,默认为无效参数
int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID,
ResourceParser.getDefaultBgId(this));//获取背景颜色资源id默认为随机背景色
// Parse call-record note
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);//解析电话簿记录
long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);//获取提醒时间默认为0
if (callDate != 0 && phoneNumber != null) {//如果通话日期与号码均存在
if (TextUtils.isEmpty(phoneNumber)) {//如果记录的通话号码为空,则显示警告
Log.w(TAG, "The call record number is null");
}
long noteId = 0;//这里根据获取到的电话号字符串从数据库中获取相应的noteid
if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(),
phoneNumber, callDate)) > 0) {//通过通话号码和通话日期在数据库中查找noteId
mWorkingNote = WorkingNote.load(this, noteId);//导入这个便签
if (mWorkingNote == null) {//noteId对应的内容为空输出报错信息返回错误初始化失败
Log.e(TAG, "load call note failed with note id" + noteId);
finish();
return false;
}
} else {//将电话号码与手机的号码簿相关
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId,
widgetType, bgResId);//没有查找到noteId信息则重新建立空便签使用之前默认参量对便签进行初始化
mWorkingNote.convertToCallNote(phoneNumber, callDate);//将便签转化为通话记录便签
}
} else {//将电话号码与手机的号码簿相关
mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType,
bgResId);//创建一个空的便签来进行操作
}
getWindow().setSoftInputMode(//键盘输入设置
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} else {
Log.e(TAG, "Intent not specified action, should not support");//打印错误信息
finish();
return false;
}
mWorkingNote.setOnSettingStatusChangedListener(this);//为这个便签设置一个设置变化的监听器
return true;//返回true表示初始化该Activity成功
}
@Override
protected void onResume() {
super.onResume();//进行重新返回的函数
initNoteScreen();//初始化便签屏幕
}
private void initNoteScreen() {//对界面进行初始化的操作
mNoteEditor.setTextAppearance(this, TextAppearanceResources
.getTexAppearanceResource(mFontSizeId));//根据字体大小设置便签编辑器的文本格式
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果便签的模式为清单模式
switchToListMode(mWorkingNote.getContent());//转移到列表的模式
} else {//不为清单列表界面,继续执行
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));//设置文本为高亮显示的搜索结果
mNoteEditor.setSelection(mNoteEditor.getText().length());//设置文本编辑框中显示的文字是workingnote类中包含的便签文字并且设置文本被选中
}
for (Integer id : sBgSelectorSelectionMap.keySet()) {//对于背景里的图片选择做for循环遍历
findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE);//将背景选择图片都设置为不显示
}
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());//设置便签头部背景和编辑部分的背景颜色
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());//为便签编辑器设置背景
mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,//设置标题中显示的文字包含其被编辑的日期信息
mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE//在便签顶部显示时间
| DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_YEAR));//年份
/**
* TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker
* is not ready
*/
showAlertHeader();//在标题头部设置提醒的时间
}
private void showAlertHeader() {
if (mWorkingNote.hasClockAlert()) {//如果当前便签已经设置了提醒,则继续向下判断
long time = System.currentTimeMillis();//得到当前时间
if (time > mWorkingNote.getAlertDate()) {//如果系统时间大于了闹钟设置的时间,那么闹钟失效
mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired);//提醒时间已过期
} else {//如果没超时,则显示还剩下多少时间
mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString(
mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));//如果提醒时间未到,则设置标题中显示提醒时间
}
mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE);//显示闹钟开启的图标
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE);//提醒时间图标显示可见
} else {
// mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);//如果便签不包含提醒,则不显示
mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
};
}
@Override
protected void onNewIntent(Intent intent) {//新建一个传值对象
super.onNewIntent(intent);
initActivityState(intent);//初始化活动状态
}
@Override
protected void onSaveInstanceState(Bundle outState) {//保存当前活动的状态
super.onSaveInstanceState(outState);
/**
* For new note without note id, we should firstly save it to
* generate a id. If the editing note is not worth saving, there
* is no id which is equivalent to create new note
*/
if (!mWorkingNote.existInDatabase()) {//如果该workingnote实例无法在数据库中找到
saveNote();//保存标签
}
outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId());//将生成的noteId保存到outState中
Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState");//使用Log输出debug信息保存的执行便签id
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {//对屏幕触控事件的判断
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mNoteBgColorSelector, ev)) {//当备件颜色选择器可见,并且触控事件不在它的范围内时,执行下面代码
mNoteBgColorSelector.setVisibility(View.GONE);//设置颜色选择器在屏幕上可见
return true;
}
if (mFontSizeSelector.getVisibility() == View.VISIBLE
&& !inRangeOfView(mFontSizeSelector, ev)) {//当文字大小选择器可见,并且触控事件不在它的范围内时,执行下面代码
mFontSizeSelector.setVisibility(View.GONE);//设置字体大小选择器在屏幕上可见
return true;
}
return super.dispatchTouchEvent(ev);//未被消耗时调用父类的方法
}
private boolean inRangeOfView(View view, MotionEvent ev) {//判断触摸事件发生的位置是否在View控件范围内
int []location = new int[2];
view.getLocationOnScreen(location);//声明location数组用于存放屏幕位置的横纵坐标x-y
int x = location[0];
int y = location[1];
if (ev.getX() < x//如果触控的位置超出了给定的范围返回false
|| ev.getX() > (x + view.getWidth())
|| ev.getY() < y
|| ev.getY() > (y + view.getHeight())) {
return false;
}
return true;
}
private void initResources() {//初始化资源
mHeadViewPanel = findViewById(R.id.note_title);//初始化便签标题栏
mNoteHeaderHolder = new HeadViewHolder();//HeadViewHolder是对便签顶部的视图的容器此处实例化了它的对象
mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);//建立便签的时候初始化时间
mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);//得到提醒闹钟图标
mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);//得到闹钟日期
mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color);//得到设置背景颜色的按钮
mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this);//设置背景颜色控件的点击监听
mNoteEditor = (EditText) findViewById(R.id.note_edit_view);//初始化便签编辑部分界面
mNoteEditorPanel = findViewById(R.id.sv_note_edit);//得到文件编辑器
mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector);//设置背景颜色的选择器
for (int id : sBgSelectorBtnsMap.keySet()) {//对所有颜色选择按钮设置监听器
ImageView iv = (ImageView) findViewById(id);
iv.setOnClickListener(this);//设置点击监听器
}
mFontSizeSelector = findViewById(R.id.font_size_selector);//初始化便签文字字号选择器
for (int id : sFontSizeBtnsMap.keySet()) {//对所有字号选择按钮设置监听器
View view = findViewById(id);
view.setOnClickListener(this);
};
mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);//得到用户的偏好信息
mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);//从偏好设置中得到设置字体大小的ID
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {//如果获取到的字体大小值的长度大于资源文件应有长度
mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;//将其设置为默认长度缺省值为1
}
mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);//得到标签编辑的列表
}
@Override
protected void onPause() {//重写onPause方法将便签编辑界面暂停
super.onPause();
if(saveNote()) {//保存便签的内容
Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());// 暂停时即进行便签的存储,记录log文件
}
clearSettingState();//清除状态设置
}
private void updateWidget() {//更新窗口与桌面小窗口同步
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);//实例化Intent用于和AppWidgetManager进行消息交换
if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) {//根据workingnote的widget类型大小设置intent中映射的类
intent.setClass(this, NoteWidgetProvider_2x.class);
} else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) {//如果是4倍大小
intent.setClass(this, NoteWidgetProvider_4x.class);
} else {
Log.e(TAG, "Unspported widget type");//Log输出error信息不支持的widget类型
return;
}
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {//将桌面挂件的标识作为附加信息添加到Intent中
mWorkingNote.getWidgetId()//以广播形式发送intent
});
sendBroadcast(intent);//把intent信息广播发送
setResult(RESULT_OK, intent);//设置当前Activity结束后将结束信息发送给其父活动
}
public void onClick(View v) {//当点击事件发生时执行该方法
int id = v.getId();//获取到点击事件的id
if (id == R.id.btn_set_bg_color) {//如果点击的是设置背景颜色的按钮
mNoteBgColorSelector.setVisibility(View.VISIBLE);//.背景颜色选择器设置为可见
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE);//将备选颜色界面设为可见
} else if (sBgSelectorBtnsMap.containsKey(id)) {//判断是否是背景颜色选择器的一个按钮
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE);//将原来的背影颜色设置为不可见
mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id));//根据id设置新的背景颜色
mNoteBgColorSelector.setVisibility(View.GONE);//将背景颜色选择器隐藏
} else if (sFontSizeBtnsMap.containsKey(id)) {//如果点击的是文字大小设置器中的文字大小选项按钮
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE);//将备选字体界面设为可见
mFontSizeId = sFontSizeBtnsMap.get(id);//获取字号
mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit();//将共享设置中的字体进行修改
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);//将字体设置设为可见
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果workingNote模式为核对列表模式
getWorkingText();//.获取到正在编辑的文本
switchToListMode(mWorkingNote.getContent());//将便签内容显示切换到列表模式
} else {
mNoteEditor.setTextAppearance(this,
TextAppearanceResources.getTexAppearanceResource(mFontSizeId));//如果不是check模式则设置文字编辑器中文字为相应字体大小
}
mFontSizeSelector.setVisibility(View.GONE);//最后将文字大小选择器设置为不可见
}
}
@Override
public void onBackPressed() {//点击返回键时的操作
if(clearSettingState()) {//如果无界面打开,则直接返回,否则关闭再返回
return;
}
saveNote();//保存便签
super.onBackPressed();
}
private boolean clearSettingState() {//清除设置状态
if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {
mNoteBgColorSelector.setVisibility(View.GONE);//如果背景色选择器可见,设置为不可见
return true;
} else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {
mFontSizeSelector.setVisibility(View.GONE);//如果文字大小选择器可见,则将其设置为不可见
return true;
}
return false;
}
public void onBackgroundColorChanged() {//背景颜色改变
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.VISIBLE);//通过workingnote对象中存储的背景色id从预定义哈希表中找到对应项设置为可见
mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());//根据workingNote的背景颜色资源id设置便签编辑器的背景资源
mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());//将便签头的背景资源设置为标题的背景色
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {//对选择菜单的准备
if (isFinishing()) {//如果窗口正在关闭,则不做处理
return true;
}
clearSettingState();//清除设置状态
menu.clear();//清除菜单项
if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {//如果便签所在的文件夹为便签的通话记录文件夹
getMenuInflater().inflate(R.menu.call_note_edit, menu);//MenuInflater是用来实例化Menu目录下的Menu布局文件的
} else {
getMenuInflater().inflate(R.menu.note_edit, menu);//加载一个布局文件
}
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//是否进入了清单模式,加载相应的菜单
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode);//将菜单中的菜单列表模式的标题设置为“离开选择列表”
} else {
menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode);//将菜单中的菜单列表模式的标题设置为“进入选择列表”
}
if (mWorkingNote.hasClockAlert()) {//如果便签有闹钟提醒
menu.findItem(R.id.menu_alert).setVisible(false);//将添加提醒的菜单选项设置为不可见
} else {//如果workingNote对象中没有时钟提醒事项则把删除提醒的菜单选项设置为不可见
menu.findItem(R.id.menu_delete_remind).setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {//处理菜单被选中后的时间处理
switch (item.getItemId()) {//获得项的id,根据菜单中不同的按钮设置不同的处理
case R.id.menu_new_note://创建新标签
createNewNote();
break;
case R.id.menu_delete://删除便签
AlertDialog.Builder builder = new AlertDialog.Builder(this);//实例化提醒对话框
builder.setTitle(getString(R.string.alert_title_delete));//设置对话框的标题,“删除便签”
builder.setIcon(android.R.drawable.ic_dialog_alert);//设置对话框的图标
builder.setMessage(getString(R.string.alert_message_delete_note));//设置对话框消息内容“确认删除这个便签?”
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {//设置确认按钮,并监听它是否被点击
public void onClick(DialogInterface dialog, int which) {//设置对话框的点击函数
deleteCurrentNote();//删除当前的便签
finish();
}
});
builder.setNegativeButton(android.R.string.cancel, null);//显示对话框.设置取消按钮
builder.show();//显示提醒对话框
break;
case R.id.menu_font_size://菜单字体大小的设置
mFontSizeSelector.setVisibility(View.VISIBLE);//将字体的选择器置为可见
findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);//通过id找到相应字体的大小
break;
case R.id.menu_list_mode://列表的菜单模式
mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?//设置清单模式,若当前为清单模式,则取消;否之则设为清单模式
TextNote.MODE_CHECK_LIST : 0);
break;
case R.id.menu_share://菜单共享
getWorkingText();//获取当前便签的文本
sendTo(this, mWorkingNote.getContent());//用sendto函数将运行文本发送到遍历的本文内
break;
case R.id.menu_send_to_desktop://发送到桌面
sendToDesktop();
break;
case R.id.menu_alert://创建菜单的提醒设置
setReminder();//删除菜单的提醒
break;
case R.id.menu_delete_remind://选择删除提醒
mWorkingNote.setAlertDate(0, false);
break;
case R.id.menu_font_select:
showSingleAlertDiglog();
break;
default:
break;
}
return true;
}
private void setReminder() {//建立事件提醒器
DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());//建立修改时间日期的对话框
d.setOnDateTimeSetListener(new OnDateTimeSetListener() {//置日期时间设定的监听器
public void OnDateTimeSet(AlertDialog dialog, long date) {//设置日期提醒
mWorkingNote.setAlertDate(date , true);//设置提醒时间
}
});
d.show();//显示该控件
}
/**
* Share note to apps that support {@link Intent#ACTION_SEND} action
* and {@text/plain} type
*/
private void sendTo(Context context, String info) {//该函数将字符串发送出去
Intent intent = new Intent(Intent.ACTION_SEND);//新建发送活动的传值对象
intent.putExtra(Intent.EXTRA_TEXT, info);//将需要传递的便签信息放入text文件中
intent.setType("text/plain");//编辑连接器的类型
context.startActivity(intent);//使用context启动intent对应的活动
}
private void createNewNote() {//创建新的便签
// Firstly, save current editing notes
saveNote();//保存已有便签
// For safety, start a new NoteEditActivity
finish();
Intent intent = new Intent(this, NoteEditActivity.class);//设置一个新的便签活动编辑器
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);//将当前活动设置为插入或者编辑
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId());//将运行便签的ID添加到Intent中
startActivity(intent);//开始activity并链接
}
private void deleteCurrentNote() {//删除当前的便签
if (mWorkingNote.existInDatabase()) {//判断便签是否在数据库中
HashSet<Long> ids = new HashSet<Long>();
long id = mWorkingNote.getNoteId();//获取当前便签的id
if (id != Notes.ID_ROOT_FOLDER) {//如果不是头文件夹建立一个hash表把便签id存起来
ids.add(id);
} else {//否则输出错误
Log.d(TAG, "Wrong note id, should not happen");
}
if (!isSyncMode()) {//在非同步模式情况下
if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {//使用DataUtils的批量删除便签将ids中的所有便签删除
Log.e(TAG, "Delete Note error");//删除操作
}
} else {
if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) {//如果是同步模式则将ids中的便签批量移动到“垃圾”文件夹。
Log.e(TAG, "Move notes to trash folder error, should not happens");//输出错误信息
}
}
}
mWorkingNote.markDeleted(true);//将该便签标记为已删除
}
private boolean isSyncMode() {//判断是否为同步模式
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;//返回同步的用户名长度如果大于0则有同步状态否则非同步
}
public void onClockAlertChanged(long date, boolean set) {//当提醒时间改变时执行该函数
/**
* User could set clock to an unsaved note, so before setting the
* alert clock, we should save the note first
*/
if (!mWorkingNote.existInDatabase()) {
saveNote();//若当前编辑的便签不在数据库中,则先保存便签
}
if (mWorkingNote.getNoteId() > 0) {//若当前编辑的便签的id>0
Intent intent = new Intent(this, AlarmReceiver.class);//新建一个intent指向活动AlarmReceiver
intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId()));//若有运行的便签就将便签的ID放置在URI中去
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);//设置延迟触发Intent
AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE));//获得闹钟服务
showAlertHeader();//设置提醒管理器
if(!set) {
alarmManager.cancel(pendingIntent);//如果没有确定设置提醒 ,则闹钟管理器取消该提醒
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent);//将提醒时间、pendingintent传入闹钟管理器作为新的提醒事项
}
} else {//如果没有设置就报错
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
Log.e(TAG, "Clock alert setting error");//如果便签id不存在输出error信息
showToast(R.string.error_note_empty_for_clock);//显示消息提示框,为未编辑的便签设置闹钟
}
}
public void onWidgetChanged() {
updateWidget();
}//当widget变化时执行更新widget这个函数
public void onEditTextDelete(int index, String text) {//删除编辑的文本框所出发的事件
int childCount = mEditTextList.getChildCount();//获取EditText列表里EditText项的数量
if (childCount == 1) {
return;//如果EditText项数为1不做操作返回
}
for (int i = index + 1; i < childCount; i++) {//修改删除文本之后的Index
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))//通过id把编辑框存在便签编辑框中
.setIndex(i - 1);
}
mEditTextList.removeViewAt(index);//移除特定位置的视图
NoteEditText edit = null;
if(index == 0) {////如果index为0则将edit定位到第一个EditText项
edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById(
R.id.et_edit_text);
} else {//通过id把编辑框存在空的NoteEditText中
edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById(
R.id.et_edit_text);
}
int length = edit.length();//获取edit的长度
edit.append(text);//将后面的文本加入到edit中
edit.requestFocus();//请求优先完成该此编辑
edit.setSelection(length);//定位到length位置处的条目
}
public void onEditTextEnter(int index, String text) {//进入编辑文本框所触发的事件
/**
* Should not happen, check for debug
*/
if(index > mEditTextList.getChildCount()) {//如果越界就报错
Log.e(TAG, "Index out of mEditTextList boundrary, should not happen");//输出错误信息,“不可能发生”
}
View view = getListItem(text, index);//根据文本和index获取到列表项的view
mEditTextList.addView(view, index);//添加当前项的视图
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);//建立一个新的视图并添加到编辑文本框内
edit.requestFocus();//请求优先操作
edit.setSelection(0);//设置选择地点
for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {//遍历子文本框并设置对应对下标
((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text))
.setIndex(i);
}
}
private void switchToListMode(String text) {//切换至列表模式
mEditTextList.removeAllViews();//移除所有子视图
String[] items = text.split("\n");//根据换行符分割字符串
int index = 0;//清空所有视图,初始化下标
for (String item : items) {//遍历所有文本单元并添加到文本列表中
if(!TextUtils.isEmpty(item)) {//如果item不是空的
mEditTextList.addView(getListItem(item, index));//添加新的视图
index++;
}
}
mEditTextList.addView(getListItem("", index));//添加最后一行的相关标签
mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus();//获取当前列表项焦点
mNoteEditor.setVisibility(View.GONE);//便签编辑器不可见
mEditTextList.setVisibility(View.VISIBLE);//将文本编辑框置为可见
}
private Spannable getHighlightQueryResult(String fullText, String userQuery) {//获取高亮效果的反馈情况
SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);//新建一个效果选项
if (!TextUtils.isEmpty(userQuery)) {//如果搜索结果不为空
mPattern = Pattern.compile(userQuery);//将用户的请求编译为正则表达式
Matcher m = mPattern.matcher(fullText);//建立一个状态机检查pattern并进行匹配
int start = 0;//初始化start
while (m.find(start)) {//将匹配到的内容设置为高亮
spannable.setSpan(//设置背景颜色
new BackgroundColorSpan(this.getResources().getColor(//将目标设置为高亮
R.color.user_query_highlight)), m.start(), m.end(),//更新起始位置
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
start = m.end();
}
}
return spannable;
}
private View getListItem(String item, int index) {//获取列表项
View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null);//获取便签编辑列表项的布局
final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);//获得编辑文本
edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId));//创建一个文本编辑框并置为可见
CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item));//建立一个打钩框并设置监听器
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {//设置监听判断是否已标识
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {//如果CheckBox已勾选
if (isChecked) {//如果已经被标记
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);//设置中划线
} else {//未被标记
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
}
}
});
if (item.startsWith(TAG_CHECKED)) {//判断是否勾选
cb.setChecked(true);//选择框设置为true
edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
item = item.substring(TAG_CHECKED.length(), item.length()).trim();//去掉TAG_CHECKED和空格
} else if (item.startsWith(TAG_UNCHECKED)) {//选择不勾选
cb.setChecked(false);//设置为false
edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//绘画
item = item.substring(TAG_UNCHECKED.length(), item.length()).trim();//去掉unchecked与空格
}
edit.setOnTextViewChangeListener(this);//监听文本视图的变化
edit.setIndex(index);//运行编辑框的监听器对该行为作出反应,并设置下标及文本内容
edit.setText(getHighlightQueryResult(item, mUserQuery));//设置用户输入为高亮
return view;
}
public void onTextChange(int index, boolean hasText) {//便签内容发生改变
if (index >= mEditTextList.getChildCount()) {//index超出EditText列表项数
Log.e(TAG, "Wrong index, should not happen");//输出错误信息
return;
}
if(hasText) {//内容不为空
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE);//将其子编辑框可见性置为可见
} else {//否则不可见
mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE);
}
}
public void onCheckListModeChanged(int oldMode, int newMode) {//检查模式和列表模式的切换
if (newMode == TextNote.MODE_CHECK_LIST) {//如果新模式为列表模式
switchToListMode(mNoteEditor.getText().toString());//检查模式切换到列表模式
} else {
if (!getWorkingText()) {//如果未获取到workingText
mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ",
""));//设置工作文本
}
mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));//设置高亮文本
mEditTextList.setVisibility(View.GONE);//便签文本列表设置为不可见
mNoteEditor.setVisibility(View.VISIBLE);//便签编辑器设置为可见
}
}
private boolean getWorkingText() {//得到工作文本
boolean hasChecked = false;//初始化check的标记
if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//判断是否是清单模式
StringBuilder sb = new StringBuilder();//创建可变字符串
for (int i = 0; i < mEditTextList.getChildCount(); i++) {//for循环遍历EditTextList的项
View view = mEditTextList.getChildAt(i);//获取当前文本编辑列表的第i项
NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text);//获得文本编辑框
if (!TextUtils.isEmpty(edit.getText())) {//若文本不为空
if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) {
sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n");//扩展字符串为已打钩并把标记置true
hasChecked = true;
} else {//如果未被勾选
sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n");//扩展字符串并且添加为未打勾
}
}
}
mWorkingNote.setWorkingText(sb.toString());//利用编辑好的字符串设置运行便签的内容
} else {
mWorkingNote.setWorkingText(mNoteEditor.getText().toString());//用编辑器中的内容设置运行中标签的内容
}
return hasChecked;//返回便签是否已标记
}
private boolean saveNote() {//保存便签
getWorkingText();//获取到当前编辑便签的文本
boolean saved = mWorkingNote.saveNote();//获取工作文本后保存内容
if (saved) {//如果已保存
/**
* There are two modes from List view to edit view, open one note,
* create/edit a node. Opening node requires to the original
* position in the list when back from edit view, while creating a
* new node requires to the top of the list. This code
* {@link #RESULT_OK} is used to identify the create/edit state
*/
setResult(RESULT_OK);//代表是通过编辑的方式打开便签,而非新建便签
}
return saved;
}
private void sendToDesktop() {//将便签发送至桌面
/**
* Before send message to home, we should make sure that current
* editing note is exists in databases. So, for new note, firstly
* save it
*/
if (!mWorkingNote.existInDatabase()) {//若便签不存在数据库中
saveNote();//保存此新建的便签
}
if (mWorkingNote.getNoteId() > 0) {//若是有内容
Intent sender = new Intent();//新建传递对象
Intent shortcutIntent = new Intent(this, NoteEditActivity.class);//从当前活动跳转到编辑便签页面NoteEditActivity
shortcutIntent.setAction(Intent.ACTION_VIEW);//链接内容为一个视图
shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId());//将便签的相关信息都添加到要发送的文件里
sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);//将shortcut的图标标题存入sender中
sender.putExtra(Intent.EXTRA_SHORTCUT_NAME,
makeShortcutIconTitle(mWorkingNote.getContent()));//设置图标
sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app));//将便签的相关信息都添加到要发送的文件里
sender.putExtra("duplicate", true);
sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT");//设置sneder的行为是发送
showToast(R.string.info_note_enter_desktop);//显示消息提示框表示文本已经增加到home中
sendBroadcast(sender);//显示到桌面
} else {//如果便签的id错误则保存提醒用户
/**
* There is the condition that user has input nothing (the note is
* not worthy saving), we have no note id, remind the user that he
* should input something
*/
Log.e(TAG, "Send to desktop error");//空便签直接报错
showToast(R.string.error_note_empty_for_send_to_desktop);//展示toast报错消息提示不能发送一个空便签到桌面
}
}
private String makeShortcutIconTitle(String content) {//生成快捷方式的图标标题
content = content.replace(TAG_CHECKED, "");//编辑小图标的标题
content = content.replace(TAG_UNCHECKED, "");
return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0,
SHORTCUT_ICON_TITLE_MAX_LEN) : content;//直接设置为content中的内容并返回有勾选和未勾选2种
}
private void showToast(int resId) {
showToast(resId, Toast.LENGTH_SHORT);
}//显示提示的视图
private void showToast(int resId, int duration) {//持续显示提示的视图
Toast.makeText(this, resId, duration).show();//设置toast消息的文本内容
}
public void showSingleAlertDiglog(){
final String[] items = {"方正舒体","华文彩云","华文琥珀","华文行楷","Viner Hand ITC","Vivaldi斜体紧缩","Vladimir Script"};
final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setTitle("选择字体");
alertBuilder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case 0:
Typeface typeface0 = Typeface.createFromAsset(getAssets(), "font/FZSTK.TTF");
mNoteEditor.setTypeface(typeface0);
break;
case 1:
Typeface typeface1 = Typeface.createFromAsset(getAssets(), "font/STCAIYUN.TTF");
mNoteEditor.setTypeface(typeface1);
break;
case 2:
Typeface typeface2 = Typeface.createFromAsset(getAssets(), "font/STHUPO.TTF");
mNoteEditor.setTypeface(typeface2);
break;
case 3:
Typeface typeface3 = Typeface.createFromAsset(getAssets(), "font/STXINGKA.TTF");
mNoteEditor.setTypeface(typeface3);
break;
case 4:
Typeface typeface4 = Typeface.createFromAsset(getAssets(), "font/VINERITC.TTF");
mNoteEditor.setTypeface(typeface4);
break;
case 5:
Typeface typeface5 = Typeface.createFromAsset(getAssets(), "font/VIVALDII.TTF");
mNoteEditor.setTypeface(typeface5);
break;
case 6:
Typeface typeface6 = Typeface.createFromAsset(getAssets(), "font/VLADIMIR.TTF");
mNoteEditor.setTypeface(typeface6);
break;
}
Toast.makeText(NoteEditActivity.this, items[i],Toast.LENGTH_SHORT).show();
}
});
alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertBuilder.create().show();
}
}

@ -0,0 +1,216 @@
/*
* 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;//导入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;//URL格式
import android.util.AttributeSet;// 属性,特征
import android.util.Log;//日志
import android.view.ContextMenu;//菜单内容视图
import android.view.KeyEvent;//关键事件
import android.view.MenuItem;//菜单选项
import android.view.MenuItem.OnMenuItemClickListener;//菜单点击监听器
import android.view.MotionEvent;//动作事件
import android.widget.EditText;//编辑文本
import net.micode.notes.R;
import java.util.HashMap;
import java.util.Map;
public class NoteEditText extends EditText {//继承edittext设置便签设置文本框
private static final String TAG = "NoteEditText";//标志为字符串"NoteEditText"
private int mIndex;//建立字符整型的HASH表用于进行电话、网站、邮箱的链接
private int mSelectionStartBeforeDelete;//声明整型变量,获取删除文本前的位置
private static final String SCHEME_TEL = "tel:" ;//文本中电话号码内容
private static final String SCHEME_HTTP = "http:" ;//文本中网页内容
private static final String SCHEME_EMAIL = "mailto:" ;//文本中邮件内容
private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>();//设置映射,将文本内容(电话、网址、邮件)做链接处理
static {//在NoteEditActivity中删除或增添文本的操作
sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel);
sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web);
sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email);
}
/**
* Call by the {@link NoteEditActivity} to delete or add edit text
*/
public interface OnTextViewChangeListener {//实现对TextView组件中的文字信息进行修改
/**
* Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens
* and the text is null
*/
void onEditTextDelete(int index, String text);//当触发删除文本KeyEvent时删除文本
/**
* Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER}
* happen
*/
void onEditTextEnter(int index, String text);//处理进入按键时的操作
/**
* Hide or show item option when text change
*/
void onTextChange(int index, boolean hasText);//文字更改时隐藏或显示项目选项
}
private OnTextViewChangeListener mOnTextViewChangeListener;//声明文本视图变化监听器
public NoteEditText(Context context) {//根据context设置文本
super(context, null);//用super引用父类变量
mIndex = 0;//设置当前光标
}
public void setIndex(int index) {
mIndex = index;
}//初始化文本修改标记
public void setOnTextViewChangeListener(OnTextViewChangeListener listener) {//设置一个文本改变的监听器
mOnTextViewChangeListener = listener;//设置文本视图变化监听器
}
public NoteEditText(Context context, AttributeSet attrs) {//初始化便签
super(context, attrs, android.R.attr.editTextStyle);//第三个参数就是xml文件的资源编辑风格
}
public NoteEditText(Context context, AttributeSet attrs, int defStyle) {//根据defstyle自动初始化
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event) {//处理手机屏幕的所有事件
switch (event.getAction()) {//重写屏幕触发事件
case MotionEvent.ACTION_DOWN://更新坐标
int x = (int) event.getX();//更新当前坐标值
int y = (int) event.getY();
x -= getTotalPaddingLeft();//减去左边控件的距离
y -= getTotalPaddingTop();//减去上方控件的距离
x += getScrollX();//加上滚轮滚过的距离
y += getScrollY();
Layout layout = getLayout();//layout布局控件设置新的位置
int line = layout.getLineForVertical(y);//获取纵向的行数
int off = layout.getOffsetForHorizontal(line, x);//获得横向的偏移量
Selection.setSelection(getText(), off);//定位光标的位置
break;
}
return super.onTouchEvent(event);//继续调用父类的监听事件方法
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {//处理用户按下一个键盘按键时会触发的事件
switch (keyCode) {//根据按键的KeyCode来处理
case KeyEvent.KEYCODE_ENTER://根据按键的 Unicode 编码值来处理
if (mOnTextViewChangeListener != null) {//进入键
return false;//返回false
}
break;
case KeyEvent.KEYCODE_DEL://按下删除时设置了光标位置
mSelectionStartBeforeDelete = getSelectionStart();//获取删除文本的开始位置
break;
default://其他情况,我们返回父类的onKeyDown值
break;
}
return super.onKeyDown(keyCode, event);//父类其他键盘事件
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {//当用户松开按键瞬间系统的响应
switch(keyCode) {//据按键的 Unicode 编码值来处理有删除和进入2种操作根
case KeyEvent.KEYCODE_DEL://抬起删除键
if (mOnTextViewChangeListener != null) {//如果文本视图发生变化
if (0 == mSelectionStartBeforeDelete && mIndex != 0) {//如果文本视图发生变化
mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());//监听文本的删除
return true;
}
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");//其他情况报错,文档的改动监听器并没有建立
}
break;
case KeyEvent.KEYCODE_ENTER://抬起回车键
if (mOnTextViewChangeListener != null) {//如果文本视图发生变化
int selectionStart = getSelectionStart();//获取当前位置
String text = getText().subSequence(selectionStart, length()).toString();//获取当前文本
setText(getText().subSequence(0, selectionStart));//根据获取的文本设置当前文本
mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);//将选择区域内的文字移到下一行
} else {
Log.d(TAG, "OnTextViewChangeListener was not seted");//其他情况报错,文档的改动监听器并没有建立
}
break;
default:
break;
}
return super.onKeyUp(keyCode, event);//继续执行父类的其他按键弹起的事件
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {//规定了编辑文本焦点改变时的系统响应
if (mOnTextViewChangeListener != null) {//若监听器已经建立
if (!focused && TextUtils.isEmpty(getText())) {//获取焦点文本不为空
mOnTextViewChangeListener.onTextChange(mIndex, false);//置false隐藏事件选项
} else {
mOnTextViewChangeListener.onTextChange(mIndex, true);//置true显示事件选项
}
}
super.onFocusChanged(focused, direction, previouslyFocusedRect);//置true显示事件选项
}
@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);//设置url的信息的范围值
if (urls.length == 1) {//设置url的信息的范围值
int defaultResId = 0;//默认的资源ID值为0
for(String schema: sSchemaActionResMap.keySet()) {//获取计划表中所有的key值
if(urls[0].getURL().indexOf(schema) >= 0) {//若url可以添加则在添加后将defaultResId置为key所映射的值
defaultResId = sSchemaActionResMap.get(schema);//若url可以添加则在添加后将defaultResId置为key所映射的值
break;
}
}
if (defaultResId == 0) {//defaultResId == 0则说明url并没有添加任何东西所以置为打开map的值
defaultResId = R.string.note_link_other;
}
menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener(//建立菜单
new OnMenuItemClickListener() {//实例化菜单监听器
public boolean onMenuItemClick(MenuItem item) {
// goto a new intent
urls[0].onClick(NoteEditText.this);//根据相应的文本设置菜单的按键
return true;
}
});
}
}
super.onCreateContextMenu(menu);//创建文本菜单
}
}

@ -0,0 +1,82 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;//package是包名继承于gtask用于记录数据变化//
import android.database.Cursor;//引用基于数据库服务游标的类//
import android.util.Log;//引用日志输出工具类//
import net.micode.notes.tool.GTaskStringUtils;// 导入tool包的GTaskStringUtils工具类//
import org.json.JSONException;//Json使用失败异常处理//
import org.json.JSONObject;//包jsonObject就是常说的json是一种重要的数据传输对象。其格式为{“key1":value1."key2":value2,......};key必须是字符串内部封装了一个函数用来储存json对象//
public class MetaData extends Task {
private final static String TAG = MetaData.class.getSimpleName();//调用getSimpleName ()函数,得到类的简写名称存入字符串TAG中//
private String mRelatedGid = null;//创建私有变量mRelatedGid并初始化为null。//
public void setMeta(String gid, JSONObject metaInfo) {// 调用JSONObject库函数put ()Task类中的setNotes ()和setName ()函数,实现设置数据,即生成元数据库//
try {//对函数块进行注释//
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
}// 捕捉异常并进行异常处理放入TAG//
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);
}
public String getRelatedGid() {
return mRelatedGid;
}//获取相关Gid//
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}//判断是否值得存放,即当前数据是否有效,若数据非空则返回真值。//
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);//如果是继承的方法,是没有必要使用 super 来调用,直接即可调用。但如果子类覆盖或重写了父类的方法,则只有使用 super 才能在子类中调用父类中的被重写的方法//
if (getNotes() != null) {
try {//捕捉异常,获取关联 Gid 失败//
JSONObject metaInfo = new JSONObject(getNotes().trim());//创建新json对象getnotes返回值mNotes调用trim方法去掉首尾空格//
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);//获取关联gid且为字符串类型//
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
mRelatedGid = null;
}//用catch进行异常处理并输出警告信息//
}
}// 功能描述使用远程json数据对象设置元数据内容实现过程调用父类Task中的setContentByRemoteJSON ()函数//
@Override
public void setContentByLocalJSON(JSONObject js) {
// this function should not be called
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}//使用本地json数据对象设置元数据内容一般不会用到若用到则抛出异常//
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}//从元数据内容中获取本地json对象一般不会用到若用到则抛出异常//
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}//获取同步动作状态,一般不会用到,若用到,则抛出异常
}//新建一个继承Task类的MetaData类该类主要用于记录数据的变化作为元数据类描述数据属性的信息。//

@ -0,0 +1,100 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import org.json.JSONObject;
public abstract class Node {
public static final int SYNC_ACTION_NONE = 0;//本地和远端都不更新同步行为代号0//
public static final int SYNC_ACTION_ADD_REMOTE = 1;//=1时在远端接口增加内容//
public static final int SYNC_ACTION_ADD_LOCAL = 2;//=2时需要在本地增加内容//
public static final int SYNC_ACTION_DEL_REMOTE = 3;//=3时需要在远程云端删除内容//
public static final int SYNC_ACTION_DEL_LOCAL = 4;//=4时需要在本地删除内容//
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;//=5时需要将本地内容更新到远程云端//
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;//=6时需要将远程云端内容更新到本地//
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;//同步出现冲突//
public static final int SYNC_ACTION_ERROR = 8;//同步出现错误//
private String mGid;//记录最后一次修改时间//
private String mName;//bool类型表明表征是否被删除//
private long mLastModified;//声明long类型表示记录最后行为时间//
private boolean mDeleted;//判断 表征是否被删除//
public Node() {
mGid = null;
mName = "";
mLastModified = 0;
mDeleted = false;
}/*构造函数进行初始化界面没有名字为空最后一次修改时间为0没有修改表征是否删除。*/
public abstract JSONObject getCreateAction(int actionId);//引用一个抽象的类,下同不再注释//
public abstract JSONObject getUpdateAction(int actionId);
public abstract void setContentByRemoteJSON(JSONObject js);
public abstract void setContentByLocalJSON(JSONObject js);
public abstract JSONObject getLocalJSONFromContent();
public abstract int getSyncAction(Cursor c);
public void setGid(String gid) {
this.mGid = gid;
}//以下几个函数都是对于上面的公共类Node的里的变量进行赋值和修改。//
public void setName(String name) {
this.mName = name;
}//设置名称//
public void setLastModified(long lastModified) {
this.mLastModified = lastModified;
}//设置最近修改时间标识//
public void setDeleted(boolean deleted) {
this.mDeleted = deleted;
}//设置删除标识//
public String getGid() {
return this.mGid;
}//获取Gid//
public String getName() {
return this.mName;
}//获取名称//
public long getLastModified() {
return this.mLastModified;
}//获取最近创建时间标识//
public boolean getDeleted() {
return this.mDeleted;
}//获取删除标识//
}//这里是一个类用于建立node类来提供模板设置各种参数及定义各种函数会在别的地方用到定义了各种同步活动的标识码。//

@ -0,0 +1,257 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
//定义note类处理单个便签//
public class Note {
private ContentValues mNoteDiffValues;//声明一个ContentValues变量用来存储note与上次修改后的改动//
private NoteData mNoteData;//申明一个NoteData变量用来记录note的一些基本信息//
private static final String TAG = "Note";//设置软件标签//
/**
* Create a new note id for adding a new note to databases
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
ContentValues values = new ContentValues();//在数据库中新建一个便签文件//
long createdTime = System.currentTimeMillis();//设置系统当前时间为新便签创建时间//
values.put(NoteColumns.CREATED_DATE, createdTime);//将创建时间和修改时间都更改为当前系统时间//
values.put(NoteColumns.MODIFIED_DATE, createdTime);// 将便签的创建时间和修改时间都设定为创建时间//
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);//设定类型为便签类型//
values.put(NoteColumns.LOCAL_MODIFIED, 1);//修改标志置为1//
values.put(NoteColumns.PARENT_ID, folderId);//将数据写入数据库表格//
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);//将数据写入到数据库中//
long noteId = 0;
try {
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}//异常处理,捕获异常//
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
}//块错误ID异常处理//
return noteId;//没有异常返回ID//
}//获取新建便签的编号//
public Note() {
mNoteDiffValues = new ContentValues();//设置存储便签属性//
mNoteData = new NoteData();//设置存储便签内容//
}//构造Note,实例化note数据//
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}//设置数据库表格的标签属性数据//
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}/*设置数据库表格的标签文本内容的数据*/
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}//设置文本数据的ID//
public long getTextDataId() {
return mNoteData.mTextDataId;
}//获取文本数据的id//
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}//设置电话号码数据的ID//
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}//得到电话号码数据的ID//
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}//根据属性特征值判定便签是否被本地修改//
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}//便签ID不合法时抛出异常//
if (!isLocalModified()) {
return true;
}//如果本地没有发现修改直接返回1指示已经同步到数据库中//
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
*/
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
}//数据被修改后被同步到数据库,为了安全操作,现在更新后重新同步//
mNoteDiffValues.clear();
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
}//判断数据是否同步
return true;
}//判断是否是本地修改//
//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据//
private class NoteData {
private long mTextDataId;//文本数据id//
private ContentValues mTextDataValues;//文本数据属性//
private long mCallDataId;//电话号码数据ID//
private ContentValues mCallDataValues;//电话号码数据内容//
private static final String TAG = "NoteData";//NoteData成员主要负责给几个变量赋初值//
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
mTextDataId = 0;
mCallDataId = 0;
}//变量初始化//
//以下是几个函数的具体实现//
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}//判断是否本地修改//
void setTextDataId(long id) {
if(id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
}//设置文本数据ID号//
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
}
mCallDataId = id;
}//设置电话号码对应的id//
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}//设置呼叫数据ID若传入参数小于0则抛出参数错误的异常//
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}//设置文本数据内容,并且保存修改时间//
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}//为了安全,检查异常//
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);//文本数据ID为零意味着这个id是新建默认的id//
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}//捕获异常//
} //.把文本数据存入DataColumns//
else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}//内容提供者的更新操作因为这个uri对应的数据是已经存在的所以不需要向上面一样新建而是更新即可//
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
}//如果这个便签之前有历史操作的话那么在此基础上返回上一个操作对应位置的uri//
}//存储过程中如果遇到异常,通过以上操作进行处理//
else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}//当电话号码不为新建时更新电话号码ID//
mCallDataValues.clear();
}
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} //抛出远程异常,并写回日志//
catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;//捕捉操作异常并写回日志//
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;//异常日志//
}
}//操作列表不为空,即需要进行操作
return null;
}
}
}

@ -0,0 +1,189 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;//Java中除注释外的第一行代码将SplData类置于net.micode.notes.gtask.data类库单元中以后使用者想要使用SQLData类时需要import加net.micode.notes.gtask.data.SqlData//
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
import net.micode.notes.gtask.exception.ActionFailureException;
import org.json.JSONException;
import org.json.JSONObject;
public class SqlData {//类:数据库中的基本数据//
private static final String TAG = SqlData.class.getSimpleName();//调用getSimpleName ()函数得到类简称存入字符串TAG中//
private static final int INVALID_ID = -99999;
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3//获得数据列idmime类型内容1类型数据3类型数据//
};//新建一个字符串数组,集合了 interface DataColumns 中所有SF常量//
public static final int DATA_ID_COLUMN = 0;//在数据库中表头的每一列都有一个名字这里0号列名称为DATA_ID_COLUMN//
public static final int DATA_MIME_TYPE_COLUMN = 1;// 在数据库中表头的每一列都有一个名字这里把1号列名称设置为DATA_MIME_TYPE_COLUMN。//
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_3_COLUMN = 4;
private ContentResolver mContentResolver;//代码块定义的一些私有全局变量可以与sqlNote中的变量相对应分析定义以下8个内部变量//
private boolean mIsCreate;
private long mDataId;
private String mDataMimeType;
private String mDataContent;
private long mDataContentData1;
private String mDataContentData3;
private ContentValues mDiffDataValues;
public SqlData(Context context) {
mContentResolver = context.getContentResolver();//getContentResolver()获取ContentResovler对象如果需要查询数据就直接可以在mContentResolver上操作//
mIsCreate = true;
mDataId = INVALID_ID;
mDataMimeType = DataConstants.NOTE;
mDataContent = "";
mDataContentData1 = 0;
mDataContentData3 = "";
mDiffDataValues = new ContentValues();
}//第一种SQLData的构造方式只从上下文获取初始化其中的变量//
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDiffDataValues = new ContentValues();
}//第二种SqlData的构造方式通过cursor来获取数据//
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
mDataContent = c.getString(DATA_CONTENT_COLUMN);
mDataContentData1 = c.getLong(DATA_CONTENT_DATA_1_COLUMN);
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}//从光标c处加载数据帮助实现SqlData的第二种构造将5列的数据赋给该类的对象//
public void setContent(JSONObject js) throws JSONException {
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;/*如果传入的JSONObject对象有DataColumns.ID这一项则设置dataID为这个ID否则设为INVALID_ID*/
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
}
mDataId = dataId;
String dataMimeType = js.has(DataColumns.MIME_TYPE) ? js.getString(DataColumns.MIME_TYPE)
: DataConstants.NOTE;/*如果传入的JSONObject对象有DataColumns.MIME_TYPE一项则设置dataMimeType为这个否则设为SqlData.java*/
if (mIsCreate || !mDataMimeType.equals(dataMimeType)) {
mDiffDataValues.put(DataColumns.MIME_TYPE, dataMimeType);
}
mDataMimeType = dataMimeType;
String dataContent = js.has(DataColumns.CONTENT) ? js.getString(DataColumns.CONTENT) : "";
if (mIsCreate || !mDataContent.equals(dataContent)) {
mDiffDataValues.put(DataColumns.CONTENT, dataContent);
}//代码块对比DataContent并更新contentValue中的DataContent//
mDataContent = dataContent;
long dataContentData1 = js.has(DataColumns.DATA1) ? js.getLong(DataColumns.DATA1) : 0;/*如果传入的JSONObject对象有DataColumn.DATA1一项那么将其获取否则。将其设置为0。*/
if (mIsCreate || mDataContentData1 != dataContentData1) {
mDiffDataValues.put(DataColumns.DATA1, dataContentData1);
}
mDataContentData1 = dataContentData1;
String dataContentData3 = js.has(DataColumns.DATA3) ? js.getString(DataColumns.DATA3) : "";
if (mIsCreate || !mDataContentData3.equals(dataContentData3)) {
mDiffDataValues.put(DataColumns.DATA3, dataContentData3);
}
mDataContentData3 = dataContentData3;
}//设置用于共享的数据并提供异常抛出与处理机制其中很多if 条件语句的判断,某些条件下某些特定的操作//
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType);
js.put(DataColumns.CONTENT, mDataContent);
js.put(DataColumns.DATA1, mDataContentData1);
js.put(DataColumns.DATA3, mDataContentData3);
return js;
}//获取共享的数据内容,并提供异常抛出与处理机制//
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
if (mDataId == INVALID_ID && mDiffDataValues.containsKey(DataColumns.ID)) {
mDiffDataValues.remove(DataColumns.ID);
}//判断是否是第一种SqlData构造方式//
mDiffDataValues.put(DataColumns.NOTE_ID, noteId);
Uri uri = mContentResolver.insert(Notes.CONTENT_DATA_URI, mDiffDataValues);//在note的资源标识下加入data数据//
try {
mDataId = Long.valueOf(uri.getPathSegments().get(1));//上一句实现的是URI到Uri的转换将路径转换为Long型附识给当前id//
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}//如果转换出错则日志中显示错误“获取note的ID出错”//
} else {
if (mDiffDataValues.size() > 0) {//若共享数据存在则通过内容解析器更新关于新URI的共享数据//
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues, null, null);
}//如果版本还没确认则结果记录下的只是data的ID还有data内容//
else {
result = mContentResolver.update(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mDataId), mDiffDataValues,
" ? in (SELECT " + NoteColumns.ID + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.VERSION + "=?)", new String[] {
String.valueOf(noteId), String.valueOf(version)
});
}//如果版本确认了则从数据库中选取对应版本的id进行更新//
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}// 如果更新不存在(或许用户在同步时已经完成更新),则报错//
}
}
mDiffDataValues.clear();
mIsCreate = false;
}//commit 函数用于把当前所做的修改保存到数据库//
public long getId() {
return mDataId;
}//获取当前id//
}

@ -0,0 +1,505 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.tool.ResourceParser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
private static final int INVALID_ID = -99999;
public static final String[] PROJECTION_NOTE = new String[] {
NoteColumns.ID, NoteColumns.ALERTED_DATE, NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE, NoteColumns.HAS_ATTACHMENT, NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT, NoteColumns.PARENT_ID, NoteColumns.SNIPPET, NoteColumns.TYPE,
NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE, NoteColumns.SYNC_ID,
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION
};
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
public static final int BG_COLOR_ID_COLUMN = 2;
public static final int CREATED_DATE_COLUMN = 3;
public static final int HAS_ATTACHMENT_COLUMN = 4;
public static final int MODIFIED_DATE_COLUMN = 5;
public static final int NOTES_COUNT_COLUMN = 6;
public static final int PARENT_ID_COLUMN = 7;
public static final int SNIPPET_COLUMN = 8;
public static final int TYPE_COLUMN = 9;
public static final int WIDGET_ID_COLUMN = 10;
public static final int WIDGET_TYPE_COLUMN = 11;
public static final int SYNC_ID_COLUMN = 12;
public static final int LOCAL_MODIFIED_COLUMN = 13;
public static final int ORIGIN_PARENT_ID_COLUMN = 14;
public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mIsCreate;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private int mHasAttachment;
private long mModifiedDate;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private long mOriginParent;
private long mVersion;
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = true;
mId = INVALID_ID;
mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
mType = Notes.TYPE_NOTE;
mWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
mOriginParent = 0;
mVersion = 0;
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
}
public SqlNote(Context context, Cursor c) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(c);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
mIsCreate = false;
loadFromCursor(id);
mDataList = new ArrayList<SqlData>();
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues = new ContentValues();
}
private void loadFromCursor(long id) {
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(id)
}, null);
if (c != null) {
c.moveToNext();
loadFromCursor(c);
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
} finally {
if (c != null)
c.close();
}
}
private void loadFromCursor(Cursor c) {
mId = c.getLong(ID_COLUMN);
mAlertDate = c.getLong(ALERTED_DATE_COLUMN);
mBgColorId = c.getInt(BG_COLOR_ID_COLUMN);
mCreatedDate = c.getLong(CREATED_DATE_COLUMN);
mHasAttachment = c.getInt(HAS_ATTACHMENT_COLUMN);
mModifiedDate = c.getLong(MODIFIED_DATE_COLUMN);
mParentId = c.getLong(PARENT_ID_COLUMN);
mSnippet = c.getString(SNIPPET_COLUMN);
mType = c.getInt(TYPE_COLUMN);
mWidgetId = c.getInt(WIDGET_ID_COLUMN);
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN);
}
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
try {
c = mContentResolver.query(Notes.CONTENT_DATA_URI, SqlData.PROJECTION_DATA,
"(note_id=?)", new String[] {
String.valueOf(mId)
}, null);
if (c != null) {
if (c.getCount() == 0) {
Log.w(TAG, "it seems that the note has not data");
return;
}
while (c.moveToNext()) {
SqlData data = new SqlData(mContext, c);
mDataList.add(data);
}
} else {
Log.w(TAG, "loadDataContent: cursor = null");
}
} finally {
if (c != null)
c.close();
}
}
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
Log.w(TAG, "cannot set system 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
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
} else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
if (mIsCreate || mId != id) {
mDiffNoteValues.put(NoteColumns.ID, id);
}
mId = id;
long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note
.getLong(NoteColumns.ALERTED_DATE) : 0;
if (mIsCreate || mAlertDate != alertDate) {
mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
}
mAlertDate = alertDate;
int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note
.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext);
if (mIsCreate || mBgColorId != bgColorId) {
mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
}
mBgColorId = bgColorId;
long createDate = note.has(NoteColumns.CREATED_DATE) ? note
.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis();
if (mIsCreate || mCreatedDate != createDate) {
mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
}
mCreatedDate = createDate;
int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note
.getInt(NoteColumns.HAS_ATTACHMENT) : 0;
if (mIsCreate || mHasAttachment != hasAttachment) {
mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
}
mHasAttachment = hasAttachment;
long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note
.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis();
if (mIsCreate || mModifiedDate != modifiedDate) {
mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
}
mModifiedDate = modifiedDate;
long parentId = note.has(NoteColumns.PARENT_ID) ? note
.getLong(NoteColumns.PARENT_ID) : 0;
if (mIsCreate || mParentId != parentId) {
mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
}
mParentId = parentId;
String snippet = note.has(NoteColumns.SNIPPET) ? note
.getString(NoteColumns.SNIPPET) : "";
if (mIsCreate || !mSnippet.equals(snippet)) {
mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
}
mSnippet = snippet;
int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE)
: Notes.TYPE_NOTE;
if (mIsCreate || mType != type) {
mDiffNoteValues.put(NoteColumns.TYPE, type);
}
mType = type;
int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
: AppWidgetManager.INVALID_APPWIDGET_ID;
if (mIsCreate || mWidgetId != widgetId) {
mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
}
mWidgetId = widgetId;
int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note
.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE;
if (mIsCreate || mWidgetType != widgetType) {
mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
}
mWidgetType = widgetType;
long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note
.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0;
if (mIsCreate || mOriginParent != originParent) {
mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
}
mOriginParent = originParent;
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
SqlData sqlData = null;
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
for (SqlData temp : mDataList) {
if (dataId == temp.getId()) {
sqlData = temp;
}
}
}
if (sqlData == null) {
sqlData = new SqlData(mContext);
mDataList.add(sqlData);
}
sqlData.setContent(data);
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
}
return true;
}
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
JSONObject note = new JSONObject();
if (mType == Notes.TYPE_NOTE) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.ALERTED_DATE, mAlertDate);
note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
note.put(NoteColumns.CREATED_DATE, mCreatedDate);
note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
note.put(NoteColumns.PARENT_ID, mParentId);
note.put(NoteColumns.SNIPPET, mSnippet);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.WIDGET_ID, mWidgetId);
note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
JSONArray dataArray = new JSONArray();
for (SqlData sqlData : mDataList) {
JSONObject data = sqlData.getContent();
if (data != null) {
dataArray.put(data);
}
}
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
} else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
note.put(NoteColumns.ID, mId);
note.put(NoteColumns.TYPE, mType);
note.put(NoteColumns.SNIPPET, mSnippet);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);
}
return js;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return null;
}
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
public long getId() {
return mId;
}
public long getParentId() {
return mParentId;
}
public String getSnippet() {
return mSnippet;
}
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {
mDiffNoteValues.remove(NoteColumns.ID);
}
Uri uri = mContentResolver.insert(Notes.CONTENT_NOTE_URI, mDiffNoteValues);
try {
mId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
throw new ActionFailureException("create note failed");
}
if (mId == 0) {
throw new IllegalStateException("Create thread id failed");
}
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, false, -1);
}
}
} else {
if (mId <= 0 && mId != Notes.ID_ROOT_FOLDER && mId != Notes.ID_CALL_RECORD_FOLDER) {
Log.e(TAG, "No such note");
throw new IllegalStateException("Try to update note with invalid id");
}
if (mDiffNoteValues.size() > 0) {
mVersion ++;
int result = 0;
if (!validateVersion) {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?)", new String[] {
String.valueOf(mId)
});
} else {
result = mContentResolver.update(Notes.CONTENT_NOTE_URI, mDiffNoteValues, "("
+ NoteColumns.ID + "=?) AND (" + NoteColumns.VERSION + "<=?)",
new String[] {
String.valueOf(mId), String.valueOf(mVersion)
});
}
if (result == 0) {
Log.w(TAG, "there is no update. maybe user updates note when syncing");
}
}
if (mType == Notes.TYPE_NOTE) {
for (SqlData sqlData : mDataList) {
sqlData.commit(mId, validateVersion, mVersion);
}
}
}
// refresh local info
loadFromCursor(mId);
if (mType == Notes.TYPE_NOTE)
loadDataContent();
mDiffNoteValues.clear();
mIsCreate = false;
}
}

@ -0,0 +1,356 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;//包名,说明依赖关系。//
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Task extends Node {//创建Task类继承父类Node//
private static final String TAG = Task.class.getSimpleName();//调用 getSimpleName ()函数来得到类的简写名称并存入字符串TAG中//
private boolean mCompleted;//以下四个变量用于Task构造mCompleted判断是否完成//
private String mNotes;//页面标签信息//
private JSONObject mMetaInfo;//元数据信息//
private Task mPriorSibling;//对应的优先兄弟类Task的指针//
private TaskList mParent;//所在任务列表的指针//
public Task() {
super();
mCompleted = false;
mNotes = null;
mPriorSibling = null;
mParent = null;
mMetaInfo = null;
}//Task类的构造函数对对象进行初始化//
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
//共享数据存入动作类型//
try {
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);//存入当前task的指针//
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);//设置活动的id//
// index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mParent.getChildTaskIndex(this));//设置索引//
// entity_delta
JSONObject entity = new JSONObject();//新建一个 JSONObject 对象打包存放 namecreator idtype task//
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_TASK);
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}//如果存在 notes ,则将其也放入 entity 中//
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);//这里将entity变量属于JSONObject类作为一个数据存放进js变量中//
// parent_id
js.put(GTaskStringUtils.GTASK_JSON_PARENT_ID, mParent.getGid());//目的父id的类型//
// dest_parent_type
js.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT_TYPE ,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);//更新列表id存入父id//
// list_id
js.put(GTaskStringUtils.GTASK_JSON_LIST_ID, mParent.getGid());//存入列表id//
// prior_sibling_id
if (mPriorSibling != null) {
js.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, mPriorSibling.getGid());
}//如果存在优先兄弟 task则将其 id 放入 js 中//
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-create jsonobject");
}//抛出异常处理机制//
return js;
}//对操作号即actionId 进行一些操作的公用函数//
//此函数和上一个getCreatAction的功能差不多一个是creat一个updata都是对action进行操作//
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
if (getNotes() != null) {
entity.put(GTaskStringUtils.GTASK_JSON_NOTES, getNotes());
}
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate task-update jsonobject");
}//异常处理//
return js;
}
//通过云端传输的数据设置内容//
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}//如果传入的任务变量不是空的,那就说明有任务,设置修改;否则不用执行//
// last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}//设置last_modified//
// name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}//设置name//
// notes
if (js.has(GTaskStringUtils.GTASK_JSON_NOTES)) {
setNotes(js.getString(GTaskStringUtils.GTASK_JSON_NOTES));
}//设置notes//
// deleted
if (js.has(GTaskStringUtils.GTASK_JSON_DELETED)) {
setDeleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_DELETED));
}
// completed
if (js.has(GTaskStringUtils.GTASK_JSON_COMPLETED)) {
setCompleted(js.getBoolean(GTaskStringUtils.GTASK_JSON_COMPLETED));
}//异常处理//
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get task content from jsonobject");
}//异常处理,并抛出异常//
}
}
//通过本地的jsonobject获取内容//
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)
|| !js.has(GTaskStringUtils.META_HEAD_DATA)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
Log.e(TAG, "invalid type");
return;
}/*如果js不存在或者js没有元数据的开头或者js指针没有元数据那么反馈给用户出错信息*/
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
setName(data.getString(DataColumns.CONTENT));
break;
}
}//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data//
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}//异常处理操作,打印堆栈痕迹//
}
//通过内容更新本地的jsonobject//
public JSONObject getLocalJSONFromContent() {
String name = getName();
try {
if (mMetaInfo == null) {
// new task created from web
if (name == null) {
Log.w(TAG, "the note seems to be an empty one");
return null;
}//元数据类型信息为空,若名字也为空则新建一个 JSONObject 对象并将其返回//
JSONObject js = new JSONObject();//初始化四个指针//
JSONObject note = new JSONObject();
JSONArray dataArray = new JSONArray();
JSONObject data = new JSONObject();
data.put(DataColumns.CONTENT, name);
dataArray.put(data);
js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);//如果存在,那么进行更新本地信息并推送//
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
js.put(GTaskStringUtils.META_HEAD_NOTE, note);//获取metainfo中的head_note//
return js;
} else {
// synced task
JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//同步任务//
JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);// 定义一个数组并进行初始化//
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
data.put(DataColumns.CONTENT, getName());
break;
}
}//遍历 dataArray 查找与数据库中DataConstants.NOTE 记录信息一致的 data//
note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
return mMetaInfo;
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
}//异常处理并抛出//
}
public void setMetaInfo(MetaData metaData) {
if (metaData != null && metaData.getNotes() != null) {
try {
mMetaInfo = new JSONObject(metaData.getNotes());
} catch (JSONException e) {
Log.w(TAG, e.toString());
mMetaInfo = null;
}//抛出异常信息并将元数据信息置空//
}//如果元数据非空且其 notes 非空,则修改元数据类型信息//
}//设置元数据信息//
//设置同步action//
public int getSyncAction(Cursor c) {
try {
JSONObject noteInfo = null;
if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
}/*异常处理,进行同步操作,如果不成功按照对应的情况进行异常信息的反馈,比如远端文档被删除、文档不匹配等等*/
if (noteInfo == null) {
Log.w(TAG, "it seems that note meta has been deleted");
return SYNC_ACTION_UPDATE_REMOTE;
}//云端便签 id 已被删除,不存在,返回更新本地数据的同步行为//
if (!noteInfo.has(NoteColumns.ID)) {
Log.w(TAG, "remote note id seems to be deleted");
return SYNC_ACTION_UPDATE_LOCAL;
}//便签 id 不匹配,返回更新本地数据的同步行为//
// validate the note id now
if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
Log.w(TAG, "note id doesn't match");
return SYNC_ACTION_UPDATE_LOCAL;
}//代码块:信息不匹配//
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
return SYNC_ACTION_NONE;
} else {
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;
}/*判断修改后的ID匹配是否成功成功则返回无同步操作未成功则应用云端到本地返回本地同步更新操作*/
} else {
// validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}//判断gtask的id与获取的id是否匹配//
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
} else {
return SYNC_ACTION_UPDATE_CONFLICT;
}//本地id与云端id一致即更新云端//
}
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}//异常处理//
return SYNC_ACTION_ERROR;
}
public boolean isWorthSaving() {
return mMetaInfo != null || (getName() != null && getName().trim().length() > 0)
|| (getNotes() != null && getNotes().trim().length() > 0);
}//判断是否值得存放//
public void setCompleted(boolean completed) {
this.mCompleted = completed;
}//设置是否完成的标志//
public void setNotes(String notes) {
this.mNotes = notes;
}//设定是note成员变量//
public void setPriorSibling(Task priorSibling) {
this.mPriorSibling = priorSibling;
}//设置这个任务的优先兄弟//
public void setParent(TaskList parent) {
this.mParent = parent;
}//设置父节点列表//
public boolean getCompleted() {
return this.mCompleted;
}//获取 task 是否修改完毕的记录//
public String getNotes() {
return this.mNotes;
}//获取成员变量 mNotes 的信息//
public Task getPriorSibling() {
return this.mPriorSibling;
}//获取优先兄弟列表//
public TaskList getParent() {
return this.mParent;
}//获取父节点列表//
}

@ -0,0 +1,347 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.data;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
//创建继承 Node的任务表类//
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();//调用getSimpleName ()函数得到类的简称存入字符串TAG中//
private int mIndex;//当前tasklist的指针//
private ArrayList<Task> mChildren;
public TaskList() {
super();
mChildren = new ArrayList<Task>();//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList//
mIndex = 1;
}//构造方法,调用父类构造方法,同时初始化自身特有元素//
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
try {
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_CREATE);//这里指明了操作类型是“create”//
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);//调用put放入动作编号//
// index
js.put(GTaskStringUtils.GTASK_JSON_INDEX, mIndex);//放入当前任务的指针//
// entity_delta
JSONObject entity = new JSONObject();/*新建一个新的JSONObject对象用于存放一些不同的数据。最后这个结构会被放入之前创建的js对象中一起返回*/
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_CREATOR_ID, "null");
entity.put(GTaskStringUtils.GTASK_JSON_ENTITY_TYPE,
GTaskStringUtils.GTASK_JSON_TYPE_GROUP);
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} //指令类型向js对象放入数据//
catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-create jsonobject");
}
return js;
}//接受新建action,返回jsonobject//
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
//初始化 js 中的数据//
try {
// action_type
js.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_UPDATE);
// action_id
js.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, actionId);
// id
js.put(GTaskStringUtils.GTASK_JSON_ID, getGid());
// entity_delta
JSONObject entity = new JSONObject();
entity.put(GTaskStringUtils.GTASK_JSON_NAME, getName());
entity.put(GTaskStringUtils.GTASK_JSON_DELETED, getDeleted());
js.put(GTaskStringUtils.GTASK_JSON_ENTITY_DELTA, entity);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to generate tasklist-update jsonobject");
}//异常处理//
return js;
}//接受更新action返回jsonobject//
public void setContentByRemoteJSON(JSONObject js) {
if (js != null) {
try {
// id
if (js.has(GTaskStringUtils.GTASK_JSON_ID)) {
setGid(js.getString(GTaskStringUtils.GTASK_JSON_ID));
}
// last_modified
if (js.has(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED)) {
setLastModified(js.getLong(GTaskStringUtils.GTASK_JSON_LAST_MODIFIED));
}
// name
if (js.has(GTaskStringUtils.GTASK_JSON_NAME)) {
setName(js.getString(GTaskStringUtils.GTASK_JSON_NAME));
}
} //判断js对象是否为空如果为空即没有内容就不需要进行设置了若不是进行设置//
catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("fail to get tasklist content from jsonobject");
}//异常处理//
}
}//通过云端 JSON 数据设置实例化对象 js 的内容//
public void setContentByLocalJSON(JSONObject js) {
if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE)) {
Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
}//若 js 创建失败或 js 中不存在 META_HEAD_NOTE信息警告//
try {
JSONObject folder = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
String name = folder.getString(NoteColumns.SNIPPET);//若为一般类型的文件夹,获取文件夹片段字符串作为文件夹名称//
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + name);
} else if (folder.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
if (folder.getLong(NoteColumns.ID) == Notes.ID_ROOT_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT);//若为根目录文件夹设置名称MIUI系统文件夹前缀+默认文件夹名称//
else if (folder.getLong(NoteColumns.ID) == Notes.ID_CALL_RECORD_FOLDER)
setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE);//若为通话记录文件夹置名称MIUI系统文件夹前缀+通话便签文件夹名称//
else
Log.e(TAG, "invalid system folder");//错误,无效的系统文件夹//
} else {
Log.e(TAG, "error type");//其余均为错误类型//
}//若为系统类型文件夹,
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
}//通过本地 JSON 数据设置对象 js 内容//
public JSONObject getLocalJSONFromContent() {
try {
JSONObject js = new JSONObject();//创建一个 JSONObject 的实例化对象 js//
JSONObject folder = new JSONObject();//创建一个 JSONObject 的实例化对象 folder//
String folderName = getName();
if (getName().startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX))
folderName = folderName.substring(GTaskStringUtils.MIUI_FOLDER_PREFFIX.length(),
folderName.length());
folder.put(NoteColumns.SNIPPET, folderName);//如果这个文件名字是以"[MIUI_Notes]"开头,说明文件名字应该去掉这个前缀//
if (folderName.equals(GTaskStringUtils.FOLDER_DEFAULT)
|| folderName.equals(GTaskStringUtils.FOLDER_CALL_NOTE))
folder.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);/*当获取的文件夹名称是以"Default"或"Call_Note开头则为系统文件夹。否则为一般文件夹*/
else
folder.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);//普通文件//
js.put(GTaskStringUtils.META_HEAD_NOTE, folder);
return js;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return null;
}
}//通过 Content 机制获取本地 JSON 数据//
public int getSyncAction(Cursor c) {
try {
if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
// there is no local update
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// no update both side
return SYNC_ACTION_NONE;//若本地记录未修改,.最近一次修改的 id 匹配成功,返回无的同步行为//
} else {
// apply remote to local
return SYNC_ACTION_UPDATE_LOCAL;//否则返回更新本地数据的同步行为//
}
} else {
// validate gtask id
if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
Log.e(TAG, "gtask id doesn't match");
return SYNC_ACTION_ERROR;
}//如果ID未匹配抛出错误返回gtask ID未匹配//
if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
// local modification only
return SYNC_ACTION_UPDATE_REMOTE;
} else {
// for folder conflicts, just apply local modification
return SYNC_ACTION_UPDATE_REMOTE;
}//如果是最近一次修改的 id则返回云端更新的同步动作更新成功//
}
} //通过游标获取同步信息//
catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
}
return SYNC_ACTION_ERROR;
}//同步数据//
public int getChildTaskCount() {
return mChildren.size();
}//获得TaskList的大小即mChildren的大小mChildren 是TaskList 的一个实例//
public boolean addChildTask(Task task) {
boolean ret = false;
if (task != null && !mChildren.contains(task)) {
ret = mChildren.add(task);
if (ret) {
// need to set prior sibling and parent
task.setPriorSibling(mChildren.isEmpty() ? null : mChildren
.get(mChildren.size() - 1));
task.setParent(this);
}//若添加成功,则设置优先兄弟和父节点//
}// 如果传入的子任务不是空并且当前的子任务序列中不含有该任务,就将这个任务加入子任务中//
return ret;
}// 在当前任务表末尾添加新的任务//
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
return false;
}//判断插入的位置是否是正确的,如果错误,无效的索引导致添加子任务失败//
int pos = mChildren.indexOf(task);
if (task != null && pos == -1) {
mChildren.add(index, task);
// update the task list
Task preTask = null;
Task afterTask = null;//任务非空且任务表中不存在该任务,置空//
if (index != 0)
preTask = mChildren.get(index - 1);
if (index != mChildren.size() - 1)
afterTask = mChildren.get(index + 1);
task.setPriorSibling(preTask);
if (afterTask != null)
afterTask.setPriorSibling(task);//下一个任务设置兄弟任务优先级//
}//
return true;
}//在当前任务表的指定位置添加新的任务index是指针//
public boolean removeChildTask(Task task) {
boolean ret = false;/*首先声明布尔类型ret为false判断task'是否为空且是否在mChilldren中并对父兄任务做出设置*/
int index = mChildren.indexOf(task);
if (index != -1) {
ret = mChildren.remove(task);
if (ret) {
// reset prior sibling and parent
task.setPriorSibling(null);
task.setParent(null);
// update the task list
if (index != mChildren.size()) {
mChildren.get(index).setPriorSibling(
index == 0 ? null : mChildren.get(index - 1));
}//代码块:删除成功后,要对任务列表进行更新//
}//index不等于-1说明任务列表中存在该任务就要进行删除删除成功task的上一个任务指针和父指针置空//
}
return ret;
}//.删除任务表中的子任务//
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "move child task: invalid index");
return false;
}//首先判断移动的位置是否合法,错误,无效的索引导致移动子任务失败//
int pos = mChildren.indexOf(task);
if (pos == -1) {
Log.e(TAG, "move child task: the task should in the list");
return false;
}//错误,任务不在列表中导致移动子任务失败//
if (pos == index)
return true;//当前位置与索引匹配成功,返回真值//
return (removeChildTask(task) && addChildTask(task, index));//不相等则进行删除和添加即移动操作//
}//将当前TaskList中含有的某个Task移到index位置//
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
if (t.getGid().equals(gid)) {
return t;
}
}
return null;//更具判断条件返回寻找结果//
}//按gid寻找Task从头至尾遍历整个任务列表判断任务的gid与传入的gid是否相等//
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}//返回指定Task的index//
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
return null;
}
return mChildren.get(index);
}//返回指定gid的Task//
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))
return task;
}
return null;
}//获取子任务列表//
public ArrayList<Task> getChildTaskList() {
return this.mChildren;
}//获取子任务列表//
public void setIndex(int index) {
this.mIndex = index;
}//设置任务索引//
public int getIndex() {
return this.mIndex;
}//获取任务索引//
}

@ -0,0 +1,370 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.model;
import android.appwidget.AppWidgetManager;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.tool.ResourceParser.NoteBgResources;
/*申明WorkingNote类,创建小米便签的主要类,包括创建空便签,保存便签,加载小米便签内容,和设置小米便签的一些小部件之类的操作*/
public class WorkingNote {
// Note for the working note
private Note mNote;//声明一个Note类型的变量//
// Note Id
private long mNoteId;//定义NoteID//
// Note content
private String mContent;//声明便签mode//
// Note mode
private int mMode;//是否为清单模式判断条件//
private long mAlertDate;//设置闹钟时间//
private long mModifiedDate;//最后修改时间//
private int mBgColorId;//背景颜色ID//
private int mWidgetId;//小部件ID//
private int mWidgetType;//小部件类型//
private long mFolderId;//文件夹所对应的ID//
private Context mContext;//声明一个Context类型的变量用以用户与系统进行交互当前便签的上下文//
private static final String TAG = "WorkingNote";//声明 DATA_PROJECTION字符串数组//
private boolean mIsDeleted;//判断是否应该被删除//
private NoteSettingChangedListener mNoteSettingStatusListener;//一个用来监听设置是否有变化的接口//
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};//新建一个NOTE_PROJECTION数组//
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.MODIFIED_DATE
};//保存便签自身属性的字符串数组//
private static final int DATA_ID_COLUMN = 0;//以下定义的整形是上述两个列表中各元素的索引,规定每一个数据类型在哪一行//
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0;// 以下6个常量表示便签投影的0-5列//
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
mModifiedDate = System.currentTimeMillis();
mFolderId = folderId;
mNote = new Note();//加载一个已存在的便签//
mNoteId = 0;
mIsDeleted = false;//没有提供ID默认为0//
mMode = 0;
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}//该方法初始化类里的各项变量//
// Existing note construct
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
mFolderId = folderId;
mIsDeleted = false;
mNote = new Note();
loadNote();
}//从Cursor中导入Note的属性值包括文件夹id、背景颜色id、窗口图标的id和类型、提醒时间以及改动时间//
private void loadNote() {
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);//查找当前便签属性对应的便签的位置//
if (cursor != null) {
if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
}/*通过数据库调用query函数找到第一个条目通过判断cursor.moveToFirst()的值为true或false来确定查询结果是否为空不为空的话存储各项信息*/
cursor.close();
} else {
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}//.否则说明不存在这个便签,加载错误//
loadNoteData();
}
private void loadNoteData() {
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
}, null);//调用query函数查找到便签ID为mNoteId的位置并将光标移动到该位置//
if (cursor != null) {//光标存在时,将光标移动到便签的起始位置//
if (cursor.moveToFirst()) {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);//如果光标执行到第一行,获取存储内容的类型//
if (DataConstants.NOTE.equals(type)) {
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} //数据类型为文本类型时,存为文本//
else if (DataConstants.CALL_NOTE.equals(type)) {
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} //为电话号码类信息时 存为电话号码//
else {
Log.d(TAG, "Wrong note type with type:" + type);
}//如果类型错误,则提示异常//
} while (cursor.moveToNext());//查阅所有项,直到为空//
}
cursor.close();
} else {
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}//否则记录异常日志没有ID为mNoteId的数据//
}//载入便签数据//
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
note.setWidgetType(widgetType);
return note;
}//创建空的Note;传参context文件夹idwidget背景颜色//
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}//导入一个新的正在写入的便签WorkingNote//
public synchronized boolean saveNote() {
if (isWorthSaving()) {
if (!existInDatabase()) {//判断是否存在数据库中//
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}//没有成功创建一个便签时,返回出错日志//
}//判断是否有价值去保存//
mNote.syncNote(mContext, mNoteId);
/**
* Update widget content if there exist any widget of this note
*/
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE
&& mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
return true;
} else {
return false;
}//判断窗口大小是否变化,如果变化也要保存这个变化//
}//保存便签成功保存返回true否则返回false//
public boolean existInDatabase() {
return mNoteId > 0;
}//判断便签是否已经存在于数据库中mNoteID >0时存在返回true否则返回false//
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
return false;
} else {
return true;
}
}/*判断是否需要保存,已被删除或者不在数据库中但是是空便签或者已经在数据库中但本地没有修改过,都不保存*/
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}//设置监听“设置状态改变”//
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
}
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onClockAlertChanged(date, set);
}//判断是否为空//
}//设置AlertDate若 mAlertDate与data不同则更改mAlertDate并设定NoteValue//
public void markDeleted(boolean mark) {
mIsDeleted = mark;//设定标志//
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
}
}//设置删除标志//
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;//判断背景颜色//
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onBackgroundColorChanged();
}//更新背景颜色//
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
}
}//设定背景颜色//
public void setCheckListMode(int mode) {
if (mMode != mode) {//当mMode和mode不相同时进行设定//
if (mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
}
mMode = mode;//如果传入的模式与原模式不同,则更改原模式为当前模式//
mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
}//判断参数然后更改mMode//
}//设置检查列表模式,//
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType));
}//判断传入的类型是否与当前类型一样,否则更改为传入的类型并储存便签的窗口数据//
}//设置窗口类型//
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
}//判断传入是否与当前id一样否则更改为传入id//
}//设置窗口编号//
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
mNote.setTextData(DataColumns.CONTENT, mContent);
}//判断文本内容是否相同,否则更新文本//
}//设置文本内容//
public void convertToCallNote(String phoneNumber, long callDate) {
mNote.setCallData(CallNote.CALL_DATE, String.valueOf(callDate));
mNote.setCallData(CallNote.PHONE_NUMBER, phoneNumber);
mNote.setNoteValue(NoteColumns.PARENT_ID, String.valueOf(Notes.ID_CALL_RECORD_FOLDER));
}//转换到电话号码信息//
public boolean hasClockAlert() {
return (mAlertDate > 0 ? true : false);
}//检测是否有时钟提醒mAlertDate > 0返回真否则返回假//
public String getContent() {
return mContent;
}//获取便签内容//
public long getAlertDate() {
return mAlertDate;
}//获取提醒时间//
public long getModifiedDate() {
return mModifiedDate;
}//获取最近修改时间//
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}//返回来源信息//
public int getBgColorId() {
return mBgColorId;
}//获取背景颜色ID//
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}//获取标题背景颜色id//
public int getCheckListMode() {
return mMode;
}//获取检查列表模式//
public long getNoteId() {
return mNoteId;
}//获取便签id//
public long getFolderId() {
return mFolderId;
}//获取文件ID//
public int getWidgetId() {
return mWidgetId;
}//获取小部件ID//
public int getWidgetType() {
return mWidgetType;
}//获取小部件类型//
public interface NoteSettingChangedListener {
/**
* Called when the background color of current note has just changed
*/
void onBackgroundColorChanged();//背景颜色改变按钮//
/**
* Called when user set clock
*/
void onClockAlertChanged(long date, boolean set);//提醒时间按钮,可进行时间的更改和提醒的开关//
/**
* Call when user create note from widget
*/
void onWidgetChanged();//小部件的修改按钮//
/**
* Call when switch between check list mode and normal mode
* @param oldMode is previous mode before change
* @param newMode is new mode
*/
void onCheckListModeChanged(int oldMode, int newMode);//便签检查列表模式改变//
}// 该接口用来监视是否有设置改变//
}

@ -0,0 +1,224 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import net.micode.notes.data.Contact;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
public class NoteItemData {//常量标记和数据
static final String [] PROJECTION = new String [] {//PROJECTION的字符串记录基本元素
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,//某一列note的种类是text note还是folder
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 BG_COLOR_ID_COLUMN = 2;
private static final int CREATED_DATE_COLUMN = 3;
private static final int HAS_ATTACHMENT_COLUMN = 4;
private static final int MODIFIED_DATE_COLUMN = 5;
private static final int NOTES_COUNT_COLUMN = 6;
private static final int PARENT_ID_COLUMN = 7;
private static final int SNIPPET_COLUMN = 8;
private static final int TYPE_COLUMN = 9;
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;//PROJECT的字符串名称对应的值
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;//对方的id
private String mSnippet;
private int mType;
private int mWidgetId;//宽度
private int mWidgetType;//宽度形式
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;//布尔类型,判断是否为最后一项
private boolean mIsFirstItem;//判断是否为最开始的项
private boolean mIsOnlyOneItem;//判断是否只有一个便签,或者一个文件夹
private boolean mIsOneNoteFollowingFolder;//判断文件夹下是否只有一个便签
private boolean mIsMultiNotesFollowingFolder;//判断文件夹下是否有多个便签
public NoteItemData(Context context, Cursor cursor) {//初始化NoteItemData主要利用光标cursor获取的东西
mId = cursor.getLong(ID_COLUMN);//从cursor中获取数据
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) {//通过id确定电话号码
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);//使用DataUtils类中定义的函数获取电话号码信息
if (!TextUtils.isEmpty(mPhoneNumber)) {//mphonenumber里有符合字符串则用contart功能连接
mName = Contact.getContact(context, mPhoneNumber);//通过这个phonenumber调用getContact利用键值对获取对应的name
if (mName == null) {
mName = mPhoneNumber;//如果匹配失败就把phonenumber设置为name
}
}
}
if (mName == null) {//如果没有对name复制成功则把name设置为空值
mName = "";
}
checkPostion(cursor);//检查光标位置
}
private void checkPostion(Cursor cursor) {//通过光标所处位置设置标记
mIsLastItem = cursor.isLast() ? true : false;//分别为各种描述状态的变量进行赋值
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
mIsMultiNotesFollowingFolder = false;//初始化“多重子文件”“单一子文件”2个标记
mIsOneNoteFollowingFolder = false;
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {//是NOTE格式且不是第一个item
int position = cursor.getPosition();//光标指向的位置
if (cursor.moveToPrevious()) {//获取光标位置并看向上一行
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER//若光标满足SYSTEM或FOLDER格式
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {//数据行数大于当前位置+1则设置是多重子文件
if (cursor.getCount() > (position + 1)) {//数据行数大于当前位置+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;
}//若父id为保存至文件夹模式的id且电话号码不空则返回真
public boolean isLast() {
return mIsLastItem;
}//判断是否是最后一个项
public String getCallName() {
return mName;
}//获取便签名称
public boolean isFirst() {
return mIsFirstItem;
}//判断是否是第一个项
public boolean isSingle() {
return mIsOnlyOneItem;
}//判断是否只有一个项
public long getId() {
return mId;
}//获得对应的ID值
public long getAlertDate() {
return mAlertDate;
}//获得对应的提醒时间
public long getCreatedDate() {
return mCreatedDate;
}//获得创建时间
public boolean hasAttachment() {
return mHasAttachment;
}//判断是否关联桌面挂件
public long getModifiedDate() {
return mModifiedDate;
}//获得修改的时间
public int getBgColorId() {
return mBgColorId;
}//获取背景颜色
public long getParentId() {
return mParentId;
}//获得父进程的id
public int getNotesCount() {
return mNotesCount;
}//获得便签数量
public long getFolderId () {
return mParentId;
}//获得文件夹id
public int getType() {
return mType;
}//获得项的类型
public int getWidgetType() {
return mWidgetType;
}//获得桌面挂件的类型
public int getWidgetId() {
return mWidgetId;
}//获取挂件id
public String getSnippet() {
return mSnippet;
}//获得文件夹名称
public boolean hasAlert() {
return (mAlertDate > 0);
}//判读此便签是否有提醒
public boolean isCallRecord() {//判断便签项是否为CallRecord
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));// 如果父类id保存至文件夹模式并且电话号码单元不为空
}
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}//获得便签的类型
}

@ -0,0 +1,185 @@
/*
* 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;//引入tools包
import android.content.Context;//第19到31行导入各种类
import android.database.Cursor;//光标
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;//便签连接器 可能是 实现便签的编辑
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
public class NotesListAdapter extends CursorAdapter {//直译为便签列表适配器,继承自光标适配器,功能为:实现了鼠标与编辑便签的连接
private static final String TAG = "NotesListAdapter";//设置标签字符常量
private Context mContext;//便签数
private HashMap<Integer, Boolean> mSelectedIndex;//HashMap是一个散列表储存键值对的映射关系
private int mNotesCount;//便签数
private boolean mChoiceMode;//选择模式标志
public static class AppWidgetAttribute {//桌面widget的属性包括编号和类型
public int widgetId;//初始化便签链接器
public int widgetType;
};
public NotesListAdapter(Context context) {// 初始化便签链接
super(context, null);//功能描述NoteListAdapter的构造函数
//函数实现继承父类函数设置HashMap的map表实现选择item与是否选择的键值对设置context上下文初始化note数量为0
mSelectedIndex = new HashMap<Integer, Boolean>();//新建哈希表
mContext = context;//新建一个视图来存储光标所指向的数据
mNotesCount = 0;//初始便签数为0
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {//利用NotesListLtem类创建新布局
return new NotesListItem(context);//使用noteslistitem类新建一个项目选项
}
@Override
public void bindView(View view, Context context, Cursor cursor) {//将已经存在的视图和鼠标指向的数据进行捆绑
if (view instanceof NotesListItem) {//如果view是NotesListItem的实例
NoteItemData itemData = new NoteItemData(context, cursor);//新建一个项目选项并且用bind跟将view和鼠标内容便签数据捆绑在一起
((NotesListItem) view).bind(context, itemData, mChoiceMode,//用光标指向的内容新建项目并将数据、项目、鼠标、视图捆绑起来
isSelectedItem(cursor.getPosition()));
}
}
public void setCheckedItem(final int position, final boolean checked) {//设置勾选框
mSelectedIndex.put(position, checked);//根据定位和是否勾选设置下标
notifyDataSetChanged();//在修改后刷新activity
}
public boolean isInChoiceMode() {
return mChoiceMode;
}//判断单选按钮是否勾选,设置单项选项框
public void setChoiceMode(boolean mode) {//重置下标并根据参数mode设置选项
mSelectedIndex.clear();//清空勾选下表并根据当前mode设置
mChoiceMode = mode;
}
public void selectAll(boolean checked) {//选择全部选项,遍历所有光标可用的位置在判断为便签类型之后勾选单项框
Cursor cursor = getCursor();//获取光标位置
for (int i = 0; i < getCount(); i++) {//遍历可用光标位置如果光标移动且光标当前指向的便签项目类型为TYPE_NOTE则设置为勾选状态
if (cursor.moveToPosition(i)) {//遍历所有位置并设置勾选标志
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {//如果是便签状态
setCheckedItem(i, checked);// 将位置i标志为已勾选加入到 mSelectedIndex中
}
}
}
}
public HashSet<Long> getSelectedItemIds() {//建立选择项目的ID的HASH表
HashSet<Long> itemSet = new HashSet<Long>();//建立一个选项集合
for (Integer position : mSelectedIndex.keySet()) {//遍历所有的关键
if (mSelectedIndex.get(position) == true) {//判断光标位置是否可用
Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) {//原文件不需要添加则将id该下标假如选项集合中
Log.d(TAG, "Wrong item id, should not happen");//原文件不需要添加
} else {//如果不是,则加入条目集合
itemSet.add(id);//将该id加入到选项集合当中
}
}
}
return itemSet;//返回条目集合
}
public HashSet<AppWidgetAttribute> getSelectedWidget() {//建立桌面widget选项表
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();//类似于getselecteditemids的实现方法
for (Integer position : mSelectedIndex.keySet()) {//如果光标位置可用
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);//用c记录光标位置以判断是否选择了桌面挂件可用
if (c != null) {//获取光标位置可用
AppWidgetAttribute widget = new AppWidgetAttribute();//新建widget并更新ID和类型最后添加到选项表中
NoteItemData item = new NoteItemData(mContext, c);//初始化所选桌面挂件信息加入到itemSet中
widget.widgetId = item.getWidgetId();
widget.widgetType = item.getWidgetType();
itemSet.add(widget);//加入条目集合
/**
* Don't close cursor here, only the adapter could close it
*/
} else {//在这里不关闭光标而是在adapter中才能关闭光标
Log.e(TAG, "Invalid cursor");//设置标签无效的cursor
return null;
}
}
}
return itemSet;
}
public int getSelectedCount() {//被选中的进行计数的函数
Collection<Boolean> values = mSelectedIndex.values();//获取选项下标的值
if (null == values) {//如果此项值为空贼返回0
return 0;
}
Iterator<Boolean> iter = values.iterator();//初始化迭代器
int count = 0;
while (iter.hasNext()) {//如果iter后面还有则count加一
if (true == iter.next()) {//value值为真则count加一
count++;
}
}
return count;
}
public boolean isAllSelected() {//判断是否全选
int checkedCount = getSelectedCount();//通过获得计数的结果与小米便签中的数量相比较
return (checkedCount != 0 && checkedCount == mNotesCount);//对比选项数和总数是否一致且不为0
}
public boolean isSelectedItem(final int position) {//判断是否为选项表
if (null == mSelectedIndex.get(position)) {//选项下标为空则不是
return false;
}
return mSelectedIndex.get(position);//判断Item是否被选中的状态
}
@Override
protected void onContentChanged() {//activity内容变动时调用calcNotesCount计算便签数量
super.onContentChanged();//执行父类函数
calcNotesCount();
}
@Override
public void changeCursor(Cursor cursor) {//activity光标变动时调用calcNotesCount计算便签数量
super.changeCursor(cursor);//重载父类函数
calcNotesCount();//calcNotesCount函数实现
}
private void calcNotesCount() {//实现方式类似前面代码中的selectAll函数
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {//获取总数同时遍历
Cursor c = (Cursor) getItem(i);//遍历所有选项
if (c != null) {//判断语句如果光标不是null那么便得到信息便签数目加1
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {//若选项的数据类型为便签类型,那么计数+1
mNotesCount++;
}
} else {//设置为无效的光标
Log.e(TAG, "Invalid cursor");//否则就将设置为无效的光标
return;
}
}
}
}

@ -0,0 +1,122 @@
/*
* 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;//第19到30行导入各种类
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;//勾选框
public NotesListItem(Context context) {//初始化
super(context);//super()它的主要作用是调整调用父类构造函数的顺序
inflate(context, R.layout.note_item, this);//Inflate()作用就是将xml定义的一个布局找出来
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);//findViewById用于从contentView中查找指定ID的View转换出来的形式根据需要而定
mTitle = (TextView) findViewById(R.id.tv_title);// 获取题目(文件夹或便签项上的文本)
mTime = (TextView) findViewById(R.id.tv_time);//获取创建或修改时间
mCallName = (TextView) findViewById(R.id.tv_name);//获取联系人姓名
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);//获取复选框
}
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {//根据data的属性对各个控件的属性的控制主要是可见性Visibility内容setText格式setTextAppearance
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {//如果当前处于选择模式下且数据类型为便签
mCheckBox.setVisibility(View.VISIBLE);//设置View可见
mCheckBox.setChecked(checked);//设置勾选
} else {
mCheckBox.setVisibility(View.GONE);//设置复选框不可见
}
mItemData = data;//把数据传给标签
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//设置控件属性通过判断保存到文件夹的ID、当前ID以及父ID之间关系决定
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()));//设置title的内容文件夹名字+数量)
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);//设置title文本风格
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));//设置title的文本内容为便签内容的前面片段
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);//设置title的文本格式
if (data.getType() == Notes.TYPE_FOLDER) {//设置Type格式
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));//设置便签标题内容为便签的前面部分的内容+文件数+便签数
mAlert.setVisibility(View.GONE);//设置图标不可见
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);//否则设置提醒图标不可见
}
}
}
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));//将时间设置为编辑便签的时间
setBackground(data);//设置背景
}
private void setBackground(NoteItemData data) {//通过data设置背景
int id = data.getBgColorId();//获取id用此id用来获取背景颜色
if (data.getType() == Notes.TYPE_NOTE) {//若是note型文件则4种情况对于4种不同情况的背景来源
if (data.isSingle() || data.isOneFollowingFolder()) {//单个数据或只有一个子文件夹
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {//最后一个数据
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {//设置背景来源为id的最后一个数据
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));//.若不是Note类型则使用文件夹背景来源
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));//设置背景来源为id的普通数据
}
} else {//如果不是便签类型的数据
setBackgroundResource(NoteItemBgResources.getFolderBgRes());//设置背景来源为文件夹
}
}
public NoteItemData getItemData() {
return mItemData;
}//返回当前便签的数据信息
}

@ -0,0 +1,388 @@
/*
* 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;//引入ui包
import android.accounts.Account;//第19到48行导入各种类
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;//继承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;//引入R包
import net.micode.notes.data.Notes.NoteColumns;//小米便签栏
import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity {//NotesPreferenceActivity在小米便签中主要实现的是对背景颜色和字体大小的数据储存。
public static final String PREFERENCE_NAME = "notes_preferences";//继承了PreferenceActivity主要功能为对系统信息和配置进行自动保存的Activity
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) {//新建Activity
super.onCreate(icicle);//执行父类创建函数
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);//给左上角图标的左边加上一个返回的图标
addPreferencesFromResource(R.xml.preferences);//给左上角图标的左边加上一个返回的图标
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);//根据同步账户密码进行账户分组
mReceiver = new GTaskReceiver();//根据同步账户关键码来初始化分组
IntentFilter filter = new IntentFilter();//设置过滤项
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);//初始化同步组件
mOriAccounts = null;//初始化同步组件
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);//从xml获取Listview
getListView().addHeaderView(header, null, true);//在listview组件上方添加其它组件
}
@Override
protected void onResume() {//activity交互功能的实现用于接受用户的输入
super.onResume();
// need to set sync account automatically if user has added a new
// account
if (mHasAddedAccount) {//若用户新加了账户则自动设置同步账户
Account[] accounts = getGoogleAccounts();//获取google账户
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {//若账户不为空且账户增加
for (Account accountNew : accounts) {//遍历账户
boolean found = false;//更新账户
for (Account accountOld : mOriAccounts) {//循环判断当前账户列表中的账户是否与新建账户名相同
if (TextUtils.equals(accountOld.name, accountNew.name)) {//若没找到旧账户则只设置新账户为同步账户
found = true;//更新账户
break;//若是没有找到旧的账户,那么同步账号中就只添加新账户
}
}
if (!found) {//若是没有找到旧的账户,那么同步账号中就只添加新账户
setSyncAccount(accountNew.name);//保存该账户
break;
}
}
}
}
refreshUI();
}
@Override
protected void onDestroy() {//销毁Activity
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));//与google task同步便签记录
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {//建立监听器
public boolean onPreferenceClick(Preference preference) {//判断是否处于同步模式和默认的数据,指向不同的操作
if (!GTaskSyncService.isSyncing()) {//不在同步状态下,如果没有默认的账户,显示选择账户的对话框,否则显示需要改变账户的对话框
if (TextUtils.isEmpty(defaultAccount)) {//第一次设置账户
// the first time to set account
showSelectAccountAlertDialog();//第一次建立账户,显示选择账户提示对话框
} else {//若是账户已经存在,则显示修改对话框并进行修改操作
// if the account has already been set, we need to promp
// user about the risk
showChangeAccountConfirmAlertDialog();//已有账户则显示确认对话框
}
} else {//若在没有同步的情况下则在toast中显示不能修改
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);//配置资源设置一个button
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);//获取同步按键和同步时间显示
// set button state
if (GTaskSyncService.isSyncing()) {//同步状态下按键显示“取消同步”,设置相关监听器
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {//设置点击监听器
public void onClick(View v) {//设置取消同步的响应方法
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);//响应点击的行为:取消同步
}
});
} else {//非同步状态下按键显示“立即同步”,设置相关监听器
syncButton.setText(getString(R.string.preferences_button_sync_immediately));//若是不同步则设置按钮显示的文本为“立即同步”以及对应监听器
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {//点击行为
GTaskSyncService.startSync(NotesPreferenceActivity.this);//开始同步
}
});
}
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));//如果没有账户,则不可选“立即同步”的按键
// set last sync time
if (GTaskSyncService.isSyncing()) {//设置按键的可用性
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);//根据当前同步服务器设置时间显示框的文本以及可见性
} else {//若是非同步情况
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {//如果有上次修改时间
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));//非同步时若最近同步时间不为0则显示最近同步时间
lastSyncTimeView.setVisibility(View.VISIBLE);//根据最后同步时间的信息来编辑时间显示框的文本内容和可见性
} else {
lastSyncTimeView.setVisibility(View.GONE);//最近同步时间为空设置同步时间不可见
}
}
}
private void refreshUI() {//刷新标签界面
loadAccountPreference();
loadSyncButton();//加载“保存”按钮
}
private void showSelectAccountAlertDialog() {//显示账户选择的对话框并进行账户的设置
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);//创建一个新的对话框
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);//文本试图设置
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);//设置标题以及子标题的内容
dialogBuilder.setPositiveButton(null, null);//不设置“确定”的按钮
Account[] accounts = getGoogleAccounts();//获得谷歌账户
String defAccount = getSyncAccountName(this);//默认的账户
mOriAccounts = accounts;//获取同步账户信息
mHasAddedAccount = false;
if (accounts.length > 0) {//若账户不为空
CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;
int checkedItem = -1;
int index = 0;
for (Account account : accounts) {//通过循环检查账户列表
if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index;
}//在账户列表中查询到所需账户
items[index++] = account.name;
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,//在对话框建立一个单选的复选框
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {//响应对话框的点击,添加点击监听器,并完成一些操作
setSyncAccount(itemMapping[which].toString());//点击则开始设置同步账户
dialog.dismiss();//取消对话框
refreshUI();//刷新界面
}
});
}
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);//视图,添加新的账户
dialogBuilder.setView(addAccountView);//设置“添加账户”的视图
final AlertDialog dialog = dialogBuilder.show();//显示对话框
addAccountView.setOnClickListener(new View.OnClickListener() {//设置监听器
public void onClick(View v) {//响应点击添加账户的请求
mHasAddedAccount = true;//将新加账户的hash置为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) {//设置对话框要显示的一个list用于显示几个命令时,即changeremovecancel
if (which == 0) {//进入账户选择对话框
showSelectAccountAlertDialog();//显示账户选择提示对话框
} else if (which == 1) {//删除同步账户
removeSyncAccount();//删除账户并且跟新便签界面
refreshUI();
}
}
});
dialogBuilder.show();//显示对话框
}
private Account[] getGoogleAccounts() {//获取谷歌账户,可通过账户管理器直接获取
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
private void setSyncAccount(String account) {//设置同步账户
if (!getSyncAccountName(this).equals(account)) {//如果该账号不在同步账号列表中
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();//编辑共享首选项
if (account != null) {//编辑共享的首选项
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}//将该账号加入到首选项中
editor.commit();//提交修改的数据
// clean up last sync time
setLastSyncTime(this, 0);//将最后同步时间清零
// clean up local gtask related info
new Thread(new Runnable() {// 新线程的创建
public void run() {//清除本地的gtask关联的信息
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,//设置一个toast提示信息提示用户成功设置同步
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();//将toast的文本信息置为“设置账户成功”并显示出来
}
}
private void removeSyncAccount() {//删除同步账户
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);//SharedPreferences是以键值对的形式存储数据的其使用非常简单能够轻松的存放数据和读取数据
SharedPreferences.Editor editor = settings.edit();//设置共享首选项
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {//假如当前首选项中有账户就删除
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {//删除当前首选项中有账户时间
editor.remove(PREFERENCE_LAST_SYNC_TIME);//如果包含其中就将时间也清除
}
editor.commit();//提交更新后的数据
// clean up local gtask related info
new Thread(new Runnable() {//新线程的创建
public void run() {//清除本地的gtask关联的信息将一些参数设置为0或NULL
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
public static String getSyncAccountName(Context context) {//获取同步账户名称,通过共享的首选项里的信息直接获取
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);//获取同步账户名称
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
public static void setLastSyncTime(Context context, long time) {//设置最终同步的时间
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();//从共享首选项中找到相关账户并获取其编辑器
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();//编辑最终同步时间并提交更新
}
public static long getLastSyncTime(Context context) {//获取最终同步时间
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);//通过共享,获取时间
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
private class GTaskReceiver extends BroadcastReceiver {//接受同步信息
@Override
public void onReceive(Context context, Intent intent) {//刷新界面,判断是否同步状态下
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {//获取随广播而来的Intent中的同步服务的数据
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()) {//根据选项的id选择这里只有一个主页
case android.R.id.home://返回主界面
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);//创建活动
return true;
default://在主页情况下在创建连接组件intent发出清空的信号并开始一个相应的activity
return false;
}
}
}

@ -0,0 +1,348 @@
/*
* 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.
*/
//BackupUtils 是一个备份工具类,用于数据备份读取和显示
package net.micode.notes.tool;//定义小米便签类:功能类
//调用了Android的包
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class BackupUtils {
private static final String TAG = "BackupUtils";
// Singleton stuff
private static BackupUtils sInstance;
public static synchronized BackupUtils getInstance(Context context) {
//ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程例如线程A
//运行到这个方法时,都要检查有没有其它线程B或者C、 D等正在用这个方法(或者该类的其他同步方法)有的话要等正在使用synchronized方法的线程B或者C 、D运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。
//它包括两种用法synchronized 方法和 synchronized 块
if (sInstance == null) {//如果当前备份不存在,则新声明一个
sInstance = new BackupUtils(context);
}
return sInstance;
}
/**
* Following states are signs to represents backup or restore
* status
*/
// Currently, the sdcard is not mounted SD卡没有被装入手机
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist 备份文件夹不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs 数据已被破坏,可能被修改
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails 超时异常
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success 成功存储
public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}//初始化函数
private static boolean externalStorageAvailable() {//外部存储功能是否可用
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
public int exportToText() {
return mTextExport.exportToText();
}//输出至文本
public String getExportedTextFileName() {
return mTextExport.mFileName;
}//获取输出的文本文件名
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}//获得输出文本的文本路径
private static class TextExport {//文本输出类。包含笔记ID、修改日期等数据及其格式
private static final String[] NOTE_PROJECTION = {//定义了一个数组储存便签的信息
NoteColumns.ID,
NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET,
NoteColumns.TYPE
};
private static final int NOTE_COLUMN_ID = 0;//初始化便签ID
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;//初始化修改时间
private static final int NOTE_COLUMN_SNIPPET = 2;//初始化数据标识
private static final String[] DATA_PROJECTION = {//定义字符串存储数据的基本信息
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
//标识设定数据内容标识为0媒体类型标识为1访问日期标识为2电话号码标识为4
private static final int DATA_COLUMN_CONTENT = 0;
private static final int DATA_COLUMN_MIME_TYPE = 1;
private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
//文档格式标识名称为0;日期为1;内容为2
private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2;
private Context mContext;//为该类定义一个内部上下类
private String mFileName;//定义文件名
private String mFileDirectory;//定义文件夹字符串
public TextExport(Context context) {//从context类实例中获取信息给对应的属性赋初始值
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context;
mFileName = "";
mFileDirectory = "";
}
private String getFormat(int id) {
return TEXT_FORMAT[id];
}//通过ID返回文件的格式信息
/**
* Export the folder identified by folder id to text
*/
private void exportFolderToText(String folderId, PrintStream ps) {//通过文件夹ID将目录导出后成文件
// Query notes belong to this folder
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
}, null);
if (notesCursor != null) {//利用光标来扫描内容区别为callnote和note两种靠ps.printline输出
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date ps里面保存有这份note的日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); //将文件导出到text
} while (notesCursor.moveToNext());
}
notesCursor.close();
}
}
/**
* Export note identified by id to a print stream
*/
private void exportNoteToText(String noteId, PrintStream ps) {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
if (dataCursor != null) { //利用光标来扫描内容区别为callnote和note两种靠ps.printline输出
if (dataCursor.moveToFirst()) {
do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(phoneNumber)) {//判断是否为空字符
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
if (!TextUtils.isEmpty(location)) {//判断是否存在位置信息,若存在就打印位置信息
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {//如果只有便签的内容且存在,就将其输出
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
if (!TextUtils.isEmpty(content)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content));
}
}
} while (dataCursor.moveToNext());
}
dataCursor.close();//关闭游标
}
// print a line separator between note
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER// 在Note下方输出一条线
});
} catch (IOException e) {
Log.e(TAG, e.toString());//检测异常如果有异常输出红色TAG
}
}
/**
* Note will be exported as text which is user readable
*/
public int exportToText() {//以TEXT形式输出到外部设备
if (!externalStorageAvailable()) {//检查外部设备是否安装好,没有的话则输出显示错误的信息。
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {//获得外部设备存储路径
Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
Cursor folderCursor = mContext.getContentResolver().query(//定位需要导出的文件夹
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
if (folderCursor != null) {//导出文件夹,把里面的便签导出来
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
String folderName = "";
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
}
if (!TextUtils.isEmpty(folderName)) {//判断文件夹名称是否为空,不为空则输出格式和名称
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
String folderId = folderCursor.getString(NOTE_COLUMN_ID);// 通过便签ID得到folderID
exportFolderToText(folderId, ps);
} while (folderCursor.moveToNext());
}
folderCursor.close();
}
// Export notes in root's folder
Cursor noteCursor = mContext.getContentResolver().query(//将根目录里的便签导出
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
if (noteCursor != null) {
if (noteCursor.moveToFirst()) {
do {//将便签的修改日期显示在屏幕上
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
String noteId = noteCursor.getString(NOTE_COLUMN_ID);//找到这块数据的ID
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());//光标下移
}
noteCursor.close();
}
ps.close();
return STATE_SUCCESS;
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {//获取指向文件的打印流
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,//初始化存储在SD卡的文件
R.string.file_name_txt_format);
if (file == null) {//如果文件为空,则创建失败
Log.e(TAG, "create file to exported failed");
return null;
}
mFileName = file.getName();//获得文件名
mFileDirectory = mContext.getString(R.string.file_path);//文件输出流及异常处理
PrintStream ps = null;
try {//将ps输出流输出到特定的文件目的就是导出到文件而不是直接输出
FileOutputStream fos = new FileOutputStream(file);
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (NullPointerException e) {
e.printStackTrace();
return null;
}
return ps;
}
}
/**
* Generate the text file to store imported data
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {//生成存储文件安装在SD卡上
StringBuilder sb = new StringBuilder();///构建一个动态字符串将外部存储器路径、文件路径、编辑时间加入到其中
sb.append(Environment.getExternalStorageDirectory());//外部SD卡的存储路径
sb.append(context.getString(filePathResId));//文件的存储路径
File filedir = new File(sb.toString());
sb.append(context.getString(
fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd),//将当前的系统时间以预定的格式输出
System.currentTimeMillis())));
File file = new File(sb.toString());//将输出连接到一个文件里
try {//如果这些文件不存在,则新建
if (!filedir.exists()) {
filedir.mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
return file;
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {//输入输出异常处理
e.printStackTrace();
}
return null;
}
}

@ -0,0 +1,78 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//本文件处理联系人相关信息
package net.micode.notes.data;
//以下几个是导入Android自带的几个库文件
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;// 安卓日志输出工具类
import java.util.HashMap;// HashMap 是一个利用哈希表原理来存储元素的集合,这里用来实现存储联系人列表
public class Contact { //联系人
private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact";//定义标签 就是类名 是为了方便获取本类名
// 定义字符串CALLER_ID_SELECTION
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
// 获取联系人
public static String getContact(Context context, String phoneNumber) {
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 查找HashMap中是否已有phoneNumber信息
if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber);
}
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));//toCallerIDMinMatch是安卓自带的号码匹配工具截取查询号码的后7位作为匹配依据
// 查找数据库中phoneNumber的信息
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
// 判定查询结果
// moveToFirst()返回第一条
if (cursor != null && cursor.moveToFirst()) {
try {// 找到相关信息
String name = cursor.getString(0);
sContactCache.put(phoneNumber, name);
return name;// 异常
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString());
return null;
} finally {
cursor.close(); // 未找到相关信息
}
} else {
Log.d(TAG, "No contact matched with number:" + phoneNumber);//联系人中没有匹配到该手机号码的主人
return null;
}
}
}

@ -0,0 +1,296 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//对数据处理的操作定义
package net.micode.notes.tool;
//导入相关的库
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;//批量删除笔记
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;//操作方法
import android.database.Cursor;
import android.os.RemoteException;//远程交互
import android.util.Log;
import net.micode.notes.data.Notes;//便签数据类相关的包
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.NoteColumns;//便签栏的数据
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import java.util.ArrayList;//导入数组处理包
import java.util.HashSet;//导入需要的包
public class DataUtils {//数据的集成工具类
public static final String TAG = "DataUtils";
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {//实现了批量删除便签
if (ids == null) {//判断笔记id是否为空
Log.d(TAG, "the ids is null");
return true;
}
if (ids.size() == 0) { //判断笔记内容是否为空
Log.d(TAG, "no id is in the hashset");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();//提供一个事件的列表
for (long id : ids) {//遍历数据,如果此数据为根目录则跳过此数据不删除,如果不是根目录则将此数据删除
if(id == Notes.ID_ROOT_FOLDER) {//避免出现删除系统目录的情况
Log.e(TAG, "Don't delete system folder root");
continue;
}
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));//newDelete用来实现删除
operationList.add(builder.build());//将操作添加至列表
}
try {//返回被删除的数据如果返回为空则删除失败返回false打印异常信息删除成功返回true
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {//对错误进行处理,并将错误存储到日志当中
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
}
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {//用来把某一个便签移动到某一个文件夹
ContentValues values = new ContentValues();
values.put(NoteColumns.PARENT_ID, desFolderId);//将PARENT_ID更改为目标目录ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1);//设置修改符号为1
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);//对移动过的便签进行数据的更新
}
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {//批量的将标签移动到另一个目录下
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {//将ids里包含的每一列的数据逐次加入到operationList中等待最后的批量处理
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
operationList.add(builder.build());
}
try {//同上的容错机制,对于一些异常进行处理与汇报
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);//调用applybatch一次性处理一个操作列表
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
return true;
} catch (RemoteException e) {//异常处理
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
return false;
}
/**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*/
public static int getUserFolderCount(ContentResolver resolver) {//获取用户文件夹数
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);//String.valueof将形参转成字符串返回
int count = 0;
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {// 索引序号超出界限
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
cursor.close();//关闭游标
}
}
}
return count;
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {//是否在便签数据库中可见
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,//通过withappendedid的方法为uri加上id
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},//表示筛选出列中type等于string数组中type且每一项的PARENT_ID不等于Notes.ID.TRAXH_FOLDER
null);
boolean exist = false;//查询文件
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {//判断该note是否在数据库中存在
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
boolean exist = false;//初始化存在状态
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {//检查文件名字是否可见
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {//通过名字查询文件是否存在
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);//筛选出type相同并且未被删除名字对的上的
boolean exist = false;
if(cursor != null) {
if(cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;
}
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {//使用hashset来存储不同窗口的id和type并且建立对应关系
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
new String[] { String.valueOf(folderId) },
null);//查询条件是父ID是否为传入的folderId
HashSet<AppWidgetAttribute> set = null;//根据窗口的记录一一添加对应的属性值
if (c != null) {
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {//把每一个条目对应的窗口id和type记录下来放到set里面。每一行的第0个int和第1个int分别对应widgetId和widgetType
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
set.add(widget);
} catch (IndexOutOfBoundsException e) {//当下标超过边界,那么返回错误
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
}
c.close();
}
return set;
}
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {//通过笔记ID获取号码
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.PHONE_NUMBER },
CallNote.NOTE_ID + "=? AND " + CallNote.MIME_TYPE + "=?",
new String [] { String.valueOf(noteId), CallNote.CONTENT_ITEM_TYPE },
null);//新建字符列表
if (cursor != null && cursor.moveToFirst()) {//获取电话号码,并处理异常。
try {//返回电话号码
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
cursor.close();
}
}
return "";
}
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {//获取ID通过电话号码和呼叫日期
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
new String [] { CallNote.NOTE_ID },
CallNote.CALL_DATE + "=? AND " + CallNote.MIME_TYPE + "=? AND PHONE_NUMBERS_EQUAL("
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
cursor.close();
}
return 0;
}
public static String getSnippetById(ContentResolver resolver, long noteId) {//按ID获取片段
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
new String [] { String.valueOf(noteId)},
null);
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
snippet = cursor.getString(0);
}
cursor.close();
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
//IllegalArgumentException是非法传参异常也就是参数传的类型冲突属于RunTimeException运行时异常
}
public static String getFormattedSnippet(String snippet) {//对字符串进行格式处理,将字符串两头的空格去掉,同时将换行符去掉
if (snippet != null) {
snippet = snippet.trim();//trim()函数,将字符串两头的空格去除
int index = snippet.indexOf('\n');
if (index != -1) {
snippet = snippet.substring(0, index);//截取到第一个换行符
}
}
return snippet;
}
}

@ -0,0 +1,114 @@
/*
* 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.
*/
//定义了很多的静态字符串目的就是为了提供jsonObject中相应字符串的"key"。
// 把这些静态的定义单独写到了一个类里面,这是非常好的编程规范
package net.micode.notes.tool;
public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id";//行动ID
public final static String GTASK_JSON_ACTION_LIST = "action_list";//任务列表
public final static String GTASK_JSON_ACTION_TYPE = "action_type";//任务类型
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";//新建
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";//移动
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";//更新
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";//子实体
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";//客户端
public final static String GTASK_JSON_COMPLETED = "completed";
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";//当前列表位置
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
public final static String GTASK_JSON_DELETED = "deleted";//删除
public final static String GTASK_JSON_DEST_LIST = "dest_list";
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
public final static String GTASK_JSON_ID = "id";
public final static String GTASK_JSON_INDEX = "index";//索引
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
public final static String GTASK_JSON_LIST_ID = "list_id";
public final static String GTASK_JSON_LISTS = "lists";
public final static String GTASK_JSON_NAME = "name";
public final static String GTASK_JSON_NEW_ID = "new_id";
public final static String GTASK_JSON_NOTES = "notes";
public final static String GTASK_JSON_PARENT_ID = "parent_id";
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
public final static String GTASK_JSON_RESULTS = "results";
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
public final static String GTASK_JSON_TASKS = "tasks";//任务栏
public final static String GTASK_JSON_TYPE = "type";
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
public final static String GTASK_JSON_TYPE_TASK = "TASK";//任务
public final static String GTASK_JSON_USER = "user";
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
public final static String FOLDER_DEFAULT = "Default";
public final static String FOLDER_CALL_NOTE = "Call_Note";//呼叫小米便签
public final static String FOLDER_META = "METADATA";
public final static String META_HEAD_GTASK_ID = "meta_gid";
public final static String META_HEAD_NOTE = "meta_note";
public final static String META_HEAD_DATA = "meta_data";//数据
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
}

@ -0,0 +1,285 @@
/*
* 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.
*/
//便签的数据库,该类主要实现了对便签的相关属性包括Anthority, Tag以及数据联系人的信息进行保存管理其中主要实现了对
// 若干属性的定义并创建了DataColumnsDataColumns接口的定义该两个接口可用于其余类的实现
// 在便签管理中实现TextNote,CallNote两个类用于对便签内容的保存。
package net.micode.notes.data;//package (包) 的作用是把不同的 java 程序分类保存,更方便的被其他 java 程序调用。
// 一个包package可以定义为一组相互联系的类型类、接口、枚举和注释为这些类型提供访问保护和命名空间管理的功能。
import android.net.Uri;// Notes 类中定义了很多常量这些常量大多是int型和string型
public class Notes {
public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes";
//以下三个常量对NoteColumns.TYPE的值进行设置时会用到
public static final int TYPE_NOTE = 0;
public static final int TYPE_FOLDER = 1;
public static final int TYPE_SYSTEM = 2;
/**
* Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/
public static final int ID_ROOT_FOLDER = 0;
public static final int ID_TEMPARAY_FOLDER = -1;//临时文件夹ID=-1
public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_TRASH_FOLER = -3;
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_4X = 1;
public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}
/**
* Uri to query all notes and folders//查询所有笔记和文件夹的uri
*/
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");//定义查询便签和文件夹的指针。
/**
* Uri to query data
*/
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");//定义查找数据的指针
// 定义NoteColumns的常量,用于后面创建数据库的表头
public interface NoteColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";//每一行的ID
/**
* The parent's id for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String PARENT_ID = "parent_id";//父节点id的字符串
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";//创建时间
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";//最新的更新时间
/**
* Alert date
* <P> Type: INTEGER (long) </P>
*/
public static final String ALERTED_DATE = "alert_date";//提醒时间
/**
* Folder's name or text content of note
* <P> Type: TEXT </P>
*/
public static final String SNIPPET = "snippet";//便签的摘要
/**
* Note's widget id
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_ID = "widget_id";//小部件的ID
/**
* Note's widget type
* <P> Type: INTEGER (long) </P>
*/
public static final String WIDGET_TYPE = "widget_type";//小部件的类型
/**
* Note's background color's id
* <P> Type: INTEGER (long) </P>
*/
public static final String BG_COLOR_ID = "bg_color_id";//背景颜色
/**
* For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment
* <P> Type: INTEGER </P>
*/
public static final String HAS_ATTACHMENT = "has_attachment";//是否有附件
/**
* Folder's count of notes
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTES_COUNT = "notes_count";//文件夹中的便签数量
/**
* The file type: folder or note
* <P> Type: INTEGER </P>
*/
public static final String TYPE = "type";//文件类型
/**
* The last sync id
* <P> Type: INTEGER (long) </P>
*/
public static final String SYNC_ID = "sync_id";//同步
/**
* Sign to indicate local modified or not
* <P> Type: INTEGER </P>
*/
public static final String LOCAL_MODIFIED = "local_modified";//本地信号是否修改
/**
* Original parent id before moving into temporary folder
* <P> Type : INTEGER </P>
*/
public static final String ORIGIN_PARENT_ID = "origin_parent_id";//移动到临时文件夹之前的父文件夹
/**
* The gtask id
* <P> Type : TEXT </P>
*/
public static final String GTASK_ID = "gtask_id";//后台任务ID
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
public static final String VERSION = "version";//版本号
}//这些常量主要是定义便签的属性的
// 定义DataColumns的常量,用于后面创建数据库的表头
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
*/
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
*/
public static final String NOTE_ID = "note_id";//便签ID
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
public static final String CREATED_DATE = "created_date";//创建时间
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
public static final String MODIFIED_DATE = "modified_date";//修改时间
/**
* Data's content
* <P> Type: TEXT </P>
*/
public static final String CONTENT = "content";//内容
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA1 = "data1";//文本内容的数据结构
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
public static final String DATA2 = "data2";//文本模式
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
public static final String DATA5 = "data5";
}//主要是定义存储便签内容数据的
public static final class TextNote implements DataColumns {//通过接口对数据进行继承
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/
public static final String MODE = DATA1;
public static final int MODE_CHECK_LIST = 1;// 设置为检查列表模式
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";//修改CONTENT_TYPE属性即内容类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";//内容项目的类型
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");//content 的索引标识符
}//文本内容的数据结构
public static final class CallNote implements DataColumns {//通话数据CallNote继承了接口类而后进行了格式适配
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>0
*/
public static final String CALL_DATE = DATA1;//存放通话时间
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
public static final String PHONE_NUMBER = DATA3;//存放通话号码信息
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");//内容标识符
}//电话内容的数据结构
}

@ -0,0 +1,372 @@
//用于存储Notes的数据以及根据数据更改Notes结构体的变量
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.data;//声明包
import android.content.ContentValues;//就是用于保存一些数据string boolean byte double float int long short ...)信息,这些信息可以被数据库操作时使用。
import android.content.Context;//加载和访问资源。android中主要是这两个功能但是这里具体不清楚
import android.database.sqlite.SQLiteDatabase;//主要提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query()。配合content.values
import android.database.sqlite.SQLiteOpenHelper;//用来管理数据的创建和版本更新
import android.util.Log;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
//数据库操作用SQLOpenhelper,对一些note和文件进行数据库的操作比如删除文件后将文件里的note也相应删除
public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "note.db";
private static final int DB_VERSION = 4;
public interface TABLE {//接口分成note和data在后面的程序里分别使用过
public static final String NOTE = "note";
public static final String DATA = "data";
}
private static final String TAG = "NotesDatabaseHelper";
private static NotesDatabaseHelper mInstance;
private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")";//创建一个note时数据库中需要存储的项目的名称就相当于创建一个表格的表头的内容。
private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")";//和上面的功能一样,主要是存储的项目不同
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";//存储便签编号的一个数据表格
/**
* Increase folder's note count when move note to the folder
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";//在文件夹中移入一个Note之后需要更改的数据的表格
/**
* Decrease folder's note count when move note from folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " +
" AFTER UPDATE OF " + NoteColumns.PARENT_ID + " ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0" + ";" +
" END";//在文件夹中移出一个Note之后需要更改的数据的表格
/**
* Increase folder's note count when insert new note to the folder
*/
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " +
" AFTER INSERT ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + " + 1" +
" WHERE " + NoteColumns.ID + "=new." + NoteColumns.PARENT_ID + ";" +
" END";//在文件夹中插入一个Note之后需要更改的数据的表格
/**
* Decrease folder's note count when delete note from the folder
*/
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN " +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.NOTES_COUNT + "=" + NoteColumns.NOTES_COUNT + "-1" +
" WHERE " + NoteColumns.ID + "=old." + NoteColumns.PARENT_ID +
" AND " + NoteColumns.NOTES_COUNT + ">0;" +
" END";//在文件夹中删除一个Note之后需要更改的数据的表格
/**
* Update note's content when insert data with type {@link DataConstants#NOTE}
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " +
" AFTER INSERT ON " + TABLE.DATA +
" WHEN new." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";//在文件夹中对一个Note导入新的数据之后需要更改的数据的表格
/**
* Update note's content when data with {@link DataConstants#NOTE} type has changed
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " +
" AFTER UPDATE ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=new." + DataColumns.CONTENT +
" WHERE " + NoteColumns.ID + "=new." + DataColumns.NOTE_ID + ";" +
" END";//Note数据被修改后需要更改的数据的表格
/**
* Update note's content when data with {@link DataConstants#NOTE} type has deleted
*/
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " +
" AFTER delete ON " + TABLE.DATA +
" WHEN old." + DataColumns.MIME_TYPE + "='" + DataConstants.NOTE + "'" +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.SNIPPET + "=''" +
" WHERE " + NoteColumns.ID + "=old." + DataColumns.NOTE_ID + ";" +
" END";//Note数据被删除后需要更改的数据的表格
/**
* Delete datas belong to note which has been deleted
*/
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.DATA +
" WHERE " + DataColumns.NOTE_ID + "=old." + NoteColumns.ID + ";" +
" END";//删除已删除的便签的数据后需要更改的数据的表格
/**
* Delete notes belong to folder which has been deleted
*/
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " +
" AFTER DELETE ON " + TABLE.NOTE +
" BEGIN" +
" DELETE FROM " + TABLE.NOTE +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";//删除已删除的文件夹的便签后需要更改的数据的表格
/**
* Move notes belong to folder which has been moved to trash folder
*/
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " +
" AFTER UPDATE ON " + TABLE.NOTE +
" WHEN new." + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" BEGIN" +
" UPDATE " + TABLE.NOTE +
" SET " + NoteColumns.PARENT_ID + "=" + Notes.ID_TRASH_FOLER +
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END";//还原垃圾桶中便签后需要更改的数据的表格
public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}//构造函数,传入数据库的名称和版本
public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db);
createSystemFolder(db);
Log.d(TAG, "note table has been created");
}//创建表格(用来存储标签属性)
private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS delete_data_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS folder_delete_notes_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS folder_move_notes_on_trash");
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER);
db.execSQL(NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER);
db.execSQL(NOTE_DELETE_DATA_ON_DELETE_TRIGGER);
db.execSQL(NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER);
db.execSQL(FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER);
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
}//execSQL是数据库操作的API主要是更改行为的SQL语句。
//在这里主要是用来重新创建上述定义的表格用的,先删除原来有的数据库的触发器再重新创建新的数据库
private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues();
/**
* call record foler for call notes
*/
//储存呼叫记录的文件夹
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* root folder which is default folder
*/
//设置根目录为默认文件夹
values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* temporary folder which is used for moving note
*/
//设置临时文件夹作为文件移动的有效目标
values.clear();
values.put(NoteColumns.ID, Notes.ID_TEMPARAY_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
/**
* create trash folder
*/
//创建回收站
values.clear();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}//创建几个系统文件夹
public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db);
db.execSQL(CREATE_DATA_NOTE_ID_INDEX_SQL);
Log.d(TAG, "data table has been created");
}//创建表格(用来存储标签内容)
private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_delete");
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER);
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
}//同上面的execSQL
static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context);
}
return mInstance;
}//上网查是为解决同一时刻只能有一个线程执行.
//在写程序库代码时,有时有一个类需要被所有的其它类使用,
//但又要求这个类只能被实例化一次,是个服务类,定义一次,其它类使用同一个这个类的实例
@Override
public void onCreate(SQLiteDatabase db) {
createNoteTable(db);
createDataTable(db);
}//实现两个表格(上面创建的两个表格)
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//更新数据库
// 提供了onCreate()、onUpgrade()两个回调函数,允许我们再创建和升级数据库时,进行自己的操作
boolean reCreateTriggers = false;//是否重建
boolean skipV2 = false;//是否从V2升级到V3
if (oldVersion == 1) {//从V1升级到V2
upgradeToV2(db);
skipV2 = true; // this upgrade including the upgrade from v2 to v3
oldVersion++;
}
if (oldVersion == 2 && !skipV2) {//从V2升级到V3
upgradeToV3(db);
reCreateTriggers = true;
oldVersion++;
}
if (oldVersion == 3) {//从V3升级到V4
upgradeToV4(db);
oldVersion++;
}
if (reCreateTriggers) {//如果重新创建创建新的note table和datatable
reCreateNoteTableTriggers(db);
reCreateDataTableTriggers(db);
}
if (oldVersion != newVersion) {//判断是否版本升级成功若版本号没有升级到相应new版本这个就会抛出异常
throw new IllegalStateException("Upgrade notes database to version " + newVersion
+ "fails");
}
}//数据库版本的更新(数据库内容的更改)
private void upgradeToV2(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE.NOTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE.DATA);
createNoteTable(db);
createDataTable(db);
}//更新到V2版本
private void upgradeToV3(SQLiteDatabase db) {
// drop unused triggers
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_delete");
db.execSQL("DROP TRIGGER IF EXISTS update_note_modified_date_on_update");
// add a column for gtask id
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.GTASK_ID
+ " TEXT NOT NULL DEFAULT ''");
// add a trash system folder
ContentValues values = new ContentValues();
values.put(NoteColumns.ID, Notes.ID_TRASH_FOLER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values);
}//更新到V3版本
private void upgradeToV4(SQLiteDatabase db) {
db.execSQL("ALTER TABLE " + TABLE.NOTE + " ADD COLUMN " + NoteColumns.VERSION
+ " INTEGER NOT NULL DEFAULT 0");
}//更新到V4版本
}

@ -0,0 +1,335 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//便签信息提供类
package net.micode.notes.data;//声明所属包名
//引用android自带的类包括数据库等
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
//ContentProvider提供的方法
//query查询
//insert插入
//update更新
//delete删除
//getType得到数据类型
public class NotesProvider extends ContentProvider {//为存储和获取数据提供接口。可以在不同的应用程序之间共享数据
private static final UriMatcher mMatcher;// UriMatcher用于匹配Uri
private NotesDatabaseHelper mHelper;//数据库助手实例化
private static final String TAG = "NotesProvider";//给部分变量赋值
private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;
static {
// 创建UriMatcher时调用UriMatcher(UriMatcher.NO_MATCH)表示不匹配任何路径的返回码
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 把需要匹配Uri路径全部给注册上
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
}
/**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*/
// 声明 NOTES_SEARCH_PROJECTION
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 声明NOTES_SNIPPET_SEARCH_QUERY
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override
// Context只有在onCreate()中才被初始化
// 对mHelper进行实例化
public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext());
return true;
}
@Override
// 查询uri在数据库中对应的位置
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor c = null;
// 获取可读数据库
SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null;
// 匹配查找uri
switch (mMatcher.match(uri)) {
// 对于不同的匹配值,在数据库中查找相应的条目
case URI_NOTE://查询便签
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM://查询便签条目
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA://查询数据
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM://查询id对应的具体数据
id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_SEARCH://匹配到搜索
case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) {
// 不合法的参数异常
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
String searchString = null;
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
if (uri.getPathSegments().size() > 1) {
// getPathSegments()方法得到一个String的List
// 在uri.getPathSegments().get(1)为第2个元素
searchString = uri.getPathSegments().get(1);
}
} else {
searchString = uri.getQueryParameter("pattern");
}
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default:
// 抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
return c;
}
@Override
// 插入一个uri
public Uri insert(Uri uri, ContentValues values) {
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) {
// 新增一个条目
case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
// 如果是数据类型查找NOTE_ID
case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {//错误的数据格式没有note的id
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
insertedId = dataId = db.insert(TABLE.DATA, null, values);//把便签数据插入到数据库
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);//抛出异常未知的URI
}
// Notify the note uri
// notifyChange获得一个ContextResolver对象并且更新里面的内容
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
// 返回插入的uri的路径
return ContentUris.withAppendedId(uri, insertedId);
}
@Override
// 删除一个uri
public int delete(Uri uri, String selection, String[] selectionArgs) {
//Uri代表要操作的数据Android上可用的每种资源 -包括 图像、视频片段、音频资源等都可以用Uri来表示。
int count = 0;
String id = null;
// 获得可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
long noteId = Long.valueOf(id);
if (noteId <= 0) {
break;
}
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);//根据选择条件删除
deleteData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);//对所有修改进行通知
}
return count;
}
@Override
// 更新一个uri
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;
String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();//获取可写的数据库
boolean updateData = false;
switch (mMatcher.match(uri)) {
case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
count = db.update(TABLE.DATA, values, selection, selectionArgs);
updateData = true;
break;
case URI_DATA_ITEM:
id = uri.getPathSegments().get(1);
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
updateData = true;
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
if (count > 0) {
if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
// 将字符串解析成规定格式
private String parseSelection(String selection) {//将字符串解析成规定格式
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
//增加一个noteVersion
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(TABLE.NOTE);
sql.append(" SET ");
sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 ");
if (id > 0 || !TextUtils.isEmpty(selection)) {//selection非空或ID>0添加WHERE
sql.append(" WHERE ");
}
if (id > 0) {//如果id>0添加id
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
if (!TextUtils.isEmpty(selection)) {//输入的文本非空的条件下输入到数据库中
String selectString = id > 0 ? parseSelection(selection) : selection;
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
sql.append(selectString);
}
// execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句
mHelper.getWritableDatabase().execSQL(sql.toString());
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
}

@ -0,0 +1,181 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//这个类定义了一个对象的不同属性
package net.micode.notes.tool;
//引用便签所需要的各个库
import android.content.Context;
import android.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
//ResourceParser类获取程序资源如图片颜色等
public class ResourceParser {//ResourceParser类获取程序资源如图片颜色等
//为颜色静态常量赋值
public static final int YELLOW = 0;
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
public static final int BG_DEFAULT_COLOR = YELLOW;// 默认背景颜色是黄色
public static final int TEXT_SMALL = 0;//对字体大小的静态常量赋值
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;//默认字体大小是中等大小
public static class NoteBgResources {//Note的背景颜色
private final static int [] BG_EDIT_RESOURCES = new int [] {//调用drawable中的五种颜色的背景图片png文件
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
};
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {//背景标题的资源常量数组
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
};
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}//数组调用便签背景图片资源文件
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}//数组调用标题背景图片资源文件
}
public static int getDefaultBgId(Context context) {//直接获取默认的背景颜色
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(//如果颜色设定为随机的颜色,那么就随机返回一个颜色
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
return BG_DEFAULT_COLOR;
}
}
public static class NoteItemBgResources {//便签背景资源类
private final static int [] BG_FIRST_RESOURCES = new int [] {//不同drawable的变量声明
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
};
private final static int [] BG_NORMAL_RESOURCES = new int [] {//定义了背景的默认资源
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
};
private final static int [] BG_LAST_RESOURCES = new int [] {//定义背景的下方资源
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
};
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
};
// 根据id返回四种类型便签项目背景资源的方法
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}//通过ID寻找first的颜色值
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}//通过ID寻找last的颜色值
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}//通过ID获取单个便签背景颜色资源
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}//通过ID寻找normal的颜色值
public static int getFolderBgRes() {
return R.drawable.list_folder;
}//对widget的内置颜色变量等的声明
}
public static class WidgetBgResources {//小窗口情况下的背景资源类
private final static int [] BG_2X_RESOURCES = new int [] {//两倍大小的窗口的颜色子类的值
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}//根据ID加载BG_2X_RESOURCES数组里的颜色资源序号
private final static int [] BG_4X_RESOURCES = new int [] {//4x小窗口资源初始化
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}//根据ID加载BG_4X_RESOURCES数组里的颜色资源序号
}
public static class TextAppearanceResources {//文本外观资源,包括默认字体,以及获取资源大小
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {//文本字体的四种大小
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
public static int getTexAppearanceResource(int id) {//检测ID是否大于字体大小资源总量如果是返回默认的结果如果不是则返回大小的ID号
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {//若输入id大于字体编号最大值则返回默认值
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
}
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}//返回字体大小资源的长度
}
}

@ -0,0 +1,41 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.exception;
public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L;
/*
* serialVersionUIDjava,JavaserialVersionUID
* serialVersionUID
*/
public ActionFailureException() {
super();
}
/*
* JAVA使superthis.
* new
* 使super
* super()super (paramString)Exception ()Exception (paramString)
*/
public ActionFailureException(String paramString) {
super(paramString);
}
public ActionFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}

@ -0,0 +1,133 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
/*GTask
*
* private void showNotification(int tickerId, String content)
* protected Integer doInBackground(Void... unused) 线
* protected void onProgressUpdate(String... progress) 使 线
* protected void onPostExecute(Integer result) Handler UI使doInBackground UI
*/
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
public interface OnCompleteListener {
void onComplete();
}
private Context mContext;
private NotificationManager mNotifiManager;
private GTaskManager mTaskManager;
private OnCompleteListener mOnCompleteListener;
public GTaskASyncTask(Context context, OnCompleteListener listener) {
mContext = context;
mOnCompleteListener = listener;
mNotifiManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
mTaskManager = GTaskManager.getInstance();
}
public void cancelSync() {
mTaskManager.cancelSync();
}
public void publishProgess(String message) {//发布进度单位系统将会调用onProgressUpdate()方法更新这些值。
publishProgress(new String[] {
message
});
}
private void showNotification(int tickerId, String content) {
PendingIntent pendingIntent;//一个描述了想要启动一个Activity、Broadcast或是Service的意图。
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);//如果同步不成功那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象。
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);//如果同步成功那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象。
}
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(content)
.setContentIntent(pendingIntent)
.setWhen(System.currentTimeMillis())
.setOngoing(true);
Notification notification=builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify方法来执行一个notification的消息。
}
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));//利用getString,将把 NotesPreferenceActivity.getSyncAccountName(mContext))的字符串内容传进sync_progress_login中。
return mTaskManager.sync(mContext, this);//进行后台同步。
}
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}//instanceof 判断mContext是否是GTaskSyncService的实例
}
@Override
protected void onPostExecute(Integer result) {//在执行完后台任务后更新UI,显示结果。
if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());//设置最新的同步时间。
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
}//不同情况的结果如上。
if (mOnCompleteListener != null) {
new Thread(new Runnable() {
public void run() {
mOnCompleteListener.onComplete();
}//完成一次操作后使用onComplete()将所有值都重新初始化。
}).start();
}
}
}

@ -0,0 +1,669 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
/*GTask 客户端,提供登录 Google 账户,创建任务和任务列表,添加和删除结点,提交、重置更新,获取任务列表等功能*/
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.GTaskStringUtils;
import net.micode.notes.ui.NotesPreferenceActivity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
private static final String GTASK_URL = "https://mail.google.com/tasks/"; //这个是指定的URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
private static GTaskClient mInstance = null;
private DefaultHttpClient mHttpClient;
private String mGetUrl;
private String mPostUrl;
private long mClientVersion;
private boolean mLoggedin;
private long mLastLoginTime;
private int mActionId;
private Account mAccount;
private JSONArray mUpdateArray;
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
mClientVersion = -1;
mLoggedin = false;
mLastLoginTime = 0;
mActionId = 1;
mAccount = null;
mUpdateArray = null;
}
/*
* 使 getInstance()
* mInstance
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
}
return mInstance;
}
/*Activity
*
* 使URL使URL
* truefalse
*/
public boolean login(Activity activity) {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
//判断距离最后一次登录操作是否超过5分钟
final long interval = 1000 * 60 * 5;
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch 重新登录操作
if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
mLoggedin = false;
}
//如果没超过时间,则不需要重新登录
if (mLoggedin) {
Log.d(TAG, "already logged in");
return true;
}
mLastLoginTime = System.currentTimeMillis();//更新最后登录时间,改为系统当前的时间
String authToken = loginGoogleAccount(activity, false);//判断是否登录到谷歌账户
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
// login with custom domain if necessary
//尝试使用用户自己的域名登录
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() //将用户账号名改为统一格式(小写)后判断是否为一个谷歌账号地址
.endsWith("googlemail.com"))) {
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index);
url.append(suffix + "/");
mGetUrl = url.toString() + "ig"; //设置用户对应的getUrl
mPostUrl = url.toString() + "r/ig"; //设置用户对应的postUrl
if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true;
}
}
// try to login with google official url
//如果用户账户无法登录则使用谷歌官方的URI进行登录
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
if (!tryToLoginGtask(activity, authToken)) {
return false;
}
}
mLoggedin = true;
return true;
}
/*
* 使
* 使AccountManager
*
*/
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken; //令牌,是登录操作保证安全性的一个方法
AccountManager accountManager = AccountManager.get(activity);//AccountManager这个类给用户提供了集中注册账号的接口
Account[] accounts = accountManager.getAccountsByType("com.google");//获取全部以com.google结尾的account
if (accounts.length == 0) {
Log.e(TAG, "there is no available google account");
return null;
}
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null;
//遍历获得的accounts信息寻找已经记录过的账户信息
for (Account a : accounts) {
if (a.name.equals(accountName)) {
account = a;
break;
}
}
if (account != null) {
mAccount = account;
} else {
Log.e(TAG, "unable to get an account with the same name in the settings");
return null;
}
// get the token now
//获取选中账号的令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
Bundle authTokenBundle = accountManagerFuture.getResult();
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
//如果是invalidateToken那么需要调用invalidateAuthToken(String, String)方法废除这个无效token
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false);
}
} catch (Exception e) {
Log.e(TAG, "get auth token failed");
authToken = null;
}
return authToken;
}
//尝试登陆Gtask这只是一个预先判断令牌是否是有效以及是否能登上GTask的方法,而不是具体实现登陆的方法
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// maybe the auth token is out of authTokedate, now let's invalidate the
// token and try again
//删除过一个无效的authToken申请一个新的后再次尝试登陆
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "login google account failed");
return false;
}
if (!loginGtask(authToken)) {
Log.e(TAG, "login gtask failed");
return false;
}
}
return true;
}
//实现登录GTask的具体操作
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000;
int timeoutSocket = 15000; //socket是一种通信连接实现数据的交换的端口
HttpParams httpParameters = new BasicHttpParams(); //实例化一个新的HTTP参数类
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//设置连接超时时间
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);//设置设置端口超时时间
mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); //设置本地cookie
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
try {
String loginUrl = mGetUrl + "?auth=" + authToken; //设置登录的url
HttpGet httpGet = new HttpGet(loginUrl); //通过登录的uri实例化网页上资源的查找
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the cookie now
//获取CookieStore里存放的cookie,看如果存有“GTL(不知道什么意思)”则说明有验证成功的有效的cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
if (cookie.getName().contains("GTL")) {
hasAuthCookie = true;
}
}
if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie");
}
// get the client version
//获取client的内容具体操作是在返回的Content中截取从_setup(开始到)}</script>中间的字符串内容也就是gtask_url的内容
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
}
JSONObject js = new JSONObject(jsString);
mClientVersion = js.getLong("v");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return false;
} catch (Exception e) {
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
return true;
}
private int getActionId() {
return mActionId++;
}
/*
* 使HttpPost
* httpPost
*/
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("AT", "1");
return httpPost;
}
/*URL
* 使getContentEncoding()
*
*/
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {//通过URL得到HttpEntity对象如果不为空则使用getContent方法创建一个流将数据从网络都过来
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "encoding: " + contentEncoding);
}
InputStream input = entity.getContent();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {//GZIP是使用DEFLATE进行压缩数据的另一个压缩库
input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {//DEFLATE是一个无专利的压缩算法它可以实现无损数据压缩
Inflater inflater = new Inflater(true);
input = new InflaterInputStream(entity.getContent(), inflater);
}
try {
InputStreamReader isr = new InputStreamReader(input);
BufferedReader br = new BufferedReader(isr);//是一个包装类,它可以包装字符流,将字符流放入缓存里,先把字符读到缓存里,到缓存满了时候,再读入内存,是为了提供读的效率而设计的
StringBuilder sb = new StringBuilder();
while (true) {
String buff = br.readLine();
if (buff == null) {
return sb.toString();
}
sb = sb.append(buff);
}
} finally {
input.close();
}
}
/*JSON
* jsonjs
* UrlEncodedFormEntity entityhttpPost.setEntity(entity)jshttpPost
* 使getResponseContent
* json
*/
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {//未登录
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
//实例化一个httpPost的对象用来向服务器传输数据在这里就是发送请求而请求的内容在js里
HttpPost httpPost = createHttpPost();
try {
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
list.add(new BasicNameValuePair("r", js.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); //UrlEncodedFormEntity()的形式比较单一,是普通的键值对
httpPost.setEntity(entity);
// execute the post
//执行这个请求
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("error occurs when posting request");
}
}
/*
* .gtask.data.TaskTask
* jsonTask,jsPost
* postRequest
* 使task.setGidtasknew_ID
*/
public void createTask(Task task) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
actionList.put(task.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create task: handing jsonobject failed");
}
}
/*
* createTasktasklistgid
*/
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
actionList.put(tasklist.getCreateAction(getActionId()));
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost);
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("create tasklist: handing jsonobject failed");
}
}
/*
*
* 使JSONObject使jsPost.putPutUpdateArrayClientVersion
* 使postRequestjspost,
*/
public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) {
try {
JSONObject jsPost = new JSONObject();
// action_list
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("commit update: handing jsonobject failed");
}
}
}
/*
*
* commitUpdate()
*/
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// too many update items may result in an error
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
if (mUpdateArray == null)
mUpdateArray = new JSONArray();
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
/*
* task,tasktask
* getGidtaskgid
* JSONObject.put(String name, Object value)task
* postRequest
*/
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
if (preParent == curParent && task.getPriorSibling() != null) {
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
//设置优先级ID只有当移动是发生在文件中
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid()); //设置移动前所属列表
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid()); //设置当前所属列表
if (preParent != curParent) {
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
//最后将ACTION_LIST加入到jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("move task: handing jsonobject failed");
}
}
/*
*
* JSON
* 使postRequest
*/
public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
// action_list
node.setDeleted(true);
actionList.put(node.getUpdateAction(getActionId())); //这里会获取到删除操作的ID加入到actionLiast中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
postRequest(jsPost);
mUpdateArray = null;
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("delete node: handing jsonobject failed");
}
}
/*
*
* GetURI使getResponseContent
* "_setup(")}</script>GTASK_JSON_LISTS
*/
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
try {
HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the task list
//筛选工作把筛选出的字符串放入jsString
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
int begin = resString.indexOf(jsBegin);
int end = resString.lastIndexOf(jsEnd);
String jsString = null;
if (begin != -1 && end != -1 && begin < end) {
jsString = resString.substring(begin + jsBegin.length(), end);
}
JSONObject js = new JSONObject(jsString);
//获取GTASK_JSON_LISTS
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task lists: handing jasonobject failed");
}
}
/*
* TASKListgid,
*/
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
JSONObject jsPost = new JSONObject();
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// action_list
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid); //这里设置为传入的listGid
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
actionList.put(action);
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
JSONObject jsResponse = postRequest(jsPost);
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("get task list: handing jsonobject failed");
}
}
public Account getSyncAccount() {
return mAccount;
}
//重置更新的内容
public void resetUpdateArray() {
mUpdateArray = null;
}
}

@ -0,0 +1,887 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.data.MetaData;
import net.micode.notes.gtask.data.Node;
import net.micode.notes.gtask.data.SqlNote;
import net.micode.notes.gtask.data.Task;
import net.micode.notes.gtask.data.TaskList;
import net.micode.notes.gtask.exception.ActionFailureException;
import net.micode.notes.gtask.exception.NetworkFailureException;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.GTaskStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
public class GTaskManager {
private static final String TAG = GTaskManager.class.getSimpleName();
public static final int STATE_SUCCESS = 0;
public static final int STATE_NETWORK_ERROR = 1;
public static final int STATE_INTERNAL_ERROR = 2;
public static final int STATE_SYNC_IN_PROGRESS = 3;
public static final int STATE_SYNC_CANCELLED = 4;
private static GTaskManager mInstance = null;
private Activity mActivity;
private Context mContext;
private ContentResolver mContentResolver;
private boolean mSyncing;
private boolean mCancelled;
private HashMap<String, TaskList> mGTaskListHashMap;
private HashMap<String, Node> mGTaskHashMap;
private HashMap<String, MetaData> mMetaHashMap;
private TaskList mMetaList;
private HashSet<Long> mLocalDeleteIdMap;
private HashMap<String, Long> mGidToNid;
private HashMap<Long, String> mNidToGid;
private GTaskManager() { //对象初始化函数
mSyncing = false; //正在同步,flase代表未执行
mCancelled = false; //全局标识flase代表可以执行
mGTaskListHashMap = new HashMap<String, TaskList>(); //<>代表Java的泛型,就是创建一个用类型作为参数的类。
mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>();
mMetaList = null;
mLocalDeleteIdMap = new HashSet<Long>();
mGidToNid = new HashMap<String, Long>(); //GoogleID to NodeID??
mNidToGid = new HashMap<Long, String>(); //NodeID to GoogleID???通过hashmap散列表建立映射
}
/*
* synchronized线
*
* @author TTS
* @return GtaskManger
*/
public static synchronized GTaskManager getInstance() { //可能运行在多线程环境下,使用语言级同步--synchronized
if (mInstance == null) {
mInstance = new GTaskManager();
}
return mInstance;
}
/*
* synchronized线
* @author TTS
* @param activity
*/
public synchronized void setActivityContext(Activity activity) {
// used for getting auth token
mActivity = activity;
}
/*
*
*
* @author TTS
* @param context-----
* @param asyncTask-------
* @return int
*/
public int sync(Context context, GTaskASyncTask asyncTask) { //核心函数
if (mSyncing) {
Log.d(TAG, "Sync is in progress"); //创建日志文件调试信息debug
return STATE_SYNC_IN_PROGRESS;
}
mContext = context;
mContentResolver = mContext.getContentResolver();
mSyncing = true;
mCancelled = false;
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
try {
GTaskClient client = GTaskClient.getInstance(); //getInstance即为创建一个实例,client--客户机
client.resetUpdateArray(); //JSONArray类型reset即置为NULL
// login google task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("login google task failed");
}
}
// get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); //获取Google上的JSONtasklist转为本地TaskList
// do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) { //分为两种异常,此类异常为网络异常
Log.e(TAG, e.toString()); //创建日志文件调试信息error
return STATE_NETWORK_ERROR;
} catch (ActionFailureException e) { //此类异常为操作异常
Log.e(TAG, e.toString());
return STATE_INTERNAL_ERROR;
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
return STATE_INTERNAL_ERROR;
} finally {
mGTaskListHashMap.clear();
mGTaskHashMap.clear();
mMetaHashMap.clear();
mLocalDeleteIdMap.clear();
mGidToNid.clear();
mNidToGid.clear();
mSyncing = false;
}
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/*
*GtaskListGoogleJSONtasklistTaskList
*mMetaListmGTaskListHashMapmGTaskHashMap
*@author TTS
*@exception NetworkFailureException
*@return void
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
GTaskClient client = GTaskClient.getInstance(); //getInstance即为创建一个实例client应指远端客户机
try {
//Json对象是Name Value对(即子元素)的无序集合相当于一个Map对象。JsonObject类是bantouyan-json库对Json对象的抽象提供操纵Json对象的各种方法。
//其格式为{"key1":value1,"key2",value2....};key 必须是字符串。
//因为ajax请求不刷新页面但配合js可以实现局部刷新因此json常常被用来作为异步请求的返回对象使用。
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
mMetaList = null; //TaskList类型
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i); //JSONObject与JSONArray一个为对象一个为数组。此处取出单个JASONObject
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList(); //MetaList意为元表,Tasklist类型此处为初始化
mMetaList.setContentByRemoteJSON(object); //将JSON中部分数据复制到自己定义的对象中相对应的数据name->mname...
// load meta data
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = (JSONObject) jsMetas.getJSONObject(j);
MetaData metaData = new MetaData(); //继承自Node
metaData.setContentByRemoteJSON(object);
if (metaData.isWorthSaving()) { //if not worth to savemetadata将不加入mMetaList
mMetaList.addChildTask(metaData);
if (metaData.getGid() != null) {
mMetaHashMap.put(metaData.getRelatedGid(), metaData);
}
}
}
}
}
// create meta list if not existed
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META);
GTaskClient.getInstance().createTaskList(mMetaList);
}
// init task list
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID); //通过getString函数传入本地某个标志数据的名称获取其在远端的名称。
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX)
&& !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_META)) {
TaskList tasklist = new TaskList(); //继承自Node
tasklist.setContentByRemoteJSON(object);
mGTaskListHashMap.put(gid, tasklist);
mGTaskHashMap.put(gid, tasklist); //为什么加两遍???
// load tasks
JSONArray jsTasks = client.getTaskList(gid);
for (int j = 0; j < jsTasks.length(); j++) {
object = (JSONObject) jsTasks.getJSONObject(j);
gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
Task task = new Task();
task.setContentByRemoteJSON(object);
if (task.isWorthSaving()) {
task.setMetaInfo(mMetaHashMap.get(gid));
tasklist.addChildTask(task);
mGTaskHashMap.put(gid, task);
}
}
}
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("initGTaskList: handing JSONObject failed");
}
}
/*
*
* @throws NetworkFailureException
* @return
*/
private void syncContent() throws NetworkFailureException { //本地内容同步操作
int syncType;
Cursor c = null; //数据库指针
String gid; //GoogleID??
Node node; //Node包含Sync_Action的不同类型
mLocalDeleteIdMap.clear(); //HashSet<Long>类型
if (mCancelled) {
return;
}
// for local deleted note
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, null);
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);
}
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
}
} else {
Log.w(TAG, "failed to query trash folder");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// sync folder first
syncFolder();
// for note existing in database
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN)); //通过hashmap建立联系
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid); //通过hashmap建立联系
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
doContentSync(syncType, node, c);
}
} else {
Log.w(TAG, "failed to query existing note in database");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// go through remaining items
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator(); //Iterator迭代器
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
node = entry.getValue();
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled can be set by another thread, so we neet to check one by //thread----线程
// one
// clear local delete table
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// refresh local sync id
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
}
}
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
Node node;
int syncType;
if (mCancelled) {
return;
}
// for root folder
try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
if (c != null) {
c.moveToNext();
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);
mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid);
// for system folder, only update remote name if necessary
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
} else {
Log.w(TAG, "failed to query root folder");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// for call-note folder
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",
new String[] {
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
if (c != null) {
if (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);
mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid);
// for system folder, only update remote name if
// necessary
if (!node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX
+ GTaskStringUtils.FOLDER_CALL_NOTE))
doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c);
} else {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
}
} else {
Log.w(TAG, "failed to query call note folder");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// for local existing folders
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC");
if (c != null) {
while (c.moveToNext()) {
gid = c.getString(SqlNote.GTASK_ID_COLUMN);
node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));
mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);
syncType = node.getSyncAction(c);
} else {
if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {
// local add
syncType = Node.SYNC_ACTION_ADD_REMOTE;
} else {
// remote delete
syncType = Node.SYNC_ACTION_DEL_LOCAL;
}
}
doContentSync(syncType, node, c);
}
} else {
Log.w(TAG, "failed to query existing folder");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
// for remote add folders
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
gid = entry.getKey();
node = entry.getValue();
if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid);
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
}
if (!mCancelled)
GTaskClient.getInstance().commitUpdate();
}
/*
* syncTypeaddLocalNodeaddRemoteNodedeleteNodeupdateLocalNodeupdateRemoteNode
* @author TTS
* @param syncType
* @param node
* @param c
* @throws NetworkFailureException
*/
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
MetaData meta;
switch (syncType) {
case Node.SYNC_ACTION_ADD_LOCAL:
addLocalNode(node);
break;
case Node.SYNC_ACTION_ADD_REMOTE:
addRemoteNode(node, c);
break;
case Node.SYNC_ACTION_DEL_LOCAL:
meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN));
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
}
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
break;
case Node.SYNC_ACTION_DEL_REMOTE:
meta = mMetaHashMap.get(node.getGid());
if (meta != null) {
GTaskClient.getInstance().deleteNode(meta);
}
GTaskClient.getInstance().deleteNode(node);
break;
case Node.SYNC_ACTION_UPDATE_LOCAL:
updateLocalNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_REMOTE:
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_UPDATE_CONFLICT:
// merging both modifications maybe a good idea
// right now just use local update simply
updateRemoteNode(node, c);
break;
case Node.SYNC_ACTION_NONE:
break;
case Node.SYNC_ACTION_ERROR:
default:
throw new ActionFailureException("unkown sync action type");
}
}
/*
* Node
* @author TTS
* @param node
* @throws NetworkFailureException
*/
private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
if (node instanceof TaskList) {
if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) {
sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER);
} else if (node.getName().equals(
GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) {
sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER);
} else {
sqlNote = new SqlNote(mContext);
sqlNote.setContent(node.getLocalJSONFromContent());
sqlNote.setParentId(Notes.ID_ROOT_FOLDER);
}
} else {
sqlNote = new SqlNote(mContext);
JSONObject js = node.getLocalJSONFromContent();
try {
if (js.has(GTaskStringUtils.META_HEAD_NOTE)) {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// the id is not available, have to create a new one
note.remove(NoteColumns.ID);
}
}
}
if (js.has(GTaskStringUtils.META_HEAD_DATA)) {
JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
for (int i = 0; i < dataArray.length(); i++) {
JSONObject data = dataArray.getJSONObject(i);
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// the data id is not available, have to create
// a new one
data.remove(DataColumns.ID);
}
}
}
}
} catch (JSONException e) {
Log.w(TAG, e.toString());
e.printStackTrace();
}
sqlNote.setContent(js);
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot add local node");
}
sqlNote.setParentId(parentId.longValue());
}
// create the local node
sqlNote.setGtaskId(node.getGid());
sqlNote.commit(false);
// update gid-nid mapping
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
}
/*
* updatenode
* @author TTS
* @param node
* ----
* @param c
* ----Cursor
* @throws NetworkFailureException
*/
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote;
// update the note locally
sqlNote = new SqlNote(mContext, c);
sqlNote.setContent(node.getLocalJSONFromContent());
Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())
: new Long(Notes.ID_ROOT_FOLDER);
if (parentId == null) {
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// update meta info
updateRemoteMeta(node.getGid(), sqlNote);
}
/*
* Node
* updateRemoteMeta
* @author TTS
* @param node
* ----
* @param c
* --Cursor
* @throws NetworkFailureException
*/
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c); //从本地mContext中获取内容
Node n;
// update remotely
if (sqlNote.isNoteType()) {
Task task = new Task();
task.setContentByLocalJSON(sqlNote.getContent());
String parentGid = mNidToGid.get(sqlNote.getParentId());
if (parentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist"); //调试信息
throw new ActionFailureException("cannot add remote task");
}
mGTaskListHashMap.get(parentGid).addChildTask(task); //在本地生成的GTaskList中增加子结点
//登录远程服务器创建Task
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// add meta
updateRemoteMeta(task.getGid(), sqlNote);
} else {
TaskList tasklist = null;
// we need to skip folder if it has already existed
String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;
if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)
folderName += GTaskStringUtils.FOLDER_DEFAULT;
else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER)
folderName += GTaskStringUtils.FOLDER_CALL_NOTE;
else
folderName += sqlNote.getSnippet();
//iterator迭代器通过统一的接口迭代所有的map元素
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
String gid = entry.getKey();
TaskList list = entry.getValue();
if (list.getName().equals(folderName)) {
tasklist = list;
if (mGTaskHashMap.containsKey(gid)) {
mGTaskHashMap.remove(gid);
}
break;
}
}
// no match we can add now
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().createTaskList(tasklist);
mGTaskListHashMap.put(tasklist.getGid(), tasklist);
}
n = (Node) tasklist;
}
// update local note
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// gid-id mapping 创建id间的映射
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
/*
* Nodemeta(updateRemoteMeta)
* @author TTS
* @param node
* ----
* @param c
* --Cursor
* @throws NetworkFailureException
*/
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
}
SqlNote sqlNote = new SqlNote(mContext, c);
// update remotely
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node); //GTaskClient用途为从本地登陆远端服务器
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
// move task if necessary
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
//preParentList为通过node获取的父节点列表
String curParentGid = mNidToGid.get(sqlNote.getParentId());
//curParentGid为通过光标在数据库中找到sqlNote的mParentId再通过mNidToGid由long类型转为String类型的Gid
if (curParentGid == null) {
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot update remote task");
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
//通过HashMap找到对应Gid的TaskList
if (preParentList != curParentList) {
preParentList.removeChildTask(task);
curParentList.addChildTask(task);
GTaskClient.getInstance().moveTask(task, preParentList, curParentList);
}
}
// clear local modified flag
sqlNote.resetLocalModified();
//commit到本地数据库
sqlNote.commit(true);
}
/*
* meta meta----------
* @author TTS
* @param gid
* ---GoogleIDString
* @param sqlNote
* ---使SqlNote
* @throws NetworkFailureException
*/
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid);
if (metaData != null) {
metaData.setMeta(gid, sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(metaData);
} else {
metaData = new MetaData();
metaData.setMeta(gid, sqlNote.getContent());
mMetaList.addChildTask(metaData);
mMetaHashMap.put(gid, metaData);
GTaskClient.getInstance().createTask(metaData);
}
}
}
/*
* syncID
* @author TTS
* @return void
* @throws NetworkFailureException
*/
private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) {
return;
}
// get the latest gtask list //获取最近的最晚的gtask list
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
initGTaskList();
Cursor c = null;
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id<>?)", new String[] {
String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)
}, NoteColumns.TYPE + " DESC"); //query语句五个参数NoteColumns.TYPE + " DESC"-----为按类型递减顺序返回查询结果。new String[] {String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER)}------为选择参数。"(type<>? AND parent_id<>?)"-------指明返回行过滤器。SqlNote.PROJECTION_NOTE--------应返回的数据列的名字。Notes.CONTENT_NOTE_URI--------contentProvider包含所有数据集所对应的uri
if (c != null) {
while (c.moveToNext()) {
String gid = c.getString(SqlNote.GTASK_ID_COLUMN);
Node node = mGTaskHashMap.get(gid);
if (node != null) {
mGTaskHashMap.remove(gid);
ContentValues values = new ContentValues(); //在ContentValues中创建键值对。准备通过contentResolver写入数据
values.put(NoteColumns.SYNC_ID, node.getLastModified());
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, //进行批量更改选择参数为NULL应该可以用insert替换参数分别为表名和需要更新的value对象。
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
Log.e(TAG, "something is missed");
throw new ActionFailureException(
"some local items don't have gid after sync");
}
}
} else {
Log.w(TAG, "failed to query local note to refresh sync id");
}
} finally {
if (c != null) {
c.close();
c = null;
}
}
}
/*
* ,mAccount.name
* @author TTS
* @return String
*/
public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name;
}
/*
* mCancelledtrue
* @author TTS
*/
public void cancelSync() {
mCancelled = true;
}
}

@ -0,0 +1,143 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
/*
* GTask 广
*
* private void startSync()
* private void cancelSync()
* public void onCreate()
* public int onStartCommand(Intent intent, int flags, int startId) serviceserviceservice
* public void onLowMemory() serviceservice
* public IBinder onBind()
* public void sendBroadcast(String msg)
* public static void startSync(Activity activity)
* public static void cancelSync(Context context)
* public static boolean isSyncing()
* public static String getProgressString()
*/
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type";
public final static int ACTION_START_SYNC = 0;
public final static int ACTION_CANCEL_SYNC = 1;
public final static int ACTION_INVALID = 2;
public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";
public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";
public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";
private static GTaskASyncTask mSyncTask = null;
private static String mSyncProgress = "";
//开始同步
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
public void onComplete() {
mSyncTask = null;
sendBroadcast("");
stopSelf();
}
});
sendBroadcast("");
mSyncTask.execute();//这个函数让任务是以单线程队列方式或线程池队列方式运行
}
}
private void cancelSync() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
@Override
public void onCreate() {
mSyncTask = null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras();
if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {//开始同步和取消同步的不同情况
switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
case ACTION_START_SYNC:
startSync();
break;
case ACTION_CANCEL_SYNC:
cancelSync();
break;
default:
break;
}
return START_STICKY;//等待新的intent到这个service继续运行
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onLowMemory() {
if (mSyncTask != null) {
mSyncTask.cancelSync();
}
}
public IBinder onBind(Intent intent) {
return null;
}
public void sendBroadcast(String msg) {
mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);//创建一个新的Intent
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);//添加Intent中相应参数的值
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
sendBroadcast(intent); //开始发送通知
}
public static void startSync(Activity activity) {//执行一个service即开始同步
GTaskManager.getInstance().setActivityContext(activity);
Intent intent = new Intent(activity, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
activity.startService(intent);
}
public static void cancelSync(Context context) {//执行一个service即取消同步
Intent intent = new Intent(context, GTaskSyncService.class);
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent);
}
public static boolean isSyncing() {
return mSyncTask != null;
}
public static String getProgressString() {
return mSyncProgress;
}
}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.exception;
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
/*
* serialVersionUIDjava,JavaserialVersionUID
* serialVersionUID
*/
public NetworkFailureException() {
super();
}
/*
* JAVA使superthis.
* new
* 使super
* super()super (paramString)Exception ()Exception (paramString)
*/
public NetworkFailureException(String paramString) {
super(paramString);
}
public NetworkFailureException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}

@ -0,0 +1,132 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;//导入widget
import android.app.PendingIntent;//引入各种类
import android.appwidget.AppWidgetManager;//导入AppWidget
import android.appwidget.AppWidgetProvider;//提供widget的基本操作和属性
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;//数据库的光标
import android.util.Log;
import android.widget.RemoteViews;//远程访问
import net.micode.notes.R;//引入android自动生成的R类资源
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;//便签栏
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;
public abstract class NoteWidgetProvider extends AppWidgetProvider {//构造了一个类继承Android原有的AppWidgetProvider类
public static final String [] PROJECTION = new String [] {//定义了一个字符数组类型的静态变量
NoteColumns.ID,
NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET
};
public static final int COLUMN_ID = 0;//便签栏编号
public static final int COLUMN_BG_COLOR_ID = 1;//背景颜色编号
public static final int COLUMN_SNIPPET = 2;//便签片段
private static final String TAG = "NoteWidgetProvider";//定义NoteWidgetProvider为标签TAG
@Override
public void onDeleted(Context context, int[] appWidgetIds) {//重载删除方法把WIDGET_ID置为INVALID_APPPWIDGET_ID,把当前窗口ID置为无效
ContentValues values = new ContentValues();//定义了一个新values变量
values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);//存储便签信息
for (int i = 0; i < appWidgetIds.length; i++) {//遍历修改所有的URI值
context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
values,
NoteColumns.WIDGET_ID + "=?",
new String[] { String.valueOf(appWidgetIds[i])});// valueOf() 方法用于返回给定参数的原生 Number 对象值
}
}
private Cursor getNoteWidgetInfo(Context context, int widgetId) {//获取窗口宽度信息
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,//返回信息值
PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",//用ID来筛选同时要是存在于未被删除的文件夹中
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null);
}
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {//上传widget的信息
update(context, appWidgetManager, appWidgetIds, false);//更新窗口部件
}
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,//把更新的窗口ID保存到窗口管理器中
boolean privacyMode) {
for (int i = 0; i < appWidgetIds.length; i++) {//每添加一个widget就会进行一次循环更新操作
if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {//需要跳过那些已经关闭的窗口的ID
int bgId = ResourceParser.getDefaultBgId(context);
String snippet = "";
Intent intent = new Intent(context, NoteEditActivity.class);//创建intent对象
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);//目标activity在栈顶跳转不在则新建一个
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);//将要传递的值附加键对象
intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());//附加组件类型
Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);//获取特定的对应对象
if (c != null && c.moveToFirst()) {//处理多窗口同位置的情况
if (c.getCount() > 1) {//cursor.getCount()返回cursor中的行数。
Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
c.close();
return;
}
snippet = c.getString(COLUMN_SNIPPET);//一条字符串
bgId = c.getInt(COLUMN_BG_COLOR_ID);//获取ID值
intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));//目的
intent.setAction(Intent.ACTION_VIEW);//为Intent设置一个动作Action
} else {//在Intent内设置一个Action
snippet = context.getResources().getString(R.string.widget_havenot_content);//没有关联内容,点击新建便签
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
}
if (c != null) {
c.close();
}
RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());//获取AppWidget对应的视图
rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));//根据当前的属性,设置背景图片
intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
/**
* Generate the pending intent to start host for the widget//为小部件生成启动主机的挂起意图
*/
PendingIntent pendingIntent = null;//为小部件生成启动主机的挂起的目标选项
if (privacyMode) {//判定是否是私密模式
rv.setTextViewText(R.id.widget_text,//访客模式下,便签内容不可见
context.getString(R.string.widget_under_visit_mode));
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);//获得一个PendingIntent如果该意图要发生就相当于Context.startActivity(Intent)。
} else {
rv.setTextViewText(R.id.widget_text, snippet);//设置 点击“按钮(widget_text)”时会触发的Intent从而对按钮点击事件进行处理
pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);//窗口服务部件
appWidgetManager.updateAppWidget(appWidgetIds[i], rv);//调用集合管理器对集合进行更新
}
}
}
protected abstract int getBgResourceId(int bgId);//从背景资源中获取当前应用ID
protected abstract int getLayoutId();//获取部局ID
protected abstract int getWidgetType();//可以调用2*2或者4*4的函数
}

@ -0,0 +1,47 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;//声明小米便签窗口部件这个包
import android.appwidget.AppWidgetManager;//使用AppWidgetManager这个类
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;//便签数据
import net.micode.notes.tool.ResourceParser;//资源解析器
public class NoteWidgetProvider_2x extends NoteWidgetProvider {//继承NoteWidgetProvider这个类
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {//更新窗口
super.update(context, appWidgetManager, appWidgetIds);
}
@Override
protected int getLayoutId() {
return R.layout.widget_2x;
}//获取窗口布局
@Override
protected int getBgResourceId(int bgId) {//获取背景颜色id
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X;
}//确定窗口大小
}

@ -0,0 +1,46 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.widget;//声明包名
import android.appwidget.AppWidgetManager;//导入一些类
import android.content.Context;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_4x extends NoteWidgetProvider {//定义4*4的widget
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {//对窗口更新进行重载
super.update(context, appWidgetManager, appWidgetIds);
}
protected int getLayoutId() {
return R.layout.widget_4x;
}//返回窗口位置信息返回了小米便签挂件是2x2型
@Override
protected int getBgResourceId(int bgId) {// 获取背景颜色ID
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);//返回了小米便签2x2型挂件的背景类型ID即确定了2x2型的背景。
}
@Override
protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X;
}//返回窗口类型
}

Binary file not shown.

Binary file not shown.

Binary file not shown.
Loading…
Cancel
Save