Compare commits

..

6 Commits

@ -1,15 +1,17 @@
/*
* (c) 2010-2011, MiCode (www.micode.net)
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Apache License 2.0
* 使
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.gtask.remote;
@ -58,44 +60,36 @@ 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();
// Google Tasks 的URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
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;
// HTTP客户端
private DefaultHttpClient mHttpClient;
// 请求URL
private String mGetUrl;
private String mPostUrl;
// 客户端版本
private long mClientVersion;
// 登录状态
private boolean mLoggedin;
// 上次登录时间
private long mLastLoginTime;
// 动作ID
private int mActionId;
// 账号
private Account mAccount;
// 更新数组
private JSONArray mUpdateArray;
// 构造函数
private GTaskClient() {
mHttpClient = null;
mGetUrl = GTASK_GET_URL;
@ -108,7 +102,6 @@ public class GTaskClient {
mUpdateArray = null;
}
// 获取单例实例
public static synchronized GTaskClient getInstance() {
if (mInstance == null) {
mInstance = new GTaskClient();
@ -116,34 +109,34 @@ public class GTaskClient {
return mInstance;
}
// 登录方法
public boolean login(Activity activity) {
// 假设cookie在5分钟后过期需要重新登录
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
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))) {
.getSyncAccountName(activity))) {
mLoggedin = false;
}
if (mLoggedin) {
Log.d(TAG, "已经登录");
Log.d(TAG, "already logged in");
return true;
}
mLastLoginTime = System.currentTimeMillis();
String authToken = loginGoogleAccount(activity, false);
if (authToken == null) {
Log.e(TAG, "登录Google账户失败");
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/");
@ -158,7 +151,7 @@ public class GTaskClient {
}
}
// 尝试使用Google官方URL登录
// try to login with google official url
if (!mLoggedin) {
mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL;
@ -171,14 +164,13 @@ public class GTaskClient {
return true;
}
// 登录Google账户
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
String authToken;
AccountManager accountManager = AccountManager.get(activity);
Account[] accounts = accountManager.getAccountsByType("com.google");
if (accounts.length == 0) {
Log.e(TAG, "没有可用的Google账户");
Log.e(TAG, "there is no available google account");
return null;
}
@ -193,11 +185,11 @@ public class GTaskClient {
if (account != null) {
mAccount = account;
} else {
Log.e(TAG, "无法获取设置中相同名称的账户");
Log.e(TAG, "unable to get an account with the same name in the settings");
return null;
}
// 获取token
// get the token now
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
@ -206,7 +198,6 @@ public class GTaskClient {
if (invalidateToken) {
accountManager.invalidateAuthToken("com.google", authToken);
loginGoogleAccount(activity, false);
}
} catch (Exception e) {
Log.e(TAG, "get auth token failed");
@ -216,29 +207,27 @@ public class GTaskClient {
return authToken;
}
// 尝试登录GTask服务
private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) {
// 可能auth token已经过期现在让我们使token失效并重试
// maybe the auth token is out of date, now let's invalidate the
// token and try again
authToken = loginGoogleAccount(activity, true);
if (authToken == null) {
Log.e(TAG, "登录Google账户失败");
Log.e(TAG, "login google account failed");
return false;
}
if (!loginGtask(authToken)) {
Log.e(TAG, "登录GTask失败");
Log.e(TAG, "login gtask failed");
return false;
}
}
return true;
}
// 使用auth token登录GTask
private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; // 连接超时设定
int timeoutSocket = 15000; // 套接字超时设定
int timeoutConnection = 10000;
int timeoutSocket = 15000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
@ -247,14 +236,14 @@ public class GTaskClient {
mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// 登录GTask
// login gtask
try {
String loginUrl = mGetUrl + "?auth=" + authToken;
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// 获取cookie
// get the cookie now
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false;
for (Cookie cookie : cookies) {
@ -263,10 +252,10 @@ public class GTaskClient {
}
}
if (!hasAuthCookie) {
Log.w(TAG, "似乎没有auth cookie");
Log.w(TAG, "it seems that there is no auth cookie");
}
// 获取客户端版本
// get the client version
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -283,20 +272,18 @@ public class GTaskClient {
e.printStackTrace();
return false;
} catch (Exception e) {
// 捕获所有异常
Log.e(TAG, "httpget gtask_url失败");
// simply catch all exceptions
Log.e(TAG, "httpget gtask_url failed");
return false;
}
return true;
}
// 获取动作ID
private int getActionId() {
return mActionId++;
}
// 创建HttpPost对象
private HttpPost createHttpPost() {
HttpPost httpPost = new HttpPost(mPostUrl);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
@ -304,12 +291,11 @@ public class GTaskClient {
return httpPost;
}
// 获取响应内容
private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
contentEncoding = entity.getContentEncoding().getValue();
Log.d(TAG, "编码: " + contentEncoding);
Log.d(TAG, "encoding: " + contentEncoding);
}
InputStream input = entity.getContent();
@ -337,11 +323,10 @@ public class GTaskClient {
}
}
// 发送POST请求
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "请先登录");
throw new ActionFailureException("未登录");
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
HttpPost httpPost = createHttpPost();
@ -351,7 +336,7 @@ public class GTaskClient {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
// 执行POST请求
// execute the post
HttpResponse response = mHttpClient.execute(httpPost);
String jsString = getResponseContent(response.getEntity());
return new JSONObject(jsString);
@ -359,37 +344,36 @@ public class GTaskClient {
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest失败");
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("postRequest失败");
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("无法将响应内容转换为JSONObject");
throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("发送请求时发生错误");
throw new ActionFailureException("error occurs when posting request");
}
}
// 创建任务
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);
@ -398,25 +382,24 @@ public class GTaskClient {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("创建任务: 处理JSONObject失败");
throw new ActionFailureException("create task: handing jsonobject failed");
}
}
// 创建任务列表
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);
@ -425,38 +408,35 @@ public class GTaskClient {
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("创建任务列表: 处理JSONObject失败");
throw new ActionFailureException("create tasklist: handing jsonobject failed");
}
}
// 提交更新
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("提交更新: 处理JSONObject失败");
throw new ActionFailureException("commit update: handing jsonobject failed");
}
}
}
// 添加更新节点
public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) {
// 太多的更新项可能会导致错误设置最大数量为10项
// too many update items may result in an error
// set max to 10 items
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
@ -467,80 +447,80 @@ public class GTaskClient {
}
}
// 移动任务
public void moveTask(Task task, TaskList preParent, TaskList curParent) throws NetworkFailureException {
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.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
// 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) {
// 仅在任务列表内移动且不是第一个时设置prior_sibling_id
// put prioring_sibing_id only if moving within the tasklist and
// it is not the first one
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
action.put(GTaskStringUtils.GTASK_JSON_DEST_PARENT, curParent.getGid());
if (preParent != curParent) {
// 仅在不同任务列表之间移动时设置dest_list
// put the dest_list only if moving between tasklists
action.put(GTaskStringUtils.GTASK_JSON_DEST_LIST, curParent.getGid());
}
actionList.put(action);
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("移动任务: 处理JSONObject失败");
throw new ActionFailureException("move task: handing jsonobject failed");
}
}
// 删除节点
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()));
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("删除节点: 处理JSONObject失败");
throw new ActionFailureException("delete node: handing jsonobject failed");
}
}
// 获取任务列表
public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) {
Log.e(TAG, "请先登录");
throw new ActionFailureException("未登录");
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
try {
HttpGet httpGet = new HttpGet(mGetUrl);
HttpResponse response = mHttpClient.execute(httpGet);
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// 获取任务列表
// get the task list
String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup(";
String jsEnd = ")}</script>";
@ -555,19 +535,18 @@ public class GTaskClient {
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("获取任务列表: HTTP GET失败");
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (IOException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new NetworkFailureException("获取任务列表: HTTP GET失败");
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
e.printStackTrace();
throw new ActionFailureException("获取任务列表: 处理JSONObject失败");
throw new ActionFailureException("get task lists: handing jasonobject failed");
}
}
// 获取特定任务列表
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate();
try {
@ -575,33 +554,31 @@ public class GTaskClient {
JSONArray actionList = new JSONArray();
JSONObject action = new JSONObject();
// 动作列表
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
// 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);
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("获取特定任务列表: 处理JSONObject失败");
throw new ActionFailureException("get task list: handing jsonobject failed");
}
}
// 获取同步账户
public Account getSyncAccount() {
return mAccount;
}
// 重置更新数组
public void resetUpdateArray() {
mUpdateArray = null;
}

@ -49,70 +49,56 @@ import java.util.Map;
public class GTaskManager {
// 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;
// 单例模式的GTaskManager实例
private static GTaskManager mInstance = null;
// 活动对象
private Activity mActivity;
// 上下文对象
private Context mContext;
// 内容解析器
private ContentResolver mContentResolver;
// 同步标志
private boolean mSyncing;
// 取消标志
private boolean mCancelled;
// Google任务列表哈希映射
private HashMap<String, TaskList> mGTaskListHashMap;
// Google任务哈希映射
private HashMap<String, Node> mGTaskHashMap;
// 元数据哈希映射
private HashMap<String, MetaData> mMetaHashMap;
// 元数据列表
private TaskList mMetaList;
// 本地删除ID映射集合
private HashSet<Long> mLocalDeleteIdMap;
// Google ID到笔记ID映射
private HashMap<String, Long> mGidToNid;
// 笔记ID到Google ID映射
private HashMap<Long, String> mNidToGid;
// 私有构造函数,初始化各个字段
private GTaskManager() {
mSyncing = false;
mCancelled = false;
mGTaskListHashMap = new HashMap<>();
mGTaskHashMap = new HashMap<>();
mMetaHashMap = new HashMap<>();
mGTaskListHashMap = new HashMap<String, TaskList>();
mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>();
mMetaList = null;
mLocalDeleteIdMap = new HashSet<>();
mGidToNid = new HashMap<>();
mNidToGid = new HashMap<>();
mLocalDeleteIdMap = new HashSet<Long>();
mGidToNid = new HashMap<String, Long>();
mNidToGid = new HashMap<Long, String>();
}
// 获取单例
public static synchronized GTaskManager getInstance() {
if (mInstance == null) {
mInstance = new GTaskManager();
@ -120,16 +106,14 @@ public class GTaskManager {
return mInstance;
}
// 设置活动上下文
public synchronized void setActivityContext(Activity activity) {
// 用于获取authtoken
// used for getting authtoken
mActivity = activity;
}
// 同步任务
public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) {
Log.d(TAG, "同步进行中");
Log.d(TAG, "Sync is in progress");
return STATE_SYNC_IN_PROGRESS;
}
mContext = context;
@ -147,18 +131,18 @@ public class GTaskManager {
GTaskClient client = GTaskClient.getInstance();
client.resetUpdateArray();
// 登录Google任务
// login google task
if (!mCancelled) {
if (!client.login(mActivity)) {
throw new NetworkFailureException("登录Google任务失败");
throw new NetworkFailureException("login google task failed");
}
}
// 从Google获取任务列表
// get the task list from google
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_init_list));
initGTaskList();
// 进行内容同步
// do content sync work
asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing));
syncContent();
} catch (NetworkFailureException e) {
@ -184,7 +168,6 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
}
// 初始化任务列表
private void initGTaskList() throws NetworkFailureException {
if (mCancelled)
return;
@ -192,22 +175,22 @@ public class GTaskManager {
try {
JSONArray jsTaskLists = client.getTaskLists();
// 先初始化meta列表
// init meta list first
mMetaList = null;
for (int i = 0; i < jsTaskLists.length(); i++) {
JSONObject object = jsTaskLists.getJSONObject(i);
String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);
String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);
// 处理meta列表
if (name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
if (name
.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {
mMetaList = new TaskList();
mMetaList.setContentByRemoteJSON(object);
// 加载meta数据
// load meta data
JSONArray jsMetas = client.getTaskList(gid);
for (int j = 0; j < jsMetas.length(); j++) {
object = jsMetas.getJSONObject(j);
object = (JSONObject) jsMetas.getJSONObject(j);
MetaData metaData = new MetaData();
metaData.setContentByRemoteJSON(object);
if (metaData.isWorthSaving()) {
@ -220,7 +203,7 @@ public class GTaskManager {
}
}
//如果不存在,创建元列表
// create meta list if not existed
if (mMetaList == null) {
mMetaList = new TaskList();
mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX
@ -228,7 +211,7 @@ public class GTaskManager {
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);
@ -242,7 +225,7 @@ public class GTaskManager {
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);
@ -264,21 +247,19 @@ public class GTaskManager {
}
}
// 同步内容
private void syncContent() throws NetworkFailureException {
int syncType;
Cursor c = null;
String gid;
Node node;
// 清空本地删除ID集合
mLocalDeleteIdMap.clear();
if (mCancelled) {
return;
}
// 处理本地删除的笔记
// for local deleted note
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type<>? AND parent_id=?)", new String[] {
@ -296,7 +277,7 @@ public class GTaskManager {
mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));
}
} else {
Log.w(TAG, "查询垃圾文件夹失败");
Log.w(TAG, "failed to query trash folder");
}
} finally {
if (c != null) {
@ -305,10 +286,10 @@ public class GTaskManager {
}
}
// 首先同步文件夹
// 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[] {
@ -325,17 +306,17 @@ public class GTaskManager {
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, "查询数据库中现有的笔记失败");
Log.w(TAG, "failed to query existing note in database");
}
} finally {
@ -345,7 +326,7 @@ public class GTaskManager {
}
}
// 处理剩余项
// go through remaining items
Iterator<Map.Entry<String, Node>> iter = mGTaskHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Node> entry = iter.next();
@ -353,15 +334,16 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);
}
// mCancelled可以被另一个线程设置所以需要逐一检查
// 清空本地删除表
// mCancelled can be set by another thread, so we neet to check one by
// one
// clear local delete table
if (!mCancelled) {
if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {
throw new ActionFailureException("批量删除本地删除的笔记失败");
throw new ActionFailureException("failed to batch-delete local deleted notes");
}
}
// 刷新本地同步ID
// refresh local sync id
if (!mCancelled) {
GTaskClient.getInstance().commitUpdate();
refreshLocalSyncId();
@ -369,7 +351,6 @@ public class GTaskManager {
}
// 同步文件夹
private void syncFolder() throws NetworkFailureException {
Cursor c = null;
String gid;
@ -380,7 +361,7 @@ public class GTaskManager {
return;
}
// 处理根文件夹
// for root folder
try {
c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);
@ -392,7 +373,7 @@ public class GTaskManager {
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);
@ -400,7 +381,7 @@ public class GTaskManager {
doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);
}
} else {
Log.w(TAG, "查询根文件夹失败");
Log.w(TAG, "failed to query root folder");
}
} finally {
if (c != null) {
@ -409,11 +390,11 @@ public class GTaskManager {
}
}
// 处理通话记录文件夹
// 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)
String.valueOf(Notes.ID_CALL_RECORD_FOLDER)
}, null);
if (c != null) {
if (c.moveToNext()) {
@ -423,7 +404,8 @@ public class GTaskManager {
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))
@ -433,7 +415,7 @@ public class GTaskManager {
}
}
} else {
Log.w(TAG, "查询通话记录文件夹失败");
Log.w(TAG, "failed to query call note folder");
}
} finally {
if (c != null) {
@ -442,7 +424,7 @@ public class GTaskManager {
}
}
// 处理本地存在的文件夹
// for local existing folders
try {
c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,
"(type=? AND parent_id<>?)", new String[] {
@ -459,17 +441,17 @@ public class GTaskManager {
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, "查询现有文件夹失败");
Log.w(TAG, "failed to query existing folder");
}
} finally {
if (c != null) {
@ -478,7 +460,7 @@ public class GTaskManager {
}
}
// 处理远程新增的文件夹
// for remote add folders
Iterator<Map.Entry<String, TaskList>> iter = mGTaskListHashMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, TaskList> entry = iter.next();
@ -528,14 +510,15 @@ public class GTaskManager {
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("未知的同步操作类型");
throw new ActionFailureException("unkown sync action type");
}
}
@ -566,7 +549,7 @@ public class GTaskManager {
if (note.has(NoteColumns.ID)) {
long id = note.getLong(NoteColumns.ID);
if (DataUtils.existInNoteDatabase(mContentResolver, id)) {
// ID不可用必须创建一个新的
// the id is not available, have to create a new one
note.remove(NoteColumns.ID);
}
}
@ -579,7 +562,8 @@ public class GTaskManager {
if (data.has(DataColumns.ID)) {
long dataId = data.getLong(DataColumns.ID);
if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {
// data ID不可用必须创建一个新的
// the data id is not available, have to create
// a new one
data.remove(DataColumns.ID);
}
}
@ -594,21 +578,21 @@ public class GTaskManager {
Long parentId = mGidToNid.get(((Task) node).getParent().getGid());
if (parentId == null) {
Log.e(TAG, "在本地找不到任务的父ID");
throw new ActionFailureException("无法添加本地节点");
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);
// 更新GID-NID映射
// update gid-nid mapping
mGidToNid.put(node.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), node.getGid());
// 更新meta信息
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
}
@ -618,24 +602,23 @@ public class GTaskManager {
}
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, "在本地找不到任务的父ID");
throw new ActionFailureException("无法更新本地节点");
Log.e(TAG, "cannot find task's parent id locally");
throw new ActionFailureException("cannot update local node");
}
sqlNote.setParentId(parentId.longValue());
sqlNote.commit(true);
// 更新meta信息
// update meta info
updateRemoteMeta(node.getGid(), sqlNote);
}
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) {
return;
@ -644,27 +627,27 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
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, "找不到任务的父任务列表");
throw new ActionFailureException("无法添加远程任务");
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot add remote task");
}
mGTaskListHashMap.get(parentGid).addChildTask(task);
GTaskClient.getInstance().createTask(task);
n = (Node) task;
// 添加元数据
// 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;
@ -688,7 +671,7 @@ public class GTaskManager {
}
}
// 没有匹配的,现在可以添加
// no match we can add now
if (tasklist == null) {
tasklist = new TaskList();
tasklist.setContentByLocalJSON(sqlNote.getContent());
@ -698,13 +681,13 @@ public class GTaskManager {
n = (Node) tasklist;
}
// 更新本地笔记
// update local note
sqlNote.setGtaskId(n.getGid());
sqlNote.commit(false);
sqlNote.resetLocalModified();
sqlNote.commit(true);
// gid-id 映射
// gid-id mapping
mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid());
}
@ -716,22 +699,22 @@ public class GTaskManager {
SqlNote sqlNote = new SqlNote(mContext, c);
// 远程更新
// update remotely
node.setContentByLocalJSON(sqlNote.getContent());
GTaskClient.getInstance().addUpdateNode(node);
// 更新元数据
// update meta
updateRemoteMeta(node.getGid(), sqlNote);
// 如果需要,移动任务
// move task if necessary
if (sqlNote.isNoteType()) {
Task task = (Task) node;
TaskList preParentList = task.getParent();
String curParentGid = mNidToGid.get(sqlNote.getParentId());
if (curParentGid == null) {
Log.e(TAG, "找不到任务的父任务列表");
throw new ActionFailureException("无法更新远程任务");
Log.e(TAG, "cannot find task's parent tasklist");
throw new ActionFailureException("cannot update remote task");
}
TaskList curParentList = mGTaskListHashMap.get(curParentGid);
@ -742,7 +725,7 @@ public class GTaskManager {
}
}
// 清除本地修改标志
// clear local modified flag
sqlNote.resetLocalModified();
sqlNote.commit(true);
}
@ -768,7 +751,7 @@ public class GTaskManager {
return;
}
// 获取最新的gtask列表
// get the latest gtask list
mGTaskHashMap.clear();
mGTaskListHashMap.clear();
mMetaHashMap.clear();
@ -791,13 +774,13 @@ public class GTaskManager {
mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,
c.getLong(SqlNote.ID_COLUMN)), values, null, null);
} else {
Log.e(TAG, "有些数据缺失");
Log.e(TAG, "something is missed");
throw new ActionFailureException(
"同步后某些本地项目没有gid");
"some local items don't have gid after sync");
}
}
} else {
Log.w(TAG, "查询本地笔记以刷新同步ID失败");
Log.w(TAG, "failed to query local note to refresh sync id");
}
} finally {
if (c != null) {

@ -24,57 +24,38 @@ 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;
// GTask服务广播名称
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();
@ -83,7 +64,6 @@ public class GTaskSyncService extends Service {
@Override
public void onCreate() {
// 清空同步任务
mSyncTask = null;
}
@ -93,11 +73,9 @@ public class GTaskSyncService extends Service {
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:
@ -111,58 +89,39 @@ public class GTaskSyncService extends Service {
@Override
public void onLowMemory() {
if (mSyncTask != null) {
// 低内存时取消同步任务
mSyncTask.cancelSync();
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
// 发送广播
public void sendBroadcast(String msg) {
// 更新同步进度消息
mSyncProgress = msg;
// 创建意图
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
// 添加是否正在同步的信息
intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
// 添加同步进度消息
intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
// 发送广播
sendBroadcast(intent);
}
// 启动同步服务
public static void startSync(Activity activity) {
// 设置活动上下文
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) {
// 创建意图
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;
}

@ -35,15 +35,14 @@ import java.util.ArrayList;
public class Note {
private ContentValues mNoteDiffValues; // 记录笔记的差异值
private NoteData mNoteData; // 笔记数据
private static final String TAG = "Note"; // 日志标签
private ContentValues mNoteDiffValues;
private NoteData mNoteData;
private static final String TAG = "Note";
/**
* ID
* 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);
@ -57,11 +56,11 @@ public class Note {
try {
noteId = Long.valueOf(uri.getPathSegments().get(1));
} catch (NumberFormatException e) {
Log.e(TAG, "获取笔记ID错误" + e.toString());
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
if (noteId == -1) {
throw new IllegalStateException("错误的笔记ID" + noteId);
throw new IllegalStateException("Wrong note id:" + noteId);
}
return noteId;
}
@ -78,55 +77,48 @@ public class Note {
}
public void setTextData(String key, String value) {
// 设置文本数据
mNoteData.setTextData(key, value);
}
public void setTextDataId(long id) {
// 设置文本数据的ID
mNoteData.setTextDataId(id);
}
public long getTextDataId() {
// 获取文本数据的ID
return mNoteData.mTextDataId;
}
public void setCallDataId(long id) {
// 设置通话数据的ID
mNoteData.setCallDataId(id);
}
public void setCallData(String key, String value) {
// 设置通话数据
mNoteData.setCallData(key, value);
}
public boolean isLocalModified() {
// 检查本地是否有修改
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
// 如果笔记ID无效抛出异常
throw new IllegalArgumentException("错误的笔记ID" + noteId);
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
if (!isLocalModified()) {
// 如果本地没有修改,则同步成功
return true;
}
/**
* {@link NoteColumns#LOCAL_MODIFIED}
* {@link NoteColumns#MODIFIED_DATE}使
* 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, "更新笔记错误,不应该发生");
// 不要返回,继续执行
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
}
mNoteDiffValues.clear();
@ -139,18 +131,17 @@ public class Note {
}
private class NoteData {
private long mTextDataId; // 文本数据ID
private long mTextDataId;
private ContentValues mTextDataValues; // 文本数据值
private ContentValues mTextDataValues;
private long mCallDataId; // 通话数据ID
private long mCallDataId;
private ContentValues mCallDataValues; // 通话数据值
private ContentValues mCallDataValues;
private static final String TAG = "NoteData"; // 日志标签
private static final String TAG = "NoteData";
public NoteData() {
// 初始化NoteData对象创建文本数据和通话数据的ContentValues对象并将ID初始化为0
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
mTextDataId = 0;
@ -158,126 +149,103 @@ public class Note {
}
boolean isLocalModified() {
// 检查本地数据是否被修改
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
void setTextDataId(long id) {
// 设置文本数据IDID必须大于0
if(id <= 0) {
throw new IllegalArgumentException("文本数据ID应大于0");
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
}
void setCallDataId(long id) {
// 设置通话数据IDID必须大于0
if (id <= 0) {
throw new IllegalArgumentException("通话数据ID应大于0");
throw new IllegalArgumentException("Call data id should larger than 0");
}
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());
}
Uri pushIntoContentResolver(Context context, long noteId) {
/**
*
* Check for safety
*/
if (noteId <= 0) {
// 检查笔记ID是否合法若不合法则抛出异常
throw new IllegalArgumentException("错误的笔记ID" + noteId);
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
// 创建一个操作列表用于批量操作数据库
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if (mTextDataValues.size() > 0) {
// 若文本数据存在修改将笔记ID添加到文本数据中
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataId == 0) {
// 若文本数据ID为0表示需要插入新数据
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mTextDataValues);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
// 尝试从返回的URI中获取新插入的数据ID并设置为文本数据ID
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
// 若获取ID失败记录日志并清空文本数据值返回null
Log.e(TAG, "插入新文本数据失败笔记ID" + noteId);
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}
} else {
// 若文本数据ID不为0表示需要更新已有数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
// 清空文本数据值
mTextDataValues.clear();
}
if (mCallDataValues.size() > 0) {
// 若通话数据存在修改将笔记ID添加到通话数据中
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
// 若通话数据ID为0表示需要插入新数据
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, mCallDataValues);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
try {
// 尝试从返回的URI中获取新插入的数据ID并设置为通话数据ID
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
// 若获取ID失败记录日志并清空通话数据值返回null
Log.e(TAG, "插入新通话数据失败笔记ID" + noteId);
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
}
} else {
// 若通话数据ID不为0表示需要更新已有数据
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}
// 清空通话数据值
mCallDataValues.clear();
}
if (operationList.size() > 0) {
try {
// 批量执行数据库操作
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
// 返回操作结果若无结果或结果为空则返回null
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
// 捕获远程异常记录日志并返回null
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
// 捕获操作应用异常记录日志并返回null
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}
}
return null;
}

@ -33,82 +33,75 @@ import net.micode.notes.tool.ResourceParser.NoteBgResources;
public class WorkingNote {
// 工作笔记的笔记对象
// Note for the working note
private Note mNote;
// 笔记ID
// Note Id
private long mNoteId;
// 笔记内容
// Note content
private String mContent;
// 笔记模式
// 笔记的模式
// Note mode
private int mMode;
// 提醒日期
private long mAlertDate;
// 修改日期
private long mModifiedDate;
// 背景颜色ID
private int mBgColorId;
// 小部件ID
private int mWidgetId;
// 小部件类型
private int mWidgetType;
// 文件夹ID
private long mFolderId;
// 应用上下文
private Context mContext;
// 日志标签
private static final String TAG = "WorkingNote";
// 笔记是否已被删除的标志
private boolean mIsDeleted;
// 笔记设置变化监听器
private NoteSettingChangedListener mNoteSettingStatusListener;
// 数据查询的投影(列名)
public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID, // 数据ID
DataColumns.CONTENT, // 数据内容
DataColumns.MIME_TYPE, // 数据MIME类型
DataColumns.DATA1, // 数据1
DataColumns.DATA2, // 数据2
DataColumns.DATA3, // 数据3
DataColumns.DATA4, // 数据4
DataColumns.ID,
DataColumns.CONTENT,
DataColumns.MIME_TYPE,
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
// 笔记查询的投影(列名)
public static final String[] NOTE_PROJECTION = new String[] {
NoteColumns.PARENT_ID, // 父ID
NoteColumns.ALERTED_DATE, // 提醒日期
NoteColumns.BG_COLOR_ID, // 背景颜色ID
NoteColumns.WIDGET_ID, // 小部件ID
NoteColumns.WIDGET_TYPE, // 小部件类型
NoteColumns.MODIFIED_DATE // 修改日期
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; // 数据ID列索引
private static final int DATA_CONTENT_COLUMN = 1; // 数据内容列索引
private static final int DATA_MIME_TYPE_COLUMN = 2; // 数据MIME类型列索引
private static final int DATA_MODE_COLUMN = 3; // 数据模式列索引
// 笔记表中各列的索引
private static final int NOTE_PARENT_ID_COLUMN = 0; // 父ID列索引
private static final int NOTE_ALERTED_DATE_COLUMN = 1; // 提醒日期列索引
private static final int NOTE_BG_COLOR_ID_COLUMN = 2; // 背景颜色ID列索引
private static final int NOTE_WIDGET_ID_COLUMN = 3; // 小部件ID列索引
private static final int NOTE_WIDGET_TYPE_COLUMN = 4; // 小部件类型列索引
private static final int NOTE_MODIFIED_DATE_COLUMN = 5; // 修改日期列索引
// 新笔记构造函数
private static final int DATA_ID_COLUMN = 0;
private static final int DATA_CONTENT_COLUMN = 1;
private static final int DATA_MIME_TYPE_COLUMN = 2;
private static final int DATA_MODE_COLUMN = 3;
private static final int NOTE_PARENT_ID_COLUMN = 0;
private static final int NOTE_ALERTED_DATE_COLUMN = 1;
private static final int NOTE_BG_COLOR_ID_COLUMN = 2;
private static final int NOTE_WIDGET_ID_COLUMN = 3;
private static final int NOTE_WIDGET_TYPE_COLUMN = 4;
private static final int NOTE_MODIFIED_DATE_COLUMN = 5;
// New note construct
private WorkingNote(Context context, long folderId) {
mContext = context;
mAlertDate = 0;
@ -121,7 +114,7 @@ public class WorkingNote {
mWidgetType = Notes.TYPE_WIDGET_INVALIDE;
}
// 已存在笔记构造函数
// Existing note construct
private WorkingNote(Context context, long noteId, long folderId) {
mContext = context;
mNoteId = noteId;
@ -131,94 +124,83 @@ public class WorkingNote {
loadNote();
}
// 加载笔记
private void loadNote() {
// 查询指定笔记ID的数据
Cursor cursor = mContext.getContentResolver().query(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null,
null, null);
// 检查查询结果是否为空
if (cursor != null) {
// 如果查询到数据,加载笔记信息
if (cursor.moveToFirst()) {
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN); // 获取父文件夹ID
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN); // 获取背景颜色ID
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN); // 获取小部件ID
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN); // 获取小部件类型
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN); // 获取提醒日期
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN); // 获取修改日期
mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);
mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);
mWidgetId = cursor.getInt(NOTE_WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(NOTE_WIDGET_TYPE_COLUMN);
mAlertDate = cursor.getLong(NOTE_ALERTED_DATE_COLUMN);
mModifiedDate = cursor.getLong(NOTE_MODIFIED_DATE_COLUMN);
}
cursor.close();
} else {
// 如果查询结果为空,记录错误日志并抛出异常
Log.e(TAG, "没有ID为" + mNoteId + "的笔记");
throw new IllegalArgumentException("找不到ID为 " + mNoteId + " 的笔记");
Log.e(TAG, "No note with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note with id " + mNoteId);
}
loadNoteData(); // 加载笔记的具体数据
loadNoteData();
}
// 加载笔记的具体数据
private void loadNoteData() {
// 查询笔记的具体数据
Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION,
DataColumns.NOTE_ID + "=?", new String[] {
String.valueOf(mNoteId)
String.valueOf(mNoteId)
}, null);
// 检查查询结果是否为空
if (cursor != null) {
// 如果查询到数据,逐行加载
if (cursor.moveToFirst()) {
do {
String type = cursor.getString(DATA_MIME_TYPE_COLUMN); // 获取数据类型
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)); // 设置文本数据ID
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)); // 设置通话数据ID
mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));
} else {
Log.d(TAG, "笔记类型错误,类型:" + type); // 记录错误的笔记类型
Log.d(TAG, "Wrong note type with type:" + type);
}
} while (cursor.moveToNext());
}
cursor.close();
} else {
// 如果查询结果为空,记录错误日志并抛出异常
Log.e(TAG, "没有ID为" + mNoteId + "的数据");
throw new IllegalArgumentException("找不到ID为 " + mNoteId + " 的笔记数据");
Log.e(TAG, "No data with id:" + mNoteId);
throw new IllegalArgumentException("Unable to find note's data with id " + mNoteId);
}
}
// 创建一个空的笔记
public static WorkingNote createEmptyNote(Context context, long folderId, int widgetId,
int widgetType, int defaultBgColorId) {
int widgetType, int defaultBgColorId) {
WorkingNote note = new WorkingNote(context, folderId);
note.setBgColorId(defaultBgColorId); // 设置背景颜色ID
note.setWidgetId(widgetId); // 设置小部件ID
note.setWidgetType(widgetType); // 设置小部件类型
note.setBgColorId(defaultBgColorId);
note.setWidgetId(widgetId);
note.setWidgetType(widgetType);
return note;
}
// 加载指定ID的笔记
public static WorkingNote load(Context context, long id) {
return new WorkingNote(context, id, 0);
}
// 同步笔记
public synchronized boolean saveNote() {
if (isWorthSaving()) { // 检查笔记是否值得保存
if (!existInDatabase()) { // 检查笔记是否存在于数据库中
if (isWorthSaving()) {
if (!existInDatabase()) {
if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {
Log.e(TAG, "创建新笔记失败ID为" + mNoteId);
Log.e(TAG, "Create new note fail with id:" + mNoteId);
return false;
}
}
mNote.syncNote(mContext, mNoteId); // 同步笔记
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) {
@ -230,12 +212,10 @@ public class WorkingNote {
}
}
// 检查笔记是否存在于数据库中
public boolean existInDatabase() {
return mNoteId > 0;
}
// 检查笔记是否值得保存
private boolean isWorthSaving() {
if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))
|| (existInDatabase() && !mNote.isLocalModified())) {
@ -245,14 +225,10 @@ public class WorkingNote {
}
}
// 设置笔记设置变化监听器
public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {
mNoteSettingStatusListener = l;
}
// 设置提醒日期
public void setAlertDate(long date, boolean set) {
if (date != mAlertDate) {
mAlertDate = date;
@ -263,16 +239,14 @@ public class WorkingNote {
}
}
// 标记为已删除
public void markDeleted(boolean mark) {
mIsDeleted = mark;
if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {
mNoteSettingStatusListener.onWidgetChanged();
mNoteSettingStatusListener.onWidgetChanged();
}
}
// 设置背景颜色ID
public void setBgColorId(int id) {
if (id != mBgColorId) {
mBgColorId = id;
@ -283,7 +257,6 @@ public class WorkingNote {
}
}
// 设置检查列表模式
public void setCheckListMode(int mode) {
if (mMode != mode) {
if (mNoteSettingStatusListener != null) {
@ -294,7 +267,6 @@ public class WorkingNote {
}
}
// 设置小部件类型
public void setWidgetType(int type) {
if (type != mWidgetType) {
mWidgetType = type;
@ -302,7 +274,6 @@ public class WorkingNote {
}
}
// 设置小部件ID
public void setWidgetId(int id) {
if (id != mWidgetId) {
mWidgetId = id;
@ -310,7 +281,6 @@ public class WorkingNote {
}
}
// 设置工作文本
public void setWorkingText(String text) {
if (!TextUtils.equals(mContent, text)) {
mContent = text;
@ -318,94 +288,80 @@ public class WorkingNote {
}
}
// 转换为通话笔记
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);
}
// 获取内容
public String getContent() {
return mContent;
}
// 获取提醒日期
public long getAlertDate() {
return mAlertDate;
}
// 获取修改日期
public long getModifiedDate() {
return mModifiedDate;
}
// 获取背景颜色资源ID
public int getBgColorResId() {
return NoteBgResources.getNoteBgResource(mBgColorId);
}
// 获取背景颜色ID
public int getBgColorId() {
return mBgColorId;
}
// 获取标题背景资源ID
public int getTitleBgResId() {
return NoteBgResources.getNoteTitleBgResource(mBgColorId);
}
// 获取检查列表模式
public int getCheckListMode() {
return mMode;
}
// 获取笔记ID
public long getNoteId() {
return mNoteId;
}
// 获取文件夹ID
public long getFolderId() {
return mFolderId;
}
// 获取小部件ID
public int getWidgetId() {
return mWidgetId;
}
// 获取小部件类型
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();
/**
*
* @param oldMode
* @param newMode
* 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);
}

@ -35,9 +35,10 @@ 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) {
@ -48,43 +49,38 @@ 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;
// 备份或还原成功
public static final int STATE_SUCCESS = 4;
// Backup or restore success
public static final int STATE_SUCCESS = 4;
private TextExport mTextExport; // 声明一个私有的TextExport对象mTextExport。
private TextExport mTextExport;
// 构造方法接受一个Context参数用于初始化mTextExport对象。
private BackupUtils(Context context) {
mTextExport = new TextExport(context);
}
// 静态方法,检查外部存储是否可用。
private static boolean externalStorageAvailable() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 公共方法调用mTextExport对象的exportToText方法返回int值。
public int exportToText() {
return mTextExport.exportToText();
}
// 公共方法,获取导出的文本文件的文件名。
public String getExportedTextFileName() {
return mTextExport.mFileName;
}
// 公共方法,获取导出的文本文件的目录。
public String getExportedTextFileDir() {
return mTextExport.mFileDirectory;
}
@ -141,23 +137,23 @@ 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
folderId
}, null);
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());
@ -167,12 +163,12 @@ 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,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
noteId
}, null);
if (dataCursor != null) {
@ -180,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);
@ -189,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));
@ -209,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
@ -220,20 +216,20 @@ public class BackupUtils {
}
/**
* 便
* Note will be exported as text which is user readable
*/
public int exportToText() {
if (!externalStorageAvailable()) {
Log.d(TAG, "存储设备未挂载");
Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED;
}
PrintStream ps = getExportToTextPrintStream();
if (ps == null) {
Log.e(TAG, "获取打印流错误");
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,
@ -244,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);
@ -261,7 +257,7 @@ public class BackupUtils {
folderCursor.close();
}
//在根目录下导出笔记
// Export notes in root's folder
Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION,
@ -287,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,
@ -314,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();

@ -36,125 +36,86 @@ import java.util.HashSet;
public class DataUtils {
// 定义一个用于日志的标签常量
public static final String TAG = "DataUtils";
// 批量删除笔记的方法接受ContentResolver对象和一组笔记的ID集合
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {
// 检查ID集合是否为null如果为null记录日志并返回true
if (ids == null) {
Log.d(TAG, "the ids is null");
return true;
}
// 检查ID集合是否为空如果为空记录日志并返回true
if(ids.size() == 0) {
if (ids.size() == 0) {
Log.d(TAG, "no id is in the hashset");
return true;
}
// 创建一个ContentProviderOperation列表用于存储删除操作
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
// 遍历ID集合为每个ID创建一个删除操作
for (long id : ids) {
// 如果ID是根文件夹ID记录错误日志并跳过删除操作
if(id == Notes.ID_ROOT_FOLDER) {
Log.e(TAG, "Don't delete system folder root");
continue;
}
// 创建删除操作的Builder对象
ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 将构建好的删除操作添加到操作列表中
operationList.add(builder.build());
}
try {
// 执行批量操作,应用删除操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查删除结果如果结果为空、长度为0或第一个结果为null记录日志并返回false
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
// 删除成功返回true
return true;
} catch (RemoteException e) {
// 捕获RemoteException记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
// 捕获OperationApplicationException记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
// 如果发生异常返回false
return false;
}
// 将笔记移动到指定文件夹
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
// 创建一个ContentValues对象用于存储更新的值
ContentValues values = new ContentValues();
// 将目标文件夹ID设置为新的父文件夹ID
values.put(NoteColumns.PARENT_ID, desFolderId);
// 将原始父文件夹ID设置为源文件夹ID
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
// 将LOCAL_MODIFIED标记设置为1表示已修改
values.put(NoteColumns.LOCAL_MODIFIED, 1);
// 更新数据库中的笔记记录
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}
// 批量将笔记移动到指定文件夹
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, long folderId) {
// 检查ID集合是否为空如果为空记录日志并返回true
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>();
// 遍历ID集合为每个ID创建一个更新操作
for (long id : ids) {
// 创建更新操作的Builder对象
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));
// 设置更新的值将目标文件夹ID设置为新的父文件夹ID将LOCAL_MODIFIED标记设置为1
builder.withValue(NoteColumns.PARENT_ID, folderId);
builder.withValue(NoteColumns.LOCAL_MODIFIED, 1);
// 将更新操作添加到操作列表中
operationList.add(builder.build());
}
try {
// 应用批量更新操作
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
// 检查更新结果如果结果为空、长度为0或第一个结果为null记录日志并返回false
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
}
// 更新成功返回true
return true;
} catch (RemoteException e) {
// 捕获RemoteException记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} catch (OperationApplicationException e) {
// 捕获OperationApplicationException记录错误日志
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
}
// 更新失败返回false
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,
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)},
@ -164,24 +125,18 @@ public class DataUtils {
if(cursor != null) {
if(cursor.moveToFirst()) {
try {
// 从查询结果中获取用户文件夹的数量
count = cursor.getInt(0);
} catch (IndexOutOfBoundsException e) {
// 捕获IndexOutOfBoundsException异常记录错误日志
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,
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER,
@ -193,16 +148,12 @@ public class DataUtils {
if (cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
// 返回笔记是否在数据库中可见
return exist;
}
// 检查笔记是否存在于数据库中
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
// 查询笔记数据库,检查笔记是否存在于数据库中
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
null, null, null, null);
@ -211,16 +162,12 @@ public class DataUtils {
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);
@ -229,37 +176,28 @@ public class DataUtils {
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 + "=?",
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
boolean exist = false;
if(cursor != null) {
if(cursor.getCount() > 0) {
exist = true;
}
// 关闭游标
cursor.close();
}
// 返回可见文件夹名称是否存在于数据库中
return exist;
}
// 获取文件夹中所有笔记的小部件信息集合
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
// 查询指定文件夹中所有笔记的小部件信息
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { NoteColumns.WIDGET_ID, NoteColumns.WIDGET_TYPE },
NoteColumns.PARENT_ID + "=?",
@ -269,31 +207,24 @@ public class DataUtils {
HashSet<AppWidgetAttribute> set = null;
if (c != null) {
if (c.moveToFirst()) {
// 如果查询结果不为空创建一个HashSet对象用于存储小部件信息
set = new HashSet<AppWidgetAttribute>();
do {
try {
// 遍历查询结果为每个笔记创建一个小部件属性对象并将其添加到HashSet中
AppWidgetAttribute widget = new AppWidgetAttribute();
widget.widgetId = c.getInt(0);
widget.widgetType = c.getInt(1);
set.add(widget);
} catch (IndexOutOfBoundsException e) {
// 捕获IndexOutOfBoundsException异常记录错误日志
Log.e(TAG, e.toString());
}
} while (c.moveToNext());
}
// 关闭游标
c.close();
}
// 返回文件夹中所有笔记的小部件信息集合
return set;
}
// 根据笔记ID获取通话记录号码
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 + "=?",
@ -302,51 +233,38 @@ public class DataUtils {
if (cursor != null && cursor.moveToFirst()) {
try {
// 如果查询结果不为空,获取通话记录号码并返回
return cursor.getString(0);
} catch (IndexOutOfBoundsException e) {
// 捕获IndexOutOfBoundsException异常记录错误日志
Log.e(TAG, "Get call number fails " + e.toString());
} finally {
// 关闭游标
cursor.close();
}
}
// 如果查询结果为空或发生异常,返回空字符串
return "";
}
// 根据通话日期和电话号码查询通话记录的笔记ID
public static long getCallNoteIdByCallDateAndPhoneNumber(ContentResolver resolver, long callDate, String phoneNumber) {
// 查询通话日期和电话号码匹配的通话记录的笔记ID
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
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 + ",?)",
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
if (cursor != null) {
if (cursor.moveToFirst()) {
try {
// 如果查询结果不为空获取通话记录的笔记ID并返回
return cursor.getLong(0);
} catch (IndexOutOfBoundsException e) {
// 捕获IndexOutOfBoundsException异常记录错误日志
Log.e(TAG, "Get call note id fails " + e.toString());
}
}
// 关闭游标
cursor.close();
}
// 如果查询结果为空或发生异常返回0
return 0;
}
// 根据笔记ID查询摘要
public static String getSnippetById(ContentResolver resolver, long noteId) {
// 查询指定笔记ID的摘要信息
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
new String [] { NoteColumns.SNIPPET },
NoteColumns.ID + "=?",
@ -356,31 +274,22 @@ public class DataUtils {
if (cursor != null) {
String snippet = "";
if (cursor.moveToFirst()) {
// 如果查询结果不为空,获取摘要信息并返回
snippet = cursor.getString(0);
}
// 关闭游标
cursor.close();
return snippet;
}
// 如果查询结果为空抛出IllegalArgumentException异常
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');
if (index != -1) {
// 如果存在换行符,截取换行符之前的部分作为摘要
snippet = snippet.substring(0, index);
}
}
// 返回格式化后的摘要信息
return snippet;
}
}

@ -18,143 +18,96 @@ package net.micode.notes.tool;
public class GTaskStringUtils {
// GTASK JSON 中的操作 ID
public final static String GTASK_JSON_ACTION_ID = "action_id";
// GTASK JSON 中的操作列表
public final static String GTASK_JSON_ACTION_LIST = "action_list";
// GTASK JSON 中的操作类型
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";
// GTASK JSON 中的创建者 ID
public final static String GTASK_JSON_CREATOR_ID = "creator_id";
// GTASK JSON 中的子实体
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
// GTASK JSON 中的客户端版本
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
// GTASK JSON 中的完成状态
public final static String GTASK_JSON_COMPLETED = "completed";
// GTASK JSON 中的当前列表 ID
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
// GTASK JSON 中的默认列表 ID
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
// GTASK JSON 中的已删除标志
public final static String GTASK_JSON_DELETED = "deleted";
// GTASK JSON 中的目标列表
public final static String GTASK_JSON_DEST_LIST = "dest_list";
// GTASK JSON 中的目标父实体
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
// GTASK JSON 中的目标父实体类型
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
// GTASK JSON 中的实体变更
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
// GTASK JSON 中的实体类型
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
// GTASK JSON 中的已删除获取标志
public final static String GTASK_JSON_GET_DELETED = "get_deleted";
// GTASK JSON 中的 ID
public final static String GTASK_JSON_ID = "id";
// GTASK JSON 中的索引
public final static String GTASK_JSON_INDEX = "index";
// GTASK JSON 中的最后修改时间
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
// GTASK JSON 中的最新同步点
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
// GTASK JSON 中的列表 ID
public final static String GTASK_JSON_LIST_ID = "list_id";
// GTASK JSON 中的列表
public final static String GTASK_JSON_LISTS = "lists";
// GTASK JSON 中的名称
public final static String GTASK_JSON_NAME = "name";
// GTASK JSON 中的新 ID
public final static String GTASK_JSON_NEW_ID = "new_id";
// GTASK JSON 中的笔记
public final static String GTASK_JSON_NOTES = "notes";
// GTASK JSON 中的父 ID
public final static String GTASK_JSON_PARENT_ID = "parent_id";
// GTASK JSON 中的上一个兄弟 ID
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
// GTASK JSON 中的结果
public final static String GTASK_JSON_RESULTS = "results";
// GTASK JSON 中的源列表
public final static String GTASK_JSON_SOURCE_LIST = "source_list";
// GTASK JSON 中的任务
public final static String GTASK_JSON_TASKS = "tasks";
// GTASK JSON 中的类型
public final static String GTASK_JSON_TYPE = "type";
// GTASK JSON 中的组类型
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
// GTASK JSON 中的任务类型
public final static String GTASK_JSON_TYPE_TASK = "TASK";
// GTASK JSON 中的用户
public final static String GTASK_JSON_USER = "user";
// MIUI 文件夹前缀
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";
// 元数据头部 GTask ID
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";
}

@ -24,180 +24,149 @@ import net.micode.notes.ui.NotesPreferenceActivity;
public class ResourceParser {
// 背景颜色常量
public static final int YELLOW = 0;
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
// 默认背景颜色
public static final int BG_DEFAULT_COLOR = YELLOW;
// 文字大小常量
public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
// 默认字体大小
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
// 笔记背景资源
public static class NoteBgResources {
// 编辑背景资源数组
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
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
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];
}
}
// 获取默认背景颜色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 [] {
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
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
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,
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
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
};
// 获取第一个条目的背景资源
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
// 获取最后一个条目的背景资源
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
// 获取单独一项条目的背景资源
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
// 获取普通条目的背景资源
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
// 获取文件夹的背景资源
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
// 小部件背景资源
public static class WidgetBgResources {
// 2x小部件背景资源数组
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
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,
};
// 获取2x小部件背景资源
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
// 4x小部件背景资源数组
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
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
};
// 获取4x小部件背景资源
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
// 文字外观资源
public static class TextAppearanceResources {
// 文字外观资源数组
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
// 获取文字外观资源
public static int getTexAppearanceResource(int id) {
/**
* HACKME: IDbug
* IDBG_DEFAULT_FONT_SIZE
* 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) {
return BG_DEFAULT_FONT_SIZE;
@ -205,10 +174,8 @@ public class ResourceParser {
return TEXTAPPEARANCE_RESOURCES[id];
}
// 获取资源数组的长度
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}

@ -1,3 +1,19 @@
/*
* 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;
@ -8,12 +24,7 @@ public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent.setClass(context, AlarmAlertActivity.class);
//启动AlarmAlertActivity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//activity要存在于activity的栈中而非activity的途径启动activity时必然不存在一个activity的栈
//所以要新起一个栈装入启动的activity
context.startActivity(intent);
}
}
//这是实现alarm这个功能最接近用户层的包基于上面的两个包
//作用还需要深究但是对于setClass和addFlags的

@ -1,10 +1,20 @@
package net.micode.notes.ui;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import net.micode.notes.R;
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.content.Context;
import android.text.format.DateFormat;
@ -12,9 +22,13 @@ import android.view.View;
import android.widget.FrameLayout;
import android.widget.NumberPicker;
import net.micode.notes.R;
import java.text.DateFormatSymbols;
import java.util.Calendar;
public class DateTimePicker extends FrameLayout {
//FrameLayout是布局模板之一
//所有的子元素全部在屏幕的右上方
private static final boolean DEFAULT_ENABLE_STATE = true;
private static final int HOURS_IN_HALF_DAY = 12;
@ -30,15 +44,13 @@ public class DateTimePicker extends FrameLayout {
private static final int MINUT_SPINNER_MAX_VAL = 59;
private static final int AMPM_SPINNER_MIN_VAL = 0;
private static final int AMPM_SPINNER_MAX_VAL = 1;
//初始化控件
private final NumberPicker mDateSpinner;
private final NumberPicker mHourSpinner;
private final NumberPicker mMinuteSpinner;
private final NumberPicker mAmPmSpinner;
//NumberPicker是数字选择器
//这里定义的四个变量全部是在设置闹钟时需要选择的变量(如日期、时、分、上午或者下午)
private Calendar mDate;
//定义了Calendar类型的变量mDate用于操作时间
private String[] mDateDisplayValues = new String[DAYS_IN_ALL_WEEK];
private boolean mIsAm;
@ -58,49 +70,43 @@ public class DateTimePicker extends FrameLayout {
updateDateControl();
onDateTimeChanged();
}
};//OnValueChangeListener这是时间改变监听器这里主要是对日期的监听
//将现在日期的值传递给mDateupdateDateControl是同步操作
};
private NumberPicker.OnValueChangeListener mOnHourChangedListener = new NumberPicker.OnValueChangeListener() {
//这里是对 小时Hour 的监听
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
boolean isDateChanged = false;
Calendar cal = Calendar.getInstance();
//声明一个Calendar的变量cal便于后续的操作
if (!mIs24HourView) {
if (!mIsAm && oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
//这里是对于12小时制时晚上11点和12点交替时对日期的更改
//12小时制时晚上11点和12点交替时对日期的更改
} else if (mIsAm && oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
//这里是对于12小时制时凌晨11点和12点交替时对日期的更改
if (oldVal == HOURS_IN_HALF_DAY - 1 && newVal == HOURS_IN_HALF_DAY ||
oldVal == HOURS_IN_HALF_DAY && newVal == HOURS_IN_HALF_DAY - 1) {
mIsAm = !mIsAm;
updateAmPmControl();
}//这里是对于12小时制时中午11点和12点交替时对AM和PM的更改
}
} else {
//24小时
if (oldVal == HOURS_IN_ALL_DAY - 1 && newVal == 0) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, 1);
isDateChanged = true;
//这里是对于24小时制时晚上11点和12点交替时对日期的更改
} else if (oldVal == 0 && newVal == HOURS_IN_ALL_DAY - 1) {
cal.setTimeInMillis(mDate.getTimeInMillis());
cal.add(Calendar.DAY_OF_YEAR, -1);
isDateChanged = true;
}
} //这里是对于12小时制时凌晨11点和12点交替时对日期的更改
}
int newHour = mHourSpinner.getValue() % HOURS_IN_HALF_DAY + (mIsAm ? 0 : HOURS_IN_HALF_DAY);
//通过数字选择器对newHour的赋值
mDate.set(Calendar.HOUR_OF_DAY, newHour);
//通过set函数将新的Hour值传给mDate
onDateTimeChanged();
if (isDateChanged) {
setCurrentYear(cal.get(Calendar.YEAR));
@ -112,19 +118,18 @@ public class DateTimePicker extends FrameLayout {
private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() {
@Override
//这里是 分钟(Minute改变的监听
//对Minute改变的监听
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int minValue = mMinuteSpinner.getMinValue();
int maxValue = mMinuteSpinner.getMaxValue();
int offset = 0;
//设置offset作为小时改变的一个记录数据
//如果原值为59新值为0则offset加1
//如果原值为0新值为59则offset减1
if (oldVal == maxValue && newVal == minValue) {
offset += 1;
} else if (oldVal == minValue && newVal == maxValue) {
offset -= 1;
}
//如果原值为59新值为0则offset加1
//如果原值为0新值为59则offset减1
if (offset != 0) {
mDate.add(Calendar.HOUR_OF_DAY, offset);
mHourSpinner.setValue(getCurrentHour());
@ -144,7 +149,6 @@ public class DateTimePicker extends FrameLayout {
};
private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() {
//对AM和PM的监听
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
mIsAm = !mIsAm;
@ -160,27 +164,25 @@ public class DateTimePicker extends FrameLayout {
public interface OnDateTimeChangedListener {
void onDateTimeChanged(DateTimePicker view, int year, int month,
int dayOfMonth, int hourOfDay, int minute);
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));
}//上面函数的得到的是一个天文数字1970至今的秒数需要DateFormat将其变得有意义
}
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);
//如果当前Activity里用到别的layout比如对话框layout
//还要设置这个layout上的其他组件的内容就必须用inflate()方法先将对话框的layout找出来
//然后再用findViewById()找到它上面的其它组件
mDateSpinner = (NumberPicker) findViewById(R.id.date);
mDateSpinner.setMinValue(DATE_SPINNER_MIN_VAL);
mDateSpinner.setMaxValue(DATE_SPINNER_MAX_VAL);
@ -188,7 +190,7 @@ public class DateTimePicker extends FrameLayout {
mHourSpinner = (NumberPicker) findViewById(R.id.hour);
mHourSpinner.setOnValueChangedListener(mOnHourChangedListener);
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);
mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);
mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);
mMinuteSpinner.setOnLongPressUpdateInterval(100);
@ -229,9 +231,7 @@ public class DateTimePicker extends FrameLayout {
mAmPmSpinner.setEnabled(enabled);
mIsEnabled = enabled;
}
//存在疑问setEnabled的作用
//下面的代码通过原程序的注释已经比较清晰,另外可以通过函数名来判断
//下面的各函数主要是对上面代码引用到的各函数功能的实现
@Override
public boolean isEnabled() {
return mIsEnabled;
@ -244,7 +244,7 @@ public class DateTimePicker extends FrameLayout {
*/
public long getCurrentDateInTimeMillis() {
return mDate.getTimeInMillis();
}//实现函数——得到当前的秒数
}
/**
* Set the current date
@ -256,7 +256,7 @@ public class DateTimePicker extends FrameLayout {
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));
}//实现函数功能——设置当前的时间参数是date
}
/**
* Set the current date
@ -268,20 +268,19 @@ public class DateTimePicker extends FrameLayout {
* @param minute The current minute
*/
public void setCurrentDate(int year, int month,
int dayOfMonth, int hourOfDay, int minute) {
int dayOfMonth, int hourOfDay, int minute) {
setCurrentYear(year);
setCurrentMonth(month);
setCurrentDay(dayOfMonth);
setCurrentHour(hourOfDay);
setCurrentMinute(minute);
}//实现函数功能——设置当前的时间,参数是各详细的变量
}
/**
* Get current year
*
* @return The current year
*/
//下面是得到year、month、day等值
public int getCurrentYear() {
return mDate.get(Calendar.YEAR);
}
@ -452,7 +451,7 @@ public class DateTimePicker extends FrameLayout {
mDateSpinner.setDisplayedValues(mDateDisplayValues);
mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
mDateSpinner.invalidate();
}// 对于星期几的算法
}
private void updateAmPmControl() {
if (mIs24HourView) {
@ -461,7 +460,7 @@ public class DateTimePicker extends FrameLayout {
int index = mIsAm ? Calendar.AM : Calendar.PM;
mAmPmSpinner.setValue(index);
mAmPmSpinner.setVisibility(View.VISIBLE);
}// 对于上下午操作的算法
}
}
private void updateHourControl() {
@ -471,7 +470,7 @@ public class DateTimePicker extends FrameLayout {
} else {
mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW);
mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW);
}// 对与小时的算法
}
}
/**
@ -488,4 +487,4 @@ public class DateTimePicker extends FrameLayout {
getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute());
}
}
}
}

@ -1,10 +1,20 @@
package net.micode.notes.ui;
import java.util.Calendar;
/*
* 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.
*/
import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
package net.micode.notes.ui;
import android.app.AlertDialog;
import android.content.Context;
@ -13,50 +23,45 @@ import android.content.DialogInterface.OnClickListener;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import net.micode.notes.R;
import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener;
import java.util.Calendar;
public class DateTimePickerDialog extends AlertDialog implements OnClickListener {
private Calendar mDate = Calendar.getInstance();
//创建一个Calendar类型的变量 mDate方便时间的操作
private boolean mIs24HourView;
private OnDateTimeSetListener mOnDateTimeSetListener;
//声明一个时间日期滚动选择控件 mOnDateTimeSetListener
private DateTimePicker mDateTimePicker;
//DateTimePicker控件控件一般用于让用户可以从日期列表中选择单个值。
//运行时,单击控件边上的下拉箭头,会显示为两个部分:一个下拉列表,一个用于选择日期的
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) {
int dayOfMonth, int hourOfDay, int minute) {
//设置为系统时间
mDate.set(Calendar.YEAR, year);
mDate.set(Calendar.MONTH, month);
mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mDate.set(Calendar.HOUR_OF_DAY, hourOfDay);
mDate.set(Calendar.MINUTE, minute);
//将视图中的各选项设置为系统当前时间
updateTitle(mDate.getTimeInMillis());
}
});
mDate.setTimeInMillis(date);
//得到系统时间
mDate.set(Calendar.SECOND, 0);
//将秒数设置为0
mDateTimePicker.setCurrentDate(mDate.getTimeInMillis());
setButton(context.getString(R.string.datetime_dialog_ok), this);
setButton2(context.getString(R.string.datetime_dialog_cancel), (OnClickListener)null);
//设置按钮
set24HourView(DateFormat.is24HourFormat(this.getContext()));
//时间标准化打印
updateTitle(mDate.getTimeInMillis());
}
@ -66,22 +71,21 @@ public class DateTimePickerDialog extends AlertDialog implements OnClickListener
public void setOnDateTimeSetListener(OnDateTimeSetListener callBack) {
mOnDateTimeSetListener = callBack;
}//将时间日期滚动选择控件实例化
}
private void updateTitle(long date) {
int flag =
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
DateUtils.FORMAT_SHOW_YEAR |
DateUtils.FORMAT_SHOW_DATE |
DateUtils.FORMAT_SHOW_TIME;
flag |= mIs24HourView ? DateUtils.FORMAT_24HOUR : DateUtils.FORMAT_24HOUR;
setTitle(DateUtils.formatDateTime(this.getContext(), date, flag));
}//android开发中常见日期管理工具类API——DateUtils按照上下午显示时间
}
public void onClick(DialogInterface arg0, int arg1) {
if (mOnDateTimeSetListener != null) {
mOnDateTimeSetListener.OnDateTimeSet(this, mDate.getTimeInMillis());
}
}//第一个参数arg0是接收到点击事件的对话框
//第二个参数arg1是该对话框上的按钮
}
}

@ -1,3 +1,19 @@
/*
* 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;
@ -14,18 +30,14 @@ 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);
//设置这个view的背景
mPopupMenu = new PopupMenu(context, mButton);
mMenu = mPopupMenu.getMenu();
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);
//MenuInflater是用来实例化Menu目录下的Menu布局文件
//根据ID来确认menu的内容选项
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPopupMenu.show();
@ -36,14 +48,14 @@ public class DropdownMenu {
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);
}//布局文件,设置标题
}
}
}

@ -1,3 +1,19 @@
/*
* 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;
@ -14,14 +30,10 @@ import net.micode.notes.data.Notes.NoteColumns;
public class FoldersListAdapter extends CursorAdapter {
//CursorAdapter是Cursor和ListView的接口
//FoldersListAdapter继承了CursorAdapter的类
//主要作用是便签数据库和用户的交互
//这里就是用folder文件夹的形式展现给用户
public static final String [] PROJECTION = {
NoteColumns.ID,
NoteColumns.SNIPPET
};//调用数据库中便签的ID和片段
NoteColumns.ID,
NoteColumns.SNIPPET
};
public static final int ID_COLUMN = 0;
public static final int NAME_COLUMN = 1;
@ -29,13 +41,12 @@ public class FoldersListAdapter extends CursorAdapter {
public FoldersListAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}//数据库操作
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
//ViewGroup是容器
return new FolderListItem(context);
}//创建一个文件夹,对于各文件夹中子标签的初始化
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
@ -44,22 +55,20 @@ public class FoldersListAdapter extends CursorAdapter {
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
((FolderListItem) view).bind(folderName);
}
}//将各个布局文件绑定起来
}
public String getFolderName(Context context, int position) {
Cursor cursor = (Cursor) getItem(position);
return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context
.getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN);
}//根据数据库中标签的ID得到标签的各项内容
}
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);
}
@ -68,4 +77,4 @@ public class FoldersListAdapter extends CursorAdapter {
}
}
}
}

@ -1,3 +1,19 @@
/*
* 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;
@ -12,20 +28,20 @@ import net.micode.notes.tool.DataUtils;
public class NoteItemData {
static final String [] PROJECTION = new String [] {
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
NoteColumns.ID,
NoteColumns.ALERTED_DATE,
NoteColumns.BG_COLOR_ID,
NoteColumns.CREATED_DATE,
NoteColumns.HAS_ATTACHMENT,
NoteColumns.MODIFIED_DATE,
NoteColumns.NOTES_COUNT,
NoteColumns.PARENT_ID,
NoteColumns.SNIPPET,
NoteColumns.TYPE,
NoteColumns.WIDGET_ID,
NoteColumns.WIDGET_TYPE,
};
//常量标记和数据就不一一标记了,意义翻译基本就知道
private static final int ID_COLUMN = 0;
private static final int ALERTED_DATE_COLUMN = 1;
private static final int BG_COLOR_ID_COLUMN = 2;
@ -59,9 +75,8 @@ public class NoteItemData {
private boolean mIsOnlyOneItem;
private boolean mIsOneNoteFollowingFolder;
private boolean mIsMultiNotesFollowingFolder;
//初始化NoteItemData主要利用光标cursor获取的东西
public NoteItemData(Context context, Cursor cursor) {
//getxxx为转换格式
public NoteItemData(Context context, Cursor cursor) {
mId = cursor.getLong(ID_COLUMN);
mAlertDate = cursor.getLong(ALERTED_DATE_COLUMN);
mBgColorId = cursor.getInt(BG_COLOR_ID_COLUMN);
@ -77,11 +92,10 @@ public class NoteItemData {
mWidgetId = cursor.getInt(WIDGET_ID_COLUMN);
mWidgetType = cursor.getInt(WIDGET_TYPE_COLUMN);
//初始化电话号码的信息
mPhoneNumber = "";
if (mParentId == Notes.ID_CALL_RECORD_FOLDER) {
mPhoneNumber = DataUtils.getCallNumberByNoteId(context.getContentResolver(), mId);
if (!TextUtils.isEmpty(mPhoneNumber)) {//mphonenumber里有符合字符串则用contart功能连接
if (!TextUtils.isEmpty(mPhoneNumber)) {
mName = Contact.getContact(context, mPhoneNumber);
if (mName == null) {
mName = mPhoneNumber;
@ -94,35 +108,32 @@ public class NoteItemData {
}
checkPostion(cursor);
}
///根据鼠标的位置设置标记,和位置
private void checkPostion(Cursor cursor) {
//初始化几个标记cursor具体功能笔记中已提到不一一叙述
mIsLastItem = cursor.isLast() ? true : false;
mIsFirstItem = cursor.isFirst() ? true : false;
mIsOnlyOneItem = (cursor.getCount() == 1);
//初始化“多重子文件”“单一子文件”2个标记
mIsMultiNotesFollowingFolder = false;
mIsOneNoteFollowingFolder = false;
//主要是设置上诉2标记
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {//若是note格式并且不是第一个元素
if (mType == Notes.TYPE_NOTE && !mIsFirstItem) {
int position = cursor.getPosition();
if (cursor.moveToPrevious()) {//获取光标位置后看上一行
if (cursor.moveToPrevious()) {
if (cursor.getInt(TYPE_COLUMN) == Notes.TYPE_FOLDER
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {//若光标满足系统或note格式
|| cursor.getInt(TYPE_COLUMN) == Notes.TYPE_SYSTEM) {
if (cursor.getCount() > (position + 1)) {
mIsMultiNotesFollowingFolder = true;//若是数据行数大于但前位置+1则设置成正确
mIsMultiNotesFollowingFolder = true;
} else {
mIsOneNoteFollowingFolder = true;//否则单一文件夹标记为true
mIsOneNoteFollowingFolder = true;
}
}
if (!cursor.moveToNext()) {//若不能再往下走则报错
if (!cursor.moveToNext()) {
throw new IllegalStateException("cursor move to previous but can't move back");
}
}
}
}
///以下都是获取标记没什么好说的,不过倒数第二个需要说明下,很具体看下面
public boolean isOneFollowingFolder() {
return mIsOneNoteFollowingFolder;
}
@ -203,7 +214,6 @@ public class NoteItemData {
return (mAlertDate > 0);
}
//若数据父id为保存至文件夹模式的id且满足电话号码单元不为空则isCallRecord为true
public boolean isCallRecord() {
return (mParentId == Notes.ID_CALL_RECORD_FOLDER && !TextUtils.isEmpty(mPhoneNumber));
}
@ -211,4 +221,4 @@ public class NoteItemData {
public static int getNoteType(Cursor cursor) {
return cursor.getInt(TYPE_COLUMN);
}
}
}

@ -1,3 +1,19 @@
/*
* 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;
@ -7,7 +23,6 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import net.micode.notes.data.Notes;
import java.util.Collection;
@ -16,94 +31,55 @@ import java.util.HashSet;
import java.util.Iterator;
/*
* 便CursorAdaptercursorListView
* NotesListAdapter便
*/
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 int mNotesCount;
private boolean mChoiceMode;
/*
* widget
*/
public static class AppWidgetAttribute {
public int widgetId;
public int widgetType;
};
/*
* 便
*
*/
public NotesListAdapter(Context context) {
super(context, null); //父类对象置空
mSelectedIndex = new HashMap<Integer, Boolean>(); //新建选项下标的hash表
super(context, null);
mSelectedIndex = new HashMap<Integer, Boolean>();
mContext = context;
mNotesCount = 0;
}
@Override
/*
*
* 使NotesListItem
*/
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) {
//若view是NotesListItem的一个实例
NoteItemData itemData = new NoteItemData(context, cursor);
((NotesListItem) view).bind(context, itemData, mChoiceMode,
isSelectedItem(cursor.getPosition()));
//则新建一个项目选项并且用bind跟将view和鼠标内容便签数据捆绑在一起
}
}
/*
*
*
*/
public void setCheckedItem(final int position, final boolean checked) {
mSelectedIndex.put(position, checked);
//根据定位和是否勾选设置下标
notifyDataSetChanged();
//在修改后刷新activity
}
/*
*
*/
public boolean isInChoiceMode() {
return mChoiceMode;
}
/*
*
* mode
*/
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) {
@ -111,47 +87,30 @@ public class NotesListAdapter extends CursorAdapter {
}
}
}
//遍历所有光标可用的位置在判断为便签类型之后勾选单项框
}
/*
*
*
*/
public HashSet<Long> getSelectedItemIds() {
HashSet<Long> itemSet = new HashSet<Long>();
//建立hash表
for (Integer position : mSelectedIndex.keySet()) {
//遍历所有的关键
if (mSelectedIndex.get(position) == true) {
//若光标位置可用
Long id = getItemId(position);
if (id == Notes.ID_ROOT_FOLDER) {
//原文件不需要添加
Log.d(TAG, "Wrong item id, should not happen");
} else {
itemSet.add(id);
}
//则将id该下标假如选项集合中
}
}
return itemSet;
}
/*
* Widget
*
*/
public HashSet<AppWidgetAttribute> getSelectedWidget() {
HashSet<AppWidgetAttribute> itemSet = new HashSet<AppWidgetAttribute>();
for (Integer position : mSelectedIndex.keySet()) {
if (mSelectedIndex.get(position) == true) {
Cursor c = (Cursor) getItem(position);
//以上4句和getSelectedItemIds一样不再重复
if (c != null) {
//光标位置可用的话就建立新的Widget属性并编辑下标和类型最后添加到选项集中
AppWidgetAttribute widget = new AppWidgetAttribute();
NoteItemData item = new NoteItemData(mContext, c);
widget.widgetId = item.getWidgetId();
@ -169,42 +128,26 @@ public class NotesListAdapter extends CursorAdapter {
return itemSet;
}
/*
*
*
*/
public int getSelectedCount() {
Collection<Boolean> values = mSelectedIndex.values();
//首先获取选项下标的值
if (null == values) {
return 0;
}
Iterator<Boolean> iter = values.iterator();
//初始化叠加器
int count = 0;
while (iter.hasNext()) {
if (true == iter.next()) {
//若value值为真计数+1
count++;
}
}
return count;
}
/*
*
*
*/
public boolean isAllSelected() {
int checkedCount = getSelectedCount();
return (checkedCount != 0 && checkedCount == mNotesCount);
//获取选项数看是否等于便签的个数
}
/*
*
*
*/
public boolean isSelectedItem(final int position) {
if (null == mSelectedIndex.get(position)) {
return false;
@ -213,45 +156,29 @@ public class NotesListAdapter extends CursorAdapter {
}
@Override
/*
* activity便
*
*/
protected void onContentChanged() {
super.onContentChanged();
//执行基类函数
calcNotesCount();
}
@Override
/*
* activity便
*/
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
//执行基类函数
calcNotesCount();
}
/*
* 便
*
*/
private void calcNotesCount() {
mNotesCount = 0;
for (int i = 0; i < getCount(); i++) {
//获取总数同时遍历
Cursor c = (Cursor) getItem(i);
if (c != null) {
if (NoteItemData.getNoteType(c) == Notes.TYPE_NOTE) {
mNotesCount++;
//若该位置不为空并且文本类型为便签就+1
}
} else {
Log.e(TAG, "Invalid cursor");
return;
}
//否则报错
}
}
}
}

@ -1,5 +1,22 @@
/*
* 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.annotation.SuppressLint;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.View;
@ -14,43 +31,38 @@ 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; //打钩框
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中定义的布局控件找出来,这里的xml是r。layout
//findViewById用于从contentView中查找指定ID的View转换出来的形式根据需要而定;
super(context);
inflate(context, R.layout.note_item, this);
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);
mTitle = (TextView) findViewById(R.id.tv_title);
mTime = (TextView) findViewById(R.id.tv_time);
mCallName = (TextView) findViewById(R.id.tv_name);
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);
}
///根据data的属性对各个控件的属性的控制主要是可见性Visibility内容setText格式setTextAppearance
@SuppressLint("SetTextI18n")
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); ///格子打钩
mCheckBox.setVisibility(View.VISIBLE);
mCheckBox.setChecked(checked);
} else {
mCheckBox.setVisibility(View.GONE);
}
mItemData = data;
///设置控件属性一共三种情况由data的id和父id是否与保存到文件夹的id一致来决定
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
mCallName.setVisibility(View.GONE);
mAlert.setVisibility(View.VISIBLE);
//设置该textview的style
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
//settext为设置内容
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));
mAlert.setImageResource(R.drawable.call_record);
@ -59,9 +71,8 @@ public class NotesListItem extends LinearLayout {
mCallName.setText(data.getCallName());
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
///关于闹钟的设置
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);//图片来源的设置
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
@ -69,48 +80,45 @@ public class NotesListItem extends LinearLayout {
} else {
mCallName.setVisibility(View.GONE);
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);
///设置title格式
if (data.getType() == Notes.TYPE_FOLDER) {
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));
data.getNotesCount()));
mAlert.setVisibility(View.GONE);
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);///设置图片来源
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);
}
}
}
///设置内容获取相关时间从data里编辑的日期中获取
mTime. setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));
setBackground(data);
}
//根据data的文件属性来设置背景
private void setBackground(NoteItemData data) {
int id = data.getBgColorId();
//若是note型文件则4种情况对于4种不同情况的背景来源
if (data.getType() == Notes.TYPE_NOTE) {
//单个数据并且只有一个子文件夹
if (data.isSingle() || data.isOneFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {//是最后一个数据
} else if (data.isLast()) {
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {//是一个数据并有多个子文件夹
} else if (data.isFirst() || data.isMultiFollowingFolder()) {
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));
}
} else {
//若不是note直接调用文件夹的背景来源
setBackgroundResource(NoteItemBgResources.getFolderBgRes());
}
}
public NoteItemData getItemData() {
return mItemData;
}
}
}

@ -1,8 +1,23 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
@ -11,6 +26,7 @@ import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
@ -19,104 +35,82 @@ 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 androidx.annotation.RequiresApi;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;
/*
*NotesPreferenceActivity便
* PreferenceActivityActivity
*/
import java.util.Objects;
public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences";
//优先名
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
//同步账号
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
//同步时间
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
//同步密码
private static final String AUTHORITIES_FILTER_KEY = "authorities";
//本地密码
private PreferenceCategory mAccountCategory;
//账户分组
private GTaskReceiver mReceiver;
//同步任务接收器
private Account[] mOriAccounts;
//账户
private boolean mHasAddedAccount;
//账户的hash标记
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
@Override
/*
*activity
*Bundle icicle activity
*
*/
protected void onCreate(Bundle icicle) {
//先执行父类的创建函数
super.onCreate(icicle);
/* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true);
//给左上角图标的左边加上一个返回的图标
Objects.requireNonNull(getActionBar()).setDisplayHomeAsUpEnabled(true);
addPreferencesFromResource(R.xml.preferences);
//添加xml来源并显示 xml
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
//根据同步账户关键码来初始化分组
mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);
//初始化同步组件
registerReceiver(mReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
//获取listvivewListView的作用:用于列出所有选择
getListView().addHeaderView(header, null, true);
//在listview组件上方添加其他组件
}
@Override
/*
* activity
*
*/
protected void onResume() {
//先执行父类 的交互实现
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;
}
}
@ -124,83 +118,58 @@ public class NotesPreferenceActivity extends PreferenceActivity {
}
refreshUI();
//刷新标签界面
}
@Override
/*
* activity
*
*/
protected void onDestroy() {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
//注销接收器
}
super.onDestroy();
//执行父类的销毁动作
}
/*
*
*
*/
private void loadAccountPreference() {
mAccountCategory.removeAll();
//销毁所有的分组
Preference accountPref = new Preference(this);
//建立首选项
final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary));
//设置首选项的大标题和小标题
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
//建立监听器
if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account
//若是第一次建立账户显示选择账户提示对话框
showSelectAccountAlertDialog();
} else {
// if the account has already been set, we need to promp
// user about the risk
//若是已经建立则显示修改对话框并进行修改操作
showChangeAccountConfirmAlertDialog();
}
} else {
//若在没有同步的情况下则在toast中显示不能修改
Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();
}
return true;
}
});
//根据新建首选项编辑新的账户分组
mAccountCategory.addPreference(accountPref);
}
/*
*
*
*/
private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
//获取同步按钮控件和最终同步时间的的窗口
// set button state
//设置按钮的状态
if (GTaskSyncService.isSyncing()) {
//若是在同步状态下
syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
}
});
//设置按钮显示的文本为“取消同步”以及监听器
} else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() {
@ -208,67 +177,50 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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);
//设置对话框的自定义标题建立一个YES的按钮
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;
@ -276,119 +228,83 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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"
"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() {
//设置对话框要显示的一个list用于显示几个命令时,即changeremovecancel
public void onClick(DialogInterface dialog, int which) {
//按键功能由which来决定
if (which == 0) {
//进入账户选择对话框
showSelectAccountAlertDialog();
} else if (which == 1) {
//删除账户并且跟新便签界面
removeSyncAccount();
refreshUI();
}
}
});
dialogBuilder.show();
//显示对话框
}
/*
*
*
*/
private Account[] getGoogleAccounts() {
AccountManager accountManager = AccountManager.get(this);
return accountManager.getAccountsByType("com.google");
}
/*
*
*
*/
private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {
//假如该账号不在同步账号列表中
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
//编辑共享的首选项
if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
}
//将该账号加入到首选项中
editor.commit();
//提交修改的数据
// clean up last sync time
setLastSyncTime(this, 0);
//将最后同步时间清零
// clean up local gtask related info
new Thread(new Runnable() {
@ -399,33 +315,23 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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();
//将toast的文本信息置为“设置账户成功”并显示出来
}
}
/*
*
*
*/
private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
//设置共享首选项
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
//假如当前首选项中有账户就删除
}
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME);
//删除当前首选项中有账户时间
}
editor.commit();
//提交更新后的数据
// clean up local gtask related info
new Thread(new Runnable() {
@ -436,79 +342,51 @@ public class NotesPreferenceActivity extends PreferenceActivity {
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);
}
/*
*
* BroadcastReceiver
*/
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));
//通过获取的数据在设置系统的状态
}
}
}
/*
*
*
* :MenuItem
*/
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;
//在主页情况下在创建连接组件intent发出清空的信号并开始一个相应的activity
default:
return false;
}
}
}
Loading…
Cancel
Save