Compare commits

..

4 Commits

Author SHA1 Message Date
Ryuki cab648c447 .
2 years ago
Ryuki 8e41221ba1 .
2 years ago
Ryuki 7d4cf94218 all
2 years ago
Ryuki 36148b43e1 注释
2 years ago

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -26,54 +26,29 @@ import org.json.JSONObject;
public class MetaData extends Task {
/* TAG
* getSimpleName ()
*/
private final static String TAG = MetaData.class.getSimpleName();
private String mRelatedGid = null;
/*
*
* JSONObjectput ()TasksetNotes ()setName ()
*/
public void setMeta(String gid, JSONObject metaInfo) {
try {
//对函数块进行注释
metaInfo.put(GTaskStringUtils.META_HEAD_GTASK_ID, gid);
/*
* metaInfojsonobject
*/
} catch (JSONException e) {
Log.e(TAG, "failed to put related gid");
/*
*
*/
}
setNotes(metaInfo.toString());
setName(GTaskStringUtils.META_NOTE_NAME);
}
/*
* Gid
*/
public String getRelatedGid() {
return mRelatedGid;
}
/*
*
*/
@Override
public boolean isWorthSaving() {
return getNotes() != null;
}
/*
* 使json
* TasksetContentByRemoteJSON ()
*
*/
@Override
public void setContentByRemoteJSON(JSONObject js) {
super.setContentByRemoteJSON(js);
@ -83,9 +58,6 @@ public class MetaData extends Task {
mRelatedGid = metaInfo.getString(GTaskStringUtils.META_HEAD_GTASK_ID);
} catch (JSONException e) {
Log.w(TAG, "failed to get related gid");
/*
*
*/
mRelatedGid = null;
}
}
@ -97,33 +69,14 @@ public class MetaData extends Task {
throw new IllegalAccessError("MetaData:setContentByLocalJSON should not be called");
}
/*
* json
*/
@Override
public JSONObject getLocalJSONFromContent() {
throw new IllegalAccessError("MetaData:getLocalJSONFromContent should not be called");
}
/*
*
*/
}
/*
*
*/
@Override
public int getSyncAction(Cursor c) {
throw new IllegalAccessError("MetaData:getSyncAction should not be called");
}
/*
*
*/
}

@ -20,38 +20,32 @@ import android.database.Cursor;
import org.json.JSONObject;
/*
*
* abstract
*/
public abstract class Node {
//定义了各种用于表征同步状态的常量
public static final int SYNC_ACTION_NONE = 0;// 本地和云端都无可更新内容(即本地和云端内容一致)
public static final int SYNC_ACTION_NONE = 0;
public static final int SYNC_ACTION_ADD_REMOTE = 1;// 需要在远程云端增加内容
public static final int SYNC_ACTION_ADD_REMOTE = 1;
public static final int SYNC_ACTION_ADD_LOCAL = 2;// 需要在本地增加内容
public static final int SYNC_ACTION_ADD_LOCAL = 2;
public static final int SYNC_ACTION_DEL_REMOTE = 3;// 需要在远程云端删除内容
public static final int SYNC_ACTION_DEL_REMOTE = 3;
public static final int SYNC_ACTION_DEL_LOCAL = 4;// 需要在本地删除内容
public static final int SYNC_ACTION_DEL_LOCAL = 4;
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;// 需要将本地内容更新到远程云端
public static final int SYNC_ACTION_UPDATE_REMOTE = 5;
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;// 需要将远程云端内容更新到本地
public static final int SYNC_ACTION_UPDATE_LOCAL = 6;
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;// 同步出现冲突
public static final int SYNC_ACTION_UPDATE_CONFLICT = 7;
public static final int SYNC_ACTION_ERROR = 8;// 同步出现错误
public static final int SYNC_ACTION_ERROR = 8;
private String mGid;
private String mName;
private long mLastModified;//记录最后一次修改时间
private long mLastModified;
private boolean mDeleted;//表征是否被删除
private boolean mDeleted;
public Node() {
mGid = null;

@ -14,21 +14,8 @@
* limitations under the License.
*/
/*
* Description便sqlnotedatanote
* SqlData
*/
package net.micode.notes.gtask.data;
/*
*
*
*
* Made By CuiCan
*/
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
@ -49,30 +36,15 @@ import org.json.JSONObject;
public class SqlData {
/*
* TAG
* getSimpleName ()
*/
private static final String TAG = SqlData.class.getSimpleName();
private static final int INVALID_ID = -99999;//为mDataId置初始值-99999
/*
* NotesDataColumn
*/
private static final int INVALID_ID = -99999;
// 集合了interface DataColumns中所有SF常量
public static final String[] PROJECTION_DATA = new String[] {
DataColumns.ID, DataColumns.MIME_TYPE, DataColumns.CONTENT, DataColumns.DATA1,
DataColumns.DATA3
};
//以下变量作为sql表中5列的编号
public static final int DATA_ID_COLUMN = 0;
public static final int DATA_MIME_TYPE_COLUMN = 1;
@ -84,7 +56,7 @@ public class SqlData {
public static final int DATA_CONTENT_DATA_3_COLUMN = 4;
private ContentResolver mContentResolver;
//判断是否直接用Content生成是为true否则为false
private boolean mIsCreate;
private long mDataId;
@ -99,13 +71,6 @@ public class SqlData {
private ContentValues mDiffDataValues;
/*
*
* mContentResolverContentProvider
* mIsCreate
*/
public SqlData(Context context) {
mContentResolver = context.getContentResolver();
mIsCreate = true;
@ -117,13 +82,6 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/*
*
* mContentResolverContentProvider
* mIsCreate
*/
public SqlData(Context context, Cursor c) {
mContentResolver = context.getContentResolver();
mIsCreate = false;
@ -131,12 +89,6 @@ public class SqlData {
mDiffDataValues = new ContentValues();
}
/*
*
*
*/
private void loadFromCursor(Cursor c) {
mDataId = c.getLong(DATA_ID_COLUMN);
mDataMimeType = c.getString(DATA_MIME_TYPE_COLUMN);
@ -145,13 +97,7 @@ public class SqlData {
mDataContentData3 = c.getString(DATA_CONTENT_DATA_3_COLUMN);
}
/*
*
*/
public void setContent(JSONObject js) throws JSONException {
//如果传入的JSONObject对象中有DataColumns.ID这一项则设置否则设为INVALID_ID
long dataId = js.has(DataColumns.ID) ? js.getLong(DataColumns.ID) : INVALID_ID;
if (mIsCreate || mDataId != dataId) {
mDiffDataValues.put(DataColumns.ID, dataId);
@ -184,18 +130,11 @@ public class SqlData {
mDataContentData3 = dataContentData3;
}
/*
*
*
*/
public JSONObject getContent() throws JSONException {
if (mIsCreate) {
Log.e(TAG, "it seems that we haven't created this in database yet");
return null;
}
//创建JSONObject对象。并将相关数据放入其中并返回。
JSONObject js = new JSONObject();
js.put(DataColumns.ID, mDataId);
js.put(DataColumns.MIME_TYPE, mDataMimeType);
@ -204,9 +143,7 @@ public class SqlData {
js.put(DataColumns.DATA3, mDataContentData3);
return js;
}
/*
* commit
*/
public void commit(long noteId, boolean validateVersion, long version) {
if (mIsCreate) {
@ -246,12 +183,6 @@ public class SqlData {
mIsCreate = false;
}
/*
* id
*
*/
public long getId() {
return mDataId;
}

@ -13,10 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Description便sqldatanotedata
* SqlDataSqlNote
*/
package net.micode.notes.gtask.data;
import android.appwidget.AppWidgetManager;
@ -40,21 +37,12 @@ import org.json.JSONObject;
import java.util.ArrayList;
/*
*
*
*/
public class SqlNote {
private static final String TAG = SqlNote.class.getSimpleName();
/*
* TAG
* getSimpleName ()
*/
private static final int INVALID_ID = -99999;
// 集合了interface NoteColumns中所有SF常量17个
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,
@ -63,7 +51,7 @@ public class SqlNote {
NoteColumns.LOCAL_MODIFIED, NoteColumns.ORIGIN_PARENT_ID, NoteColumns.GTASK_ID,
NoteColumns.VERSION
};
//以下设置17个列的编号
public static final int ID_COLUMN = 0;
public static final int ALERTED_DATE_COLUMN = 1;
@ -97,7 +85,7 @@ public class SqlNote {
public static final int GTASK_ID_COLUMN = 15;
public static final int VERSION_COLUMN = 16;
//以下定义了17个内部的变量其中12个可以由content中获得5个需要初始化为0或者new
private Context mContext;
private ContentResolver mContentResolver;
@ -133,12 +121,7 @@ public class SqlNote {
private ContentValues mDiffNoteValues;
private ArrayList<SqlData> mDataList;
/*
*
* mIsCreate
*/
//构造函数只有context对所有的变量进行初始化
public SqlNote(Context context) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -146,9 +129,9 @@ public class SqlNote {
mId = INVALID_ID;
mAlertDate = 0;
mBgColorId = ResourceParser.getDefaultBgId(context);
mCreatedDate = System.currentTimeMillis();//调用系统函数获得创建时间
mCreatedDate = System.currentTimeMillis();
mHasAttachment = 0;
mModifiedDate = System.currentTimeMillis();//最后一次修改时间初始化为创建时间
mModifiedDate = System.currentTimeMillis();
mParentId = 0;
mSnippet = "";
mType = Notes.TYPE_NOTE;
@ -159,12 +142,6 @@ public class SqlNote {
mDiffNoteValues = new ContentValues();
mDataList = new ArrayList<SqlData>();
}
/*
*
* mIsCreate
*/
//构造函数有context和一个数据库的cursor多数变量通过cursor指向的一条记录直接进行初始化
public SqlNote(Context context, Cursor c) {
mContext = context;
@ -176,10 +153,7 @@ public class SqlNote {
loadDataContent();
mDiffNoteValues = new ContentValues();
}
/*
*
* mIsCreate
*/
public SqlNote(Context context, long id) {
mContext = context;
mContentResolver = context.getContentResolver();
@ -199,10 +173,9 @@ public class SqlNote {
new String[] {
String.valueOf(id)
}, null);
if (c != null) {//通过id获得对应的ContentResolver中的cursor
if (c != null) {
c.moveToNext();
loadFromCursor(c);//然后加载数据进行初始化,这样函数
//SqlNote(Context context, long id)与SqlNote(Context context, long id)的实现方式基本相同
loadFromCursor(c);
} else {
Log.w(TAG, "loadFromCursor: cursor = null");
}
@ -211,11 +184,8 @@ public class SqlNote {
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);
@ -229,9 +199,7 @@ public class SqlNote {
mWidgetType = c.getInt(WIDGET_TYPE_COLUMN);
mVersion = c.getLong(VERSION_COLUMN);
}
/*
* content
* */
private void loadDataContent() {
Cursor c = null;
mDataList.clear();
@ -257,8 +225,7 @@ public class SqlNote {
c.close();
}
}
/*
* content*/
public boolean setContent(JSONObject js) {
try {
JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
@ -392,8 +359,6 @@ public class SqlNote {
return true;
}
/*
* contentnote*/
public JSONObject getContent() {
try {
JSONObject js = new JSONObject();
@ -441,49 +406,40 @@ public class SqlNote {
}
return null;
}
/*
* idid*/
public void setParentId(long id) {
mParentId = id;
mDiffNoteValues.put(NoteColumns.PARENT_ID, id);
}
/*
* idGtaskid*/
public void setGtaskId(String gid) {
mDiffNoteValues.put(NoteColumns.GTASK_ID, gid);
}
/*
* idid*/
public void setSyncId(long syncId) {
mDiffNoteValues.put(NoteColumns.SYNC_ID, syncId);
}
/*
* */
public void resetLocalModified() {
mDiffNoteValues.put(NoteColumns.LOCAL_MODIFIED, 0);
}
/*
* id*/
public long getId() {
return mId;
}
/*
* idid*/
public long getParentId() {
return mParentId;
}
/*
* 便*/
public String getSnippet() {
return mSnippet;
}
/*
* 便*/
public boolean isNoteType() {
return mType == Notes.TYPE_NOTE;
}
/*
* commit*/
public void commit(boolean validateVersion) {
if (mIsCreate) {
if (mId == INVALID_ID && mDiffNoteValues.containsKey(NoteColumns.ID)) {

@ -35,22 +35,22 @@ import org.json.JSONObject;
public class Task extends Node {
private static final String TAG = Task.class.getSimpleName();
private boolean mCompleted;//是否完成
private boolean mCompleted;
private String mNotes;
private JSONObject mMetaInfo;//将在实例中存储数据的类型
private JSONObject mMetaInfo;
private Task mPriorSibling;
private TaskList mParent;//所在的任务列表的指针
private TaskList mParent;
public Task() {
super();
mCompleted = false;
mNotes = null;
mPriorSibling = null;//TaskList中当前Task前面的Task的指针
mParent = null;//当前Task所在的TaskList
mPriorSibling = null;
mParent = null;
mMetaInfo = null;
}

@ -31,11 +31,11 @@ import java.util.ArrayList;
public class TaskList extends Node {
private static final String TAG = TaskList.class.getSimpleName();//tag标记
private static final String TAG = TaskList.class.getSimpleName();
private int mIndex;//当前TaskList的指针
private int mIndex;
private ArrayList<Task> mChildren;//类中主要的保存数据的单元用来实现一个以Task为元素的ArrayList
private ArrayList<Task> mChildren;
public TaskList() {
super();
@ -43,7 +43,6 @@ public class TaskList extends Node {
mIndex = 1;
}
//生成并返回一个包含了一定数据的JSONObject实体
public JSONObject getCreateAction(int actionId) {
JSONObject js = new JSONObject();
@ -75,8 +74,6 @@ public class TaskList extends Node {
return js;
}
//生成并返回一个包含了一定数据的JSONObject实体
public JSONObject getUpdateAction(int actionId) {
JSONObject js = new JSONObject();
@ -219,8 +216,6 @@ public class TaskList extends Node {
return SYNC_ACTION_ERROR;
}
//功能获得TaskList的大小即mChildren的大小
public int getChildTaskCount() {
return mChildren.size();
}
@ -238,7 +233,7 @@ public class TaskList extends Node {
}
return ret;
}
//功能:在当前任务表的指定位置添加新的任务
public boolean addChildTask(Task task, int index) {
if (index < 0 || index > mChildren.size()) {
Log.e(TAG, "add child task: invalid index");
@ -265,7 +260,6 @@ public class TaskList extends Node {
return true;
}
// 功能删除TaskList中的一个Task
public boolean removeChildTask(Task task) {
boolean ret = false;
int index = mChildren.indexOf(task);
@ -287,7 +281,6 @@ public class TaskList extends Node {
return ret;
}
//功能将当前TaskList中含有的某个Task移到index位置
public boolean moveChildTask(Task task, int index) {
if (index < 0 || index >= mChildren.size()) {
@ -305,10 +298,7 @@ public class TaskList extends Node {
return true;
return (removeChildTask(task) && addChildTask(task, index));
}
//利用已实现好的功能完成当下功能;
// 功能按gid寻找Task
public Task findChildTaskByGid(String gid) {
for (int i = 0; i < mChildren.size(); i++) {
Task t = mChildren.get(i);
@ -318,13 +308,11 @@ public class TaskList extends Node {
}
return null;
}
//功能返回指定Task的index
public int getChildTaskIndex(Task task) {
return mChildren.indexOf(task);
}
//功能返回指定index的Task
public Task getChildTaskByIndex(int index) {
if (index < 0 || index >= mChildren.size()) {
Log.e(TAG, "getTaskByIndex: invalid index");
@ -333,8 +321,6 @@ public class TaskList extends Node {
return mChildren.get(index);
}
//功能返回指定index的Task
public Task getChilTaskByGid(String gid) {
for (Task task : mChildren) {
if (task.getGid().equals(gid))

@ -14,24 +14,14 @@
* limitations under the License.
*/
// 支持小米便签运行过程中的运行异常处理
package net.micode.notes.gtask.exception;
public class ActionFailureException extends RuntimeException {
private static final long serialVersionUID = 4425249765923293627L;
/*
* serialVersionUIDjava
* serialVersionUID
*/
public ActionFailureException() {
super();
}
/*
* JAVA使superthis.
* new
*/
public ActionFailureException(String paramString) {
super(paramString);

@ -13,20 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Description便
*/
package net.micode.notes.gtask.exception;
public class NetworkFailureException extends Exception {
private static final long serialVersionUID = 2107610287180234136L;
// serialVersionUID作用是序列化时保持版本的兼容性即在版本升级时反序列化仍保持对象的唯一性。
/*
* JAVA使superthis.
* new
*/
public NetworkFailureException() {
super();

@ -28,13 +28,6 @@ import net.micode.notes.R;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;
/*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
*/
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
@ -64,7 +57,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager.cancelSync();
}
public void publishProgess(String message) {// 发布进度单位系统将会调用onProgressUpdate()方法更新这些值
public void publishProgess(String message) {
publishProgress(new String[] {
message
});
@ -73,29 +66,30 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
private void showNotification(int tickerId, String content) {
Notification notification = new Notification(R.drawable.notification, mContext
.getString(tickerId), System.currentTimeMillis());
notification.defaults = Notification.DEFAULT_LIGHTS;// 调用系统自带灯光
notification.defaults = Notification.DEFAULT_LIGHTS;
notification.flags = Notification.FLAG_AUTO_CANCEL;
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0);//如果同步不成功那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象
NotesPreferenceActivity.class), 0);
} else {
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0);//如果同步成功那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象
NotesListActivity.class), 0);
}
// notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
// pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify方法来执行一个notification的消息
notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,
pendingIntent);
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
// @Override
@Override
protected Integer doInBackground(Void... unused) {
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this); //进行后台同步具体操作
return mTaskManager.sync(mContext, this);
}
// @Override
@Override
protected void onProgressUpdate(String... progress) {
showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) {
@ -103,8 +97,8 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
}
}
//@Override
protected void onPostExecute(Integer result) {//用于在执行完后台任务后更新UI,显示结果
@Override
protected void onPostExecute(Integer result) {
if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));

@ -60,10 +60,7 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
/*
* GTASKGTASK
* 使accountManager JSONObject HttpParams authToken Gid
*/
public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName();
@ -105,10 +102,6 @@ public class GTaskClient {
mUpdateArray = null;
}
/*
* 使 getInstance()
* mInstance
*/
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();

@ -87,9 +87,9 @@ public class GTaskManager {
private HashMap<Long, String> mNidToGid;
private GTaskManager() { //对象初始化函数
mSyncing = false; //正在同步,flase代表未执行
mCancelled = false; //全局标识flase代表可以执行
private GTaskManager() {
mSyncing = false;
mCancelled = false;
mGTaskListHashMap = new HashMap<String, TaskList>();
mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>();
@ -113,7 +113,7 @@ public class GTaskManager {
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "Sync is in progress");//创建日志文件调试信息debug
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
mContext = context;
@ -128,7 +128,7 @@ public class GTaskManager {
mNidToGid.clear();
try {
GTaskClient client = GTaskClient.getInstance();//getInstance即为创建一个实例,client--客户机
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// login google task
@ -140,7 +140,7 @@ public class GTaskManager {
// get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList(); //获取Google上的JSONtasklist转为本地TaskList
initGTaskList();
// do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
@ -168,17 +168,12 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
/*
*GtaskListGoogleJSONtasklistTaskList
*mMetaListmGTaskListHashMapmGTaskHashMap
*/
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
GTaskClient client = GTaskClient.getInstance();
try {
JSONArray jsTaskLists = client.getTaskLists(); //getInstance即为创建一个实例client应指远端客户机
JSONArray jsTaskLists = client.getTaskLists();
// init meta list first
mMetaList = null;
@ -252,8 +247,6 @@ public class GTaskManager {
}
}
//功能:本地内容同步操作
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;

@ -42,8 +42,6 @@ public class GTaskSyncService extends Service {
private static String mSyncProgress = "";
////开始一个同步的工作
private void startSync() {
if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -67,14 +65,13 @@ public class GTaskSyncService extends Service {
@Override
public void onCreate() {
mSyncTask = null;
}///初始化一个service
}
@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;
@ -84,7 +81,7 @@ public class GTaskSyncService extends Service {
default:
break;
}
return START_STICKY;//等待新的intent来是这个service继续运行
return START_STICKY;
}
return super.onStartCommand(intent, flags, startId);
}

@ -42,11 +42,11 @@ public class Note {
* Create a new note id for adding a new note to databases
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
//为给定文件夹生成新的笔记ID
// 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.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);
@ -71,7 +71,6 @@ public class 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());
@ -80,12 +79,11 @@ public class Note {
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
//为笔记设置文本数据。
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
//setTextDataId、getTextDataId、setCallDataId、setCallData 这些方法处理与笔记相关的文本和通话信息的ID和数据的设置和获取。
public long getTextDataId() {
return mNoteData.mTextDataId;
}
@ -101,7 +99,7 @@ public class Note {
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);
@ -110,8 +108,6 @@ public class Note {
if (!isLocalModified()) {
return true;
}
//尝试将笔记与提供的上下文和笔记ID同步。
//如果笔记ID小于或等于0或者没有本地修改则返回true。
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
@ -151,19 +147,17 @@ public class Note {
mTextDataId = 0;
mCallDataId = 0;
}
//初始化 mTextDataValues 和 mCallDataValues 为 ContentValues 对象,用于存储文本数据和通话数据。
//初始化 mTextDataId 和 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如果提供的ID小于等于0报告异常
void setCallDataId(long id) {
if (id <= 0) {
@ -171,57 +165,52 @@ public class Note {
}
mCallDataId = id;
}
//设置通话数据的键值对,并标记笔记为本地修改,更新修改日期
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
//设置文本数据的键值对,并标记笔记为本地修改,更新修改日期
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
}
//将数据推送到ContentResolver的方法
Uri pushIntoContentResolver(Context context, long noteId) {
//检查noteID的有效性如果小于等于0抛出IllegalArgumentException
/**
* Check for safety
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
//用于保存ContentProvider操作列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
//处理文本数据的操作
if(mTextDataValues.size() > 0) {
//设置文本数据的关联noteID
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
// 如果mTextDataId为0表示需要插入新的文本数据
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
//插入数据并获取新的Uri
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
// 解析Uri中的数据获取新插入数据的id并设置给mTextDataId
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
// 插入数据失败,记录错误日志并清空数据
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}
} else {
// mTextDataId不为0表示需要更新已存在的文本数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
// 清空文本数据,以便下一次使用
mTextDataValues.clear();
}
// 处理通话数据的操作,逻辑类似于文本数据
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
@ -243,20 +232,17 @@ public class Note {
}
mCallDataValues.clear();
}
// 如果有待执行的操作将它们应用到ContentResolver
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
// 返回插入或更新后的笔记的Uri如果操作失败则返回null
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
// 捕获远程异常并记录错误日志
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;
}
@ -265,5 +251,3 @@ public class Note {
}
}
}

@ -128,11 +128,9 @@ public class WorkingNote {
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);
@ -140,49 +138,37 @@ public class WorkingNote {
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
}
// 关闭查询结果的游标
cursor.close();
} else {
// 如果查询结果为空,则输出错误日志并抛出异常
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
// 调用loadNoteData()方法加载笔记的其他数据
loadNoteData();
}
private void loadNoteData() {
// 通过内容解析器(ContentResolver)查询笔记的数据信息
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
}, null);
// 检查查询结果是否为空
if (cursor != null) {
// 移动到查询结果的第一行(如果有多行数据)
if (cursor.moveToFirst()) {
do {
// 获取数据类型
String type = cursor.getString(DATA_MIME_TYPE_COLUMN);
// 根据数据类型进行不同的处理
if (DataConstants.NOTE.equals(type)) {
// 如果是笔记类型的数据,获取内容和模式,并设置到相应的成员变量中
mContent = cursor.getString(DATA_CONTENT_COLUMN);
mMode = cursor.getInt(DATA_MODE_COLUMN);
mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN));
} else if (DataConstants.CALL_NOTE.equals(type)) {
// 如果是通话笔记类型的数据设置通话数据ID到相应的成员变量中
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
// 如果是未知类型的数据,输出调试信息
Log.d(TAG, "Wrong note type with type:" + type);
}
} while (cursor.moveToNext());
}
// 关闭查询结果的游标
cursor.close();
} else {
// 如果查询结果为空,则输出错误日志并抛出异常
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}
@ -202,32 +188,27 @@ public class WorkingNote {
}
public synchronized boolean saveNote() {
// 检查笔记是否值得保存
if (isWorthSaving()) {
// 检查笔记是否存在于数据库中
if (!existInDatabase()) {
// 如果笔记在数据库中不存在尝试创建一个新的笔记ID
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
// 如果创建新的笔记ID失败输出错误日志并返回保存失败
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;//保存成功
return true;
} else {
return false;//保存失败
return false;
}
}
@ -249,55 +230,38 @@ public class WorkingNote {
}
public void setAlertDate(long date, boolean set) {
// 检查传入的日期是否与当前提醒日期不同
if (date != mAlertDate) {
// 如果不同,更新当前提醒日期为传入的日期,并通过 mNote 对象将更新后的提醒日期同步到数据库中
mAlertDate = date;
mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate));
}
// 检查是否存在笔记设置状态监听器
if (mNoteSettingStatusListener != null) {
// 如果存在,调用监听器的 onClockAlertChanged 方法,通知提醒日期已更改,并传递新的日期和开关状态
mNoteSettingStatusListener.onClockAlertChanged(date, set);
}
}
public void markDeleted(boolean mark) {
// 将笔记的删除状态更新为传入的标记值
mIsDeleted = mark;
// 检查是否存在与该笔记相关的小部件,并且小部件类型有效,并且存在笔记设置状态监听器
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
// 如果条件满足,调用监听器的 onWidgetChanged 方法,通知小部件内容已更改
mNoteSettingStatusListener.onWidgetChanged();
}
}
public void setBgColorId(int id) {
// 检查传入的颜色ID是否与当前背景颜色ID不同
if (id != mBgColorId) {
// 如果不同更新当前背景颜色ID为传入的颜色ID
mBgColorId = id;
// 检查是否存在笔记设置状态监听器
if (mNoteSettingStatusListener != null) {
// 如果存在,调用监听器的 onBackgroundColorChanged 方法,通知背景颜色已更改
mNoteSettingStatusListener.onBackgroundColorChanged();
}
// 通过 mNote 对象将更新后的背景颜色ID同步到数据库中
mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id));
}
}
public void setCheckListMode(int mode) {
if (mMode != mode) {
// 如果不同,更新当前模式为传入的模式
// 检查是否存在笔记设置状态监听器
if (mNoteSettingStatusListener != null) {
// 如果存在,调用监听器的 onCheckListModeChanged 方法,通知检查清单模式已更改,并传递旧模式和新模式
mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);
}
// 将当前模式更新为传入的模式,并通过 mNote 对象将更新后的模式同步到数据库中
mMode = mode;
mNote.setTextData(TextNote.MODE, String.valueOf(mMode));
}
@ -311,23 +275,15 @@ public class WorkingNote {
}
public void setWidgetId(int id) {
// 检查传入的小部件类型是否与当前小部件类型不同
if (id != mWidgetId) {
// 如果不同,更新当前小部件类型为传入的小部件类型
mWidgetId = id;
// 通过 mNote 对象将更新后的小部件类型同步到数据库中
mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId));
}
}
public void setWorkingText(String text) {
// 检查传入的文本内容是否与当前内容不同
if (!TextUtils.equals(mContent, text)) {
// 如果不同,更新当前内容为传入的文本内容
mContent = text;
// 通过 mNote 对象将更新后的文本内容同步到数据库中
mNote.setTextData(DataColumns.CONTENT, mContent);
}
}

@ -1,3 +1,18 @@
/*
* 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;
@ -23,7 +38,7 @@ 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) {
@ -37,15 +52,15 @@ public class BackupUtils {
* Following states are signs to represents backup or restore
* status
*/
// 当前SD卡未挂载
// Currently, the sdcard is not mounted
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;
@ -122,10 +137,10 @@ public class BackupUtils {
}
/**
* id
* Export the folder identified by folder id to text
*/
private void exportFolderToText(String folderId, PrintStream ps) {
// 查询属于此文件夹的便签
// Query notes belong to this folder
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId
@ -134,11 +149,11 @@ public class BackupUtils {
if (notesCursor != null) {
if (notesCursor.moveToFirst()) {
do {
// 打印便签的最后修改日期
// Print note's last modified date
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);
} while (notesCursor.moveToNext());
@ -148,7 +163,7 @@ public class BackupUtils {
}
/**
* id便
* 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,
@ -161,7 +176,7 @@ public class BackupUtils {
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);
@ -170,11 +185,11 @@ public class BackupUtils {
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));
@ -190,7 +205,7 @@ public class BackupUtils {
}
dataCursor.close();
}
// 在便签之间打印一行分隔符
// print a line separator between note
try {
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -225,7 +240,7 @@ public class BackupUtils {
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);
@ -255,7 +270,7 @@ public class BackupUtils {
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);
exportNoteToText(noteId, ps);
} while (noteCursor.moveToNext());
@ -268,7 +283,7 @@ public class BackupUtils {
}
/**
* {@generateExportedTextFile}
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
@ -295,7 +310,7 @@ public class BackupUtils {
}
/**
*
* Generate the text file to store imported data
*/
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder();

@ -37,49 +37,39 @@ import java.util.HashSet;
public class DataUtils {
public static final String TAG = "DataUtils";
// 批量删除笔记的静态方法
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查传入的笔记ID集合是否为空
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;// 如果为空,返回删除成功
return true;
}
// 检查传入的笔记ID集合是否为空
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true;// 如果为空,返回删除成功
return true;
}
// 创建一个操作列表,用于存储批量操作的删除操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 遍历传入的笔记ID集合为每个ID创建一个删除操作并添加到操作列表中
for (long id : ids) {
// 检查是否为系统文件夹的ID如果是跳过不删除
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
// 创建删除操作的构建器
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 将删除操作添加到操作列表中
operationList.add(builder.build());
}
try {
// 应用批量操作,删除笔记
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查批量操作结果是否为空或第一个结果是否为空
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;// 如果为空,返回删除失败
return false;
}
return true;// 返回删除成功
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;// 返回删除失败
return false;
}
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
@ -92,34 +82,27 @@ public class DataUtils {
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) {
// 检查传入的笔记ID集合是否为空
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;// 如果为空,返回移动成功
return true;
}
// 创建一个操作列表,用于存储批量操作的更新操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 遍历传入的笔记ID集合为每个ID创建一个更新操作并设置新的父文件夹ID和本地修改标志
for (long id : ids) {
// 创建更新操作的构建器
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 设置更新操作的值包括新的父文件夹ID和本地修改标志
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
// 将更新操作添加到操作列表中
operationList.add(builder.build());
}
try {
// 应用批量操作更新笔记的父文件夹ID和本地修改标志
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 false;
}
return true;// 返回移动成功
return true;
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
@ -132,108 +115,89 @@ public class DataUtils {
* 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(*)" },
// 查询条件类型为文件夹且父文件夹ID不是回收站文件夹ID
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER)},
null);
int count = 0;
if(cursor != null) {
// 如果查询结果非空,移动到第一行
if(cursor.moveToFirst()) {
try {
// 获取查询结果中的文件夹数量
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
// 捕获异常,输出错误日志
Log.e(TAG, "get folder count failed:" + e.toString());
} finally {
// 关闭游标
cursor.close();
}
}
}
return count;// 返回文件夹数量
return count;
}
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
// 查询指定笔记ID的可见性
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null,
// 查询条件类型为指定类型且父文件夹ID不是回收站文件夹ID
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
new String [] {String.valueOf(type)},
null);
boolean exist = false;
if (cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if (cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
return exist;// 返回是否存在
return exist;
}
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 查询指定笔记ID是否存在于笔记数据库中
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if (cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
return exist;// 返回是否存在
return exist;
}
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
// 查询指定数据ID是否存在于数据数据库中
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
null, null, null, null);
boolean exist = false;
if (cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if (cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist;// 返回是否存在
return exist;
}
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
// 查询是否存在具有指定名称的可见文件夹
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
// 查询条件类型为文件夹、父文件夹ID不是回收站文件夹ID、且摘要等于指定名称
NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER +
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
// 如果查询结果非空检查结果数量是否大于0表示存在
if(cursor.getCount() > 0) {
exist = true;
}
cursor.close();
}
return exist; // 返回是否存在
return exist;
}
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询指定文件夹ID下的笔记小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
@ -242,30 +206,25 @@ public class DataUtils {
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
// 如果查询结果非空,移动到第一行
if (c.moveToFirst()) {
set = new HashSet<AppWidgetAttribute>();
do {
try {
// 创建 AppWidgetAttribute 对象获取小部件ID和小部件类型添加到集合中
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;// 返回包含小部件信息的集合
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 + "=?",
@ -274,20 +233,17 @@ public class DataUtils {
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 "";// 如果查询结果为空,返回空字符串
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("
@ -296,24 +252,19 @@ public class DataUtils {
null);
if (cursor != null) {
// 如果查询结果非空,移动到第一行
if (cursor.moveToFirst()) {
try {
// 获取查询结果中的笔记ID
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
// 捕获异常,输出错误日志
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
cursor.close();
}
return 0; // 如果查询结果为空返回0
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 + "=?",
@ -321,20 +272,17 @@ public class DataUtils {
null);
if (cursor != null) {
// 如果查询结果非空,移动到第一行
String snippet = "";
if (cursor.moveToFirst()) {
// 获取查询结果中的摘要信息
snippet = cursor.getString(0);
}
cursor.close();
return snippet;// 返回摘要信息
return snippet;
}
throw new IllegalArgumentException("Note is not found with id: " + noteId);
}
public static String getFormattedSnippet(String snippet) {
// 格式化摘要信息:去除首尾空格,并截取首个换行符之前的内容
if (snippet != null) {
snippet = snippet.trim();
int index = snippet.indexOf('\n');
@ -342,7 +290,6 @@ public class DataUtils {
snippet = snippet.substring(0, index);
}
}
return snippet;// 返回格式化后的摘要信息
return snippet;
}
}

@ -66,19 +66,15 @@ public class ResourceParser {
}
public static int getDefaultBgId(Context context) {
// 获取默认背景ID
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
// 如果用户已设置背景颜色则返回随机选择的编辑界面背景资源ID
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
// 如果用户未设置背景颜色则返回默认颜色的背景资源ID
return BG_DEFAULT_COLOR;
}
}
public static class NoteItemBgResources {
// 定义笔记列表项背景资源数组
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,

@ -12,40 +12,56 @@ import android.widget.Toast;
import net.micode.notes.R;
//继承自 Activity 类,提供用户界面删除已设置的密码
public class DeletingPassword extends Activity {
//定义 EditText 成员变量获取用户输入的密码
EditText Dt_password;
//定义 Button 成员变量,用户点击后确认删除密码
Button Acknowledged;
// Activity 的 onCreate()方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置当前 Activity 使用的布局文件
setContentView(R.layout.activity_delete_password);
//设置软键盘行为
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//关联至布局文件中的 EditText 组件(用于输入密码)
Dt_password=(EditText) findViewById(R.id.thepassword);
//关联至布局文件中的 Button 组件(确认删除按钮)
Acknowledged=(Button)findViewById(R.id.Dt_Acknowledged);
//设置确认删除按钮的点击监听器
Acknowledged.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取用户输入的密码
String text02 = Dt_password.getText().toString();
if(text02.equals("")==true)
Toast.makeText(DeletingPassword.this, "密码不能为空",
Toast.LENGTH_SHORT).show();
//检查密码是否为空
if(text02.equals("")==true) {
Toast.makeText(DeletingPassword.this, "密码不能为空", Toast.LENGTH_SHORT).show();
return; //为空则直接返回不进行后续操作
}
//获取 SharedPreferences 中保存的密码
SharedPreferences pref=getSharedPreferences("user management",MODE_PRIVATE);
String password = pref.getString("password","");
String password = pref.getString("password","");
//如果存储密码不为空,且与用户输入密码匹配
if(password.equals("")==false&&password.equals(text02)==true){
//获取 SharedPreferences 编辑器以删除密码
SharedPreferences.Editor editor=getSharedPreferences("user management", MODE_PRIVATE).edit();
editor.putBoolean("user",false);//false 表示已经设置登录密码
editor.putString("password","");
editor.apply();
Toast.makeText(DeletingPassword.this, "已经删除登录密码",
Toast.LENGTH_SHORT).show();
Intent intent=new
Intent(DeletingPassword.this,NotesListActivity.class);
editor.putBoolean("user",false);//false 表示登录密码已被设置
editor.putString("password",""); //清除密码
editor.apply(); //应用更改
//显示已删除登录密码的提示信息
Toast.makeText(DeletingPassword.this, "已经删除登录密码", Toast.LENGTH_SHORT).show();
//跳回便签列表界面
Intent intent=new Intent(DeletingPassword.this,NotesListActivity.class);
startActivity(intent);
finish();
finish(); //结束当前 Activity
}
else{
//如果输入的密码不正确,显示错误信息
Toast.makeText(DeletingPassword.this, "密码错误",
Toast.LENGTH_SHORT).show();
Dt_password.setText("");//把密码框内输入过的错误密码清空
@ -53,6 +69,8 @@ public class DeletingPassword extends Activity {
}
});
}
//重写 onBackPressed 方法,用于用户按下返回键的行为
@Override
public void onBackPressed() {
Intent intent=new Intent(DeletingPassword.this,NotesListActivity.class);

@ -27,34 +27,39 @@ import android.widget.PopupMenu.OnMenuItemClickListener;
import net.micode.notes.R;
//DropdownMenu类用来创建和显示一个下拉菜单
public class DropdownMenu {
private Button mButton;
private PopupMenu mPopupMenu;
private Menu mMenu;
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 = button;//将传入的按钮引用赋值给mButton
mButton.setBackgroundResource(R.drawable.dropdown_icon);//设置这个按钮的背景为下拉图标
mPopupMenu = new PopupMenu(context, mButton);//初始化PopupMenu
mMenu = mPopupMenu.getMenu();//获取PopupMenu关联的Menu对象
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);//使用传入的menuId资源填充Menu
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
}
}//显示菜单
});
}
//设置菜单项点击监听器
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener);
}
}
//查找具体的菜单项
public MenuItem findItem(int id) {
return mMenu.findItem(id);
}
//设置按钮的标题文字
public void setTitle(CharSequence title) {
mButton.setText(title);
}

@ -24,57 +24,66 @@ 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;
import net.micode.notes.R;//引入资源文件
import net.micode.notes.data.Notes;//引入与Notes相关的数据处理类
import net.micode.notes.data.Notes.NoteColumns;//引入NOte数据表中的字段
//FoldersListAdapter 类是CursorAdapter的一个子类用于提供文件夹数据的视图
public class FoldersListAdapter extends CursorAdapter {
//定义查询结果的列这里只用到ID和SNIPET列
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
};
//定义列的索引,方便读取数据时使用
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
//该类的构造函数
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
//必须重写的newView方法用于创建新的列表项视图
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new FolderListItem(context);
return new FolderListItem(context);//创建一个新的FoldersListItem实例
}
//用于将数据绑定到视图上
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof FolderListItem) {
if (view instanceof FolderListItem) {//检查视图类型是否正确
//根据ID列判断是否根文件夹是则使用预定义字符串否则使用数据库中的名字
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);
((FolderListItem) view).bind(folderName);//调用FolderListItem的bind方法绑定文件夹名称
}
}
//辅助方法,根据位置获取文件夹名称
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
Cursor cursor = (Cursor) getItem(position);//获取对应位置的游标
//同样根据ID列判断文件夹名称
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}
//FolderListItem是LinearLayout的一个内部子类用于表示每一项文件夹
private class FolderListItem extends LinearLayout {
private TextView mName;
private TextView mName;//文件夹名称的Textview
public FolderListItem(Context context) {
super(context);
inflate(context, R.layout.folder_list_item, this);
mName = (TextView) findViewById(R.id.tv_folder_name);
super(context);//调用父类构造函数
inflate(context, R.layout.folder_list_item, this);//填充布局
mName = (TextView) findViewById(R.id.tv_folder_name);//获取布局中的TextView
}
public void bind(String name) {
mName.setText(name);
}
}//设置文件夹名称到Textview
}
}

@ -12,36 +12,52 @@ import android.app.Activity;
import net.micode.notes.R;
//LoginActivity 类继承自Activity 类,用于管理登录页面的行为
public class LoginActivity extends Activity{
//定义EditText 成员变量用于获取用户输入的密码
EditText lgn_password;
//定义Button成员变量用于用户点击登录
Button lgn_login;
//Activity 的 onCreate()方法在创建loginActivity 时被调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//获取名为 "user management" 的 SharedPreferences 对象,用于读取或存储轻量级的键值对数据
SharedPreferences pref = getSharedPreferences("user management", MODE_PRIVATE);
//从 SharedPreferences 对象中获取名为 "user" 的布尔值,检查用户是否设置了密码
boolean User_boolean = pref.getBoolean("user", false); //检查用户是否设置了密码
if (!User_boolean) { //如果用户没有设置密码,则直接跳转到便签主界面
Intent intent = new Intent(LoginActivity.this, NotesListActivity.class);
startActivity(intent);
finish();
finish(); //结束当前 Activity
}
//设置当前 Activity 使用的布局文件
setContentView(R.layout.activity_login);
//设置软键盘行为,这里设置的是在输入框获取焦点时显示软键盘并调整布局大小以适应键盘
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//关联变量 lgn_password 至布局文件中的 EditText 组件
lgn_password = (EditText)findViewById(R.id.lgn_password);
//关联变量lgn_login 至布局文件中的 Button 组件
lgn_login = (Button) findViewById(R.id.login);
//设置登录按钮的点击监听器
lgn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//再次或者SharedPreferences 对象
SharedPreferences pref = getSharedPreferences("user management", MODE_PRIVATE);
//获取 SharedPreferences 中存储的密码字符串,若不存在则返回空字符串
String password = pref.getString("password", "");
//比较存储的密码和用户输入的密码是否相同
if (password.equals(" ") == false && password.equals(lgn_password.getText().toString()) == true) {
//如果密码匹配,跳转至便签列表界面
Intent intent = new Intent(LoginActivity.this, NotesListActivity.class);
startActivity(intent);
finish();
finish(); //结束当前 Activity
} else {
//如果密码不匹配,显示 Toast 提醒用户密码错误,并清空密码输入框
Toast.makeText(LoginActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
lgn_password.setText(""); //清空密码框内的输入
}

@ -78,7 +78,7 @@ public class NoteEditActivity extends Activity implements OnClickListener,
NoteSettingChangedListener, OnTextViewChangeListener {
private class HeadViewHolder {
public TextView tvModified; //
public TextView tvModified;
public ImageView ivAlertIcon;
@ -498,12 +498,10 @@ public class NoteEditActivity extends Activity implements OnClickListener,
//如果点击的是设置背景颜色按钮,则显示颜色选择器
if (id == R.id.btn_set_bg_color) {
mNoteBgColorSelector.setVisibility(View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
-View.VISIBLE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(View.VISIBLE);
//更改背景颜色或字体大小的逻辑
} else if (sBgSelectorBtnsMap.containsKey(id)) {
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(
View.GONE);
findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility(View.GONE);
mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id));
mNoteBgColorSelector.setVisibility(View.GONE);
} else if (sFontSizeBtnsMap.containsKey(id)) {
@ -1013,17 +1011,17 @@ public class NoteEditActivity extends Activity implements OnClickListener,
}
final ImageButton add_img_btn = (ImageButton) findViewById(R.id.add_img_btn);
add_img_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
log.d(TAG, "onClick: click add image button");
Intent loadImage = new Intent(Intent.ACTION_GET_CONTENT);
loadImage.addCategory(Intent.CATEGORY_OPENABLE);
loadImage.setType("image/*");
startActivityForResult(loadImage, PHOTO_REQUESt);
}
});
// final ImageButton add_img_btn = (ImageButton) findViewById(R.id.add_img_btn);
// add_img_btn.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// log.d(TAG, "onClick: click add image button");
// Intent loadImage = new Intent(Intent.ACTION_GET_CONTENT);
// loadImage.addCategory(Intent.CATEGORY_OPENABLE);
// loadImage.setType("image/*");
// startActivityForResult(loadImage, PHOTO_REQUESt);
// }
// });
}

@ -25,8 +25,9 @@ import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.DataUtils;
//NoteItemData 类的定义,用于封装便签应用中的便签项的数据。
public class NoteItemData {
//用于查询数据库时所需的列的数组,声明了查询笔记项需要的所有数据库列
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
@ -42,6 +43,7 @@ public class NoteItemData {
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;
@ -55,28 +57,31 @@ public class NoteItemData {
private static final int WIDGET_ID_COLUMN = 10;
private static final int WIDGET_TYPE_COLUMN = 11;
private long mId;
private long mAlertDate;
private int mBgColorId;
private long mCreatedDate;
private boolean mHasAttachment;
private long mModifiedDate;
private int mNotesCount;
private long mParentId;
private String mSnippet;
private int mType;
private int mWidgetId;
private int mWidgetType;
private String mName;
private String mPhoneNumber;
private boolean mIsLastItem;
private boolean mIsFirstItem;
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
//下面私有成员变量用于存储笔记项数据
private long mId; //笔记项ID
private long mAlertDate; //提醒日期
private int mBgColorId; //背景颜色ID
private long mCreatedDate; //创建日期
private boolean mHasAttachment; //是否有附件
private long mModifiedDate; //修改日期
private int mNotesCount; //子项个数
private long mParentId; //父项Id
private String mSnippet; //笔记摘要
private int mType; //笔记类型
private int mWidgetId; //小工具ID
private int mWidgetType; //小工具类型
private String mName; //联系人名称
private String mPhoneNumber; //联系人电话
private boolean mIsLastItem; //是否为最后一项
private boolean mIsFirstItem; //是否为第一项
private boolean mIsOnlyOneItem; //是否只有一项
private boolean mIsOneNoteFollowingFolder; //是否仅有一个笔记跟随文件夹
private boolean mIsMultiNotesFollowingFolder; //是否有多个笔记跟随文件夹
//构造器从提供的有表数据创建NoteItemData 对象
public NoteItemData(Context context, Cursor cursor) {
//从游标中读取每列的数据并赋值给相应的成员变量
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
@ -94,6 +99,7 @@ public class NoteItemData {
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
//如果父项是通话记录文件夹,获取电话号码并查找联系人的名字
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
@ -106,9 +112,11 @@ public class NoteItemData {
if (mName == null) {
mName = "";
}
//调用该方法来判断笔记项在游标中的位置
checkPostion(cursor);
}
//判断当前位于游标中的位置情况,如是否是第一个,最后一个等,并相应地设置布尔标记位
private void checkPostion(Cursor cursor) {
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
@ -116,6 +124,7 @@ public class NoteItemData {
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
//如果当前项是笔记并且不是第一项,检查它的前一个项是否是文件夹或系统项
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {
@ -128,12 +137,14 @@ public class NoteItemData {
}
}
if (!cursor.moveToNext()) {
//如果无法返回到之前的位置,抛出异常
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
//为了获取NoteItemData对象内容的公共访问方法
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
@ -218,6 +229,7 @@ public class NoteItemData {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
//一个静态方法用来从游标中直接获取类型
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}

@ -795,6 +795,8 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
createNewNote();
} else if (itemId == R.id.menu_search) {
onSearchRequested();
} else if (itemId == R.id.menu_weather) {
startWeatherActivity();
}
return true;
}
@ -857,6 +859,13 @@ public class NotesListActivity extends Activity implements OnClickListener, OnIt
from.startActivityIfNeeded(intent, -1);
}
private void startWeatherActivity() {
Activity from = getParent() != null ? getParent() : this;
Intent intent = new Intent(from, WeatherActivity.class);
from.startActivity(intent);
}
private class OnListItemClickListener implements OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

@ -30,19 +30,22 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
//NoteListAdapter 类用于将数据从Cursor绑定到ListView的每个项
//定义了列表适配器的主要功能,如创建新视图进行绑定、处理项的选择状态、统计选中的项数等
public class NotesListAdapter extends CursorAdapter {
private static final String TAG = "NotesListAdapter";
private Context mContext;
private HashMap<Integer, Boolean> mSelectedIndex;
private int mNotesCount;
private boolean mChoiceMode;
private static final String TAG = "NotesListAdapter";//用于日志记录的TAG
private Context mContext;//用于保存上下文的变量
private HashMap<Integer, Boolean> mSelectedIndex;//保存被选中项的索引
private int mNotesCount;//便签数量
private boolean mChoiceMode;//是否选择模式
//AppEidgetAttribute 是一个静态内部类,用于存储小部件属性
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
};
//构造函数,初始化上下文和被选中项的哈希表
public NotesListAdapter(Context context) {
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
@ -50,38 +53,47 @@ public class NotesListAdapter extends CursorAdapter {
mNotesCount = 0;
}
//为给定数据创建新的ListsItem视图
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return new NotesListItem(context);
}
//将数据绑定到给定的视图上
@Override
public void bindView(View view, Context context, Cursor cursor) {
if (view instanceof NotesListItem) {
//创建一个NoteItemData对象用于从Cursor提取数据
NoteItemData itemData = new NoteItemData(context, cursor);
//绑定视图
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
}
}
//设置指定位置的项是否被选中
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
notifyDataSetChanged();
}
//返回是否处于选择模式
public boolean isInChoiceMode() {
return mChoiceMode;
}
//设置选择模式
public void setChoiceMode(boolean mode) {
mSelectedIndex.clear();
mChoiceMode = mode;
}
//选择或取消选择所有便签项
public void selectAll(boolean checked) {
Cursor cursor = getCursor();
for (int i = 0; i < getCount(); i++) {
if (cursor.moveToPosition(i)) {
//仅选择便签类型的项
if (NoteItemData.getNoteType(cursor) == Notes.TYPE_NOTE) {
setCheckedItem(i, checked);
}
@ -89,8 +101,10 @@ public class NotesListAdapter extends CursorAdapter {
}
}
//获取选中项的ID集合
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
//遍历mSelectedIndex查找选中的项目
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Long id = getItemId(position);
@ -105,8 +119,10 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
//获取选中的小部件集合
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
//同样遍历选中的项但是这一次获取widgetId和widgetType
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
@ -128,6 +144,7 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
//获取选中项的数量
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
if (null == values) {
@ -143,11 +160,13 @@ public class NotesListAdapter extends CursorAdapter {
return count;
}
//检查是否所有项都被选中了
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
}
//检查指定位置的项是否被转中
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
@ -155,18 +174,21 @@ public class NotesListAdapter extends CursorAdapter {
return mSelectedIndex.get(position);
}
//当内容改变时更新便签数量
@Override
protected void onContentChanged() {
super.onContentChanged();
calcNotesCount();
}
//更改cursor时同样更新便签数量
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
calcNotesCount();
}
//计算便签的数量,只计算类型为便签的项
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {

@ -29,18 +29,21 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
//定义NotesListItem 类扩展了LinearLayout 类,用于表示一个笔记的布局
public class NotesListItem extends LinearLayout {
private ImageView mAlert;
private TextView mTitle;
private TextView mTime;
private TextView mCallName;
private NoteItemData mItemData;
private CheckBox mCheckBox;
private ImageView mAlert; //用于显示警告图标
private TextView mTitle; //显示笔记标题
private TextView mTime; //显示最后修改时间
private TextView mCallName; //显示通话名称
private NoteItemData mItemData; //保存当前笔记项的数据
private CheckBox mCheckBox; //多选模式下的复选框
public NotesListItem(Context context) {
super(context);
//从布局文件 note_item.xml中加载布局
inflate(context, R.layout.note_item, this);
//通过findViewById 方法获取对应的控件对象
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
@ -48,7 +51,9 @@ public class NotesListItem extends LinearLayout {
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
//绑定数据到当前的笔记项,设置显示内容和样式
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {
//如果是多选模式且笔记类型为普通笔记
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
@ -56,8 +61,11 @@ public class NotesListItem extends LinearLayout {
mCheckBox.setVisibility(View.GONE);
}
//保存数据到成员变量中
mItemData = data;
//根据笔记的类型分别设置不同的显示方式
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
//如果是通话记录文件夹
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
@ -65,6 +73,7 @@ public class NotesListItem extends LinearLayout {
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {
//如果笔记是通话记录文件夹中的一项
mCallName.setVisibility(View.VISIBLE);
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
@ -76,15 +85,18 @@ public class NotesListItem extends LinearLayout {
mAlert.setVisibility(View.GONE);
}
} else {
//如果笔记既不是通话记录也不是通话记录文件夹中的一项
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
//如果笔记为文件夹类型
if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
} else {
//如果笔记为普通笔记
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
@ -94,13 +106,17 @@ public class NotesListItem extends LinearLayout {
}
}
}
//设置显示笔记最后修改时间,格式化为相对时间(如"5分钟前")
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
//根据数据设置背景图案
setBackground(data);
}
//设置背景图案的私有方法
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
//根据笔记类型和位置(身处列表中的位置),选择不同的背景
if (data.getType() == Notes.TYPE_NOTE) {
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
@ -112,10 +128,12 @@ public class NotesListItem extends LinearLayout {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
//如果是文件夹,则使用文件夹的背景资源
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
//获取当前笔记项的数据
public NoteItemData getItemData() {
return mItemData;
}

@ -49,6 +49,7 @@ import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity {
//定义常量键,用于引用特定的偏好设置
public static final String PREFERENCE_NAME = "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
@ -61,29 +62,33 @@ public class NotesPreferenceActivity extends PreferenceActivity {
private static final String AUTHORITIES_FILTER_KEY = "authorities";
//成员变量,用于管理偏好设置项
private PreferenceCategory mAccountCategory;
//广播接收器,用于接收相关相同操作广播通知
private GTaskReceiver mReceiver;
//存储原始的Google账号数组用于比较之后是否有变化
private Account[] mOriAccounts;
//标志变量,记录是否添加了新账户
private boolean mHasAddedAccount;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* using the app icon for navigation */
//启用向上导航使用应用程序图标
getActionBar().setDisplayHomeAsUpEnabled(true);
//从Preferences.xml资源文件添加偏好设置项到这个活动
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);
//初始化账户数组为null
mOriAccounts = null;
//为设置列表添加表头View
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);
}
@ -92,8 +97,8 @@ public class NotesPreferenceActivity extends PreferenceActivity {
protected void onResume() {
super.onResume();
// need to set sync account automatically if user has added a new
// account
//用户添加了新账户,自动设置同步账户
//通过比较原始账号和当前账户,确定新账户,并设置同步
if (mHasAddedAccount) {
Account[] accounts = getGoogleAccounts();
if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
@ -112,12 +117,13 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
}
//刷新UI界面可能涉及到帐号显示的更新
refreshUI();
}
@Override
protected void onDestroy() {
//注销广播接收器
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
@ -125,8 +131,10 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
private void loadAccountPreference() {
//清空账户分类列表,然后重新添加账户偏好设置项
mAccountCategory.removeAll();
//创建一个账户偏好项,配置标题、概要、并设置点击监听
//如果正在同步过程中则无法更改账户
Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));
@ -154,117 +162,150 @@ public class NotesPreferenceActivity extends PreferenceActivity {
mAccountCategory.addPreference(accountPref);
}
//用于初始化并设置同步按钮的状态和功能的私有方法
private void loadSyncButton() {
// 通过 ID 查找同步按钮,它是一个 Button 对象
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
// 通过 ID 查找表示上次同步时间的 TextView 对象
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state
//检查是否当前正在同步中,根据同步状态来设置按钮的文本和点击事件
if (GTaskSyncService.isSyncing()) {
// 如果正在同步,设置按钮文本为“取消同步”并添加取消同步的点击事件
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 当按钮被点击时,取消同步
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
} else {
// 如果不在同步,设置按钮文本为“立即同步”并添加启动同步的点击事件
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//当按钮被点击时,启动同步
GTaskSyncService.startSync(NotesPreferenceActivity.this);
}
});
}
// 设置按钮的可用性,如果没有设置同步账户名称则按钮不可用
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time
// 根据同步情况设置同步状态文本和其可见性
if (GTaskSyncService.isSyncing()) {
//如果正在同步,展示当前同步进度
lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
//// 如果不在同步,获取并展示上次同步的时间
long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) {
//如果有上次同步时间,格式化并展示这个时间
lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
DateFormat.format(getString(R.string.preferences_last_sync_time_format),
lastSyncTime)));
lastSyncTimeView.setVisibility(View.VISIBLE);
} else {
// 如果没有上次同步时间,则隐藏这个视图
lastSyncTimeView.setVisibility(View.GONE);
}
}
}
// 用来刷新界面的私有方法,可能是在操作后调用以更新用户界面状态
private void refreshUI() {
// 加载账户相关设置
loadAccountPreference();
// 重新加载并设置同步按钮的状态和功能
loadSyncButton();
}
// 显示选择账户的对话框的私有方法
private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 加载并设置对话框标题的布局
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
// 设置标题文本
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
// 设置子标题文本
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
// 对话框设置自定义标题布局
dialogBuilder.setCustomTitle(titleView);
// 设置了确定按钮,但没有事件,这可能意味着默认行为就是关闭对话框
dialogBuilder.setPositiveButton(null, null);
//获取当前设备上的 Google 账户列表
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) {
// 当用户选择一个账户时设置该账户为同步账户并刷新UI
setSyncAccount(itemMapping[which].toString());
dialog.dismiss();
refreshUI();
}
});
}
// 加载并设置“添加账户”的视图
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);
// 显示对话框
final AlertDialog dialog = dialogBuilder.show();
// 给“添加账户”视图添加点击事件,用来打开系统的添加账户页面
addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 设置标记表示已添加账户,并且开始添加账户的活动
mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls"
});
// 启动活动,请求码设置为-1可能表示这个启动是特殊的或者不需要处理返回结果
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),
@ -272,100 +313,138 @@ public class NotesPreferenceActivity extends PreferenceActivity {
};
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 当用户在列表中选择选项时,根据选择执行相应操作
if (which == 0) {
// 如果选择“更改账户”,显示选择账户的对话框
showSelectAccountAlertDialog();
} else if (which == 1) {
//如果选择“移除账户”移除同步账户并刷新UI
removeSyncAccount();
refreshUI();
}
// 没有必要处理取消选项,因为点击会自动关闭对话框
}
});
// 显示对话框
dialogBuilder.show();
}
// 获取设备中所有Google账户的数组
private Account[] getGoogleAccounts() {
// 通过AccountManager获取账户管理实例
AccountManager accountManager = AccountManager.get(this);
//调用getAccountsByType方法获取类型为"com.google"的所有账户即Google账户
return accountManager.getAccountsByType("com.google");
}
// 设定或改变同步账号
private void setSyncAccount(String account) {
// 如果当前同步账号不是用户选定的账号
if (!getSyncAccountName(this).equals(account)) {
// 获取SharedPreferences的实例来存储偏好设置
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
//创建一个SharedPreferences.Editor进行编辑
SharedPreferences.Editor editor = settings.edit();
//如果传入账号不是null将其存储到SharedPreferences
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
// 如果是null则存储空字符串""
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
// 将更改提交到SharedPreferences
editor.commit();
// clean up last sync time
// 将最后同步时间设置为0清空
setLastSyncTime(this, 0);
// clean up local gtask related info
// 在新线程中清空与同步相关的本地信息
new Thread(new Runnable() {
public void run() {
//创建ContentValues以存储需要更新的值
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
values.put(NoteColumns.GTASK_ID, ""); // 清空GTASK_ID
values.put(NoteColumns.SYNC_ID, 0); // 设置SYNC_ID为0
// 调用ContentResolver以更新数据库中的信息
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
// 显示提示信息,告知用户同步账号设置成功
Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();
}
}
// 移除同步账号
private void removeSyncAccount() {
// 获取SharedPreferences的实例来存储偏好设置
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
// 创建一个SharedPreferences.Editor进行编辑
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);
}
// 将更改提交到SharedPreferences
editor.commit();
// clean up local gtask related info
// 在新线程中清空与同步相关的本地信息
new Thread(new Runnable() {
public void run() {
// 创建ContentValues以存储需要更新的值
ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);
values.put(NoteColumns.GTASK_ID, ""); // 清空GTASK_ID
values.put(NoteColumns.SYNC_ID, 0); // 设置SYNC_ID为0
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
}
}).start();
}
// 获取当前设定的同步账号
public static String getSyncAccountName(Context context) {
// 获取SharedPreferences的实例来存储偏好设置
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的实例来存储偏好设置
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
// 创建一个SharedPreferences.Editor进行编辑
SharedPreferences.Editor editor = settings.edit();
// 将同步时间设置为传入的time
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
// 将更改提交到SharedPreferences
editor.commit();
}
// 获取最后同步时间
public static long getLastSyncTime(Context context) {
// 获取SharedPreferences的实例来存储偏好设置
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
// 返回存储的最后同步时间如果没有则返回0
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
}
// 内部类,广播接收器,用于接收同步状态变更的广播
private class GTaskReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 刷新界面显示
refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
// 找到同步状态的TextView并设置显示文本
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
@ -374,9 +453,12 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
}
// 处理选项菜单的项被选择的事件
public boolean onOptionsItemSelected(MenuItem item) {
// 根据菜单项的ID进行不同的操作
switch (item.getItemId()) {
case android.R.id.home:
// 如果是home项创建意图启动NotesListActivity
Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

@ -14,38 +14,52 @@ import android.widget.Toast;
import net.micode.notes.R;
//继承自 Activity 类,用于管理设置密码的页面行为
public class SettingPassword extends Activity {
//定义两个 EditText 成员变量用于获取用户输入的密码以及确认密码
EditText password;
EditText password_ack;
//定义 Button 成员变量用于用户完成密码输入时点击确认
Button acknowledge;
//Activity 的 onCreate()方法,创建 SettingPassword时被调用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置当前 Activity 使用的布局文件
setContentView(R.layout.activity_set_loginpassword);
//设置软键盘的行为
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
| WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
//关联至 EditText 组件(用于输入密码)
password = (EditText) findViewById(R.id.password);
//关联至 EditText 组件(用于确认密码)
password_ack = (EditText) findViewById(R.id.password_ack);
//关联 acknowledge 至Button 组件(确认按钮)
acknowledge = (Button)findViewById(R.id.acknowledge);
//设置确认按钮的监听器
acknowledge.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取用户输入的密码和确认密码
String text02 = password.getText().toString();
String text03 = password_ack.getText().toString();
//检查密码是否为空
if(text02.equals("")==true) {
Toast.makeText(SettingPassword.this, "密码不能为空", Toast.LENGTH_SHORT).show();
}
//检查输入的密码和确认密码是否相同
else if (text02.equals(text03) == false) {
Toast.makeText(SettingPassword.this, "密码错误,请重新输入密码 ", Toast.LENGTH_SHORT).show();
password_ack.setText("");
password_ack.setText(""); //不同则清空确认密码框
}
//若输入的密码和确认密码相同
else if (text02.equals(text03) == true){
SharedPreferences.Editor editor=getSharedPreferences("user management", MODE_PRIVATE).edit();
editor.putBoolean("user",true); //true 表示已经设置登录密码
editor.putString("password",text02);
editor.apply();
editor.putString("password",text02); //保存密码
editor.apply(); //应用更改
Log.d("RegisterLoginPassword","password is "+text02);
Toast.makeText(SettingPassword.this, "密码设置成功",
Toast.LENGTH_SHORT).show();
@ -57,8 +71,11 @@ public class SettingPassword extends Activity {
}
});
}
//重写 onBackPressed 方法,用于在按下返回键时的操作
@Override
public void onBackPressed() {
//创建跳转到便签列表界面的 Intent
Intent intent=new Intent(SettingPassword.this,NotesListActivity.class);
startActivity(intent);
finish();

@ -0,0 +1,127 @@
package net.micode.notes.ui;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import net.micode.notes.R;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
public class WeatherActivity extends Activity
{
private String responseData;
private TextView temperature; // 声明为成员变量
private TextView location;
private TextView wea;
private TextView date;
private TextView humidity;
private TextView win;
private TextView pressure;
private TextView pm25;
private TextView airlevel; // 声明为成员变量
OkHttpClient client = new OkHttpClient();//新建一个OkHttpClient对象
//api地址http://tianqiapi.com/index/doc?version=day
//注册后获取参数拼接在url上
private static String weatherUrl = "https://v1.yiketianqi.com/free/day?appid=94339557&version=v61&appsecret=9bIWWwDL&unescape=1";
@SuppressLint("StaticFieldLeak")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_weather);
temperature = this.findViewById(R.id.temperature_tv);
location = this.findViewById(R.id.location_tv);
wea= this.findViewById(R.id.weather_tv);
date= this.findViewById(R.id.date_tv);
humidity= this.findViewById(R.id.humidity_tv);
win= this.findViewById(R.id.win_tv);
pressure= this.findViewById(R.id.pressure_tv);
pm25= this.findViewById(R.id.pm2_5_tv);
airlevel= this.findViewById(R.id.airlevel_tv);
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(weatherUrl)
.build();
try {
Response response = client.newCall(request).execute();
String responseData = response.body().string();
Log.d("NetworkData", responseData);
return responseData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String responseData) {
// if (responseData != null) {
// Gson gson = new Gson();
// HashMap map = gson.fromJson(responseData, HashMap.class);
// temperature.setText("温度:"+(CharSequence) map.get("tem"));
// location.setText("城市:"+(CharSequence) map.get("city"));
// wea.setText("天气:"+map.get("wea").toString());
// date.setText("日期:"+map.get("date").toString());
// humidity.setText("湿度:"+map.get("humidity").toString());
// win.setText("风向:"+map.get("win").toString());
// pressure.setText("气压:"+map.get("pressure").toString());
// pm25.setText("PM2.5"+map.get("air_pm25").toString());
// airlevel.setText("空气等级:"+map.get("air_level").toString());
// }
if (responseData != null) {
Gson gson = new Gson();
HashMap map = gson.fromJson(responseData, HashMap.class);
// 在此之后,检查 map 中每个键对应的值是否为 null
if (map.get("tem") != null) {
temperature.setText("温度: " + map.get("tem").toString());
}
if (map.get("city") != null) {
location.setText("城市: " + map.get("city").toString());
}
// 对其他字段也做相同的检查
if (map.get("wea") != null) {
wea.setText("天气: " + map.get("wea").toString());
}
if (map.get("date") != null) {
date.setText("日期: " + map.get("date").toString());
}
if (map.get("humidity") != null) {
humidity.setText("湿度: " + map.get("humidity").toString());
}
if (map.get("win") != null) {
win.setText("风向: " + map.get("win").toString());
}
if (map.get("pressure") != null) {
pressure.setText("气压: " + map.get("pressure").toString());
}
if (map.get("air_pm25") != null) {
pm25.setText("PM2.5 " + map.get("air_pm25").toString());
}
if (map.get("air_level") != null) {
airlevel.setText("空气等级: " + map.get("air_level").toString());
}
}
}
}.execute();
}
}

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/location_tv"
android:layout_width="114dp"
android:layout_height="45dp"
android:text="武汉" />
<TextView
android:id="@+id/date_tv"
android:layout_width="114dp"
android:layout_height="46dp"
android:text="日期"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/temperature_tv"
android:layout_width="114dp"
android:layout_height="46dp"
android:text="0"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/weather_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="天气"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/humidity_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="湿度"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/win_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="风向"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/pressure_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="气压"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/pm2.5_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="pm2.5"
android:textColor="#FF6200EE" />
<TextView
android:id="@+id/airlevel_tv"
android:layout_width="115dp"
android:layout_height="61dp"
android:text="空气等级"
android:textColor="#FF6200EE" />
</LinearLayout>

@ -45,7 +45,8 @@
android:cacheColorHint="@null"
android:listSelector="@android:color/transparent"
android:divider="@null"
android:fadingEdge="@null" />
android:fadingEdge="@null"/>
</LinearLayout>
<Button

@ -36,4 +36,9 @@
<item
android:id="@+id/menu_search"
android:title="@string/menu_search"/>
<item
android:id="@+id/menu_weather"
android:title="查询天气"/>
</menu>

Loading…
Cancel
Save