diff --git a/QQ图片20230420210242.jpg b/QQ图片20230420210242.jpg new file mode 100644 index 0000000..9723bd9 Binary files /dev/null and b/QQ图片20230420210242.jpg differ diff --git a/doc/字符统计/UML类图.png b/doc/字符统计/UML类图.png new file mode 100644 index 0000000..82de212 Binary files /dev/null and b/doc/字符统计/UML类图.png differ diff --git a/doc/字符统计/分析类图.jpg b/doc/字符统计/分析类图.jpg new file mode 100644 index 0000000..9132786 Binary files /dev/null and b/doc/字符统计/分析类图.jpg differ diff --git a/doc/字符统计/字符.png b/doc/字符统计/字符.png new file mode 100644 index 0000000..3afcb66 Binary files /dev/null and b/doc/字符统计/字符.png differ diff --git a/doc/字符统计/活动图.jpg b/doc/字符统计/活动图.jpg new file mode 100644 index 0000000..55ce5f8 Binary files /dev/null and b/doc/字符统计/活动图.jpg differ diff --git a/doc/字符统计/用例描述.docx b/doc/字符统计/用例描述.docx new file mode 100644 index 0000000..f343bca Binary files /dev/null and b/doc/字符统计/用例描述.docx differ diff --git a/doc/字符统计/界面跳转顺序图.docx b/doc/字符统计/界面跳转顺序图.docx new file mode 100644 index 0000000..2319f6a Binary files /dev/null and b/doc/字符统计/界面跳转顺序图.docx differ diff --git a/doc/字符统计/逻辑体系结构图.png b/doc/字符统计/逻辑体系结构图.png new file mode 100644 index 0000000..fa088ef Binary files /dev/null and b/doc/字符统计/逻辑体系结构图.png differ diff --git a/doc/字符统计/顺序图.jpg b/doc/字符统计/顺序图.jpg new file mode 100644 index 0000000..4954130 Binary files /dev/null and b/doc/字符统计/顺序图.jpg differ diff --git a/doc/实时显示天气/天气显示.png b/doc/实时显示天气/天气显示.png new file mode 100644 index 0000000..86308a9 Binary files /dev/null and b/doc/实时显示天气/天气显示.png differ diff --git a/doc/实时显示天气/界面跳转顺序图.docx b/doc/实时显示天气/界面跳转顺序图.docx new file mode 100644 index 0000000..2319f6a Binary files /dev/null and b/doc/实时显示天气/界面跳转顺序图.docx differ diff --git a/doc/实时显示天气/菜单栏.png b/doc/实时显示天气/菜单栏.png new file mode 100644 index 0000000..1ed2bce Binary files /dev/null and b/doc/实时显示天气/菜单栏.png differ diff --git a/doc/显示实时天气/UML类图.png b/doc/显示实时天气/UML类图.png new file mode 100644 index 0000000..82de212 Binary files /dev/null and b/doc/显示实时天气/UML类图.png differ diff --git a/doc/显示实时天气/分析类图.jpg b/doc/显示实时天气/分析类图.jpg new file mode 100644 index 0000000..e853342 Binary files /dev/null and b/doc/显示实时天气/分析类图.jpg differ diff --git a/doc/显示实时天气/活动图.png b/doc/显示实时天气/活动图.png new file mode 100644 index 0000000..6ffa7c0 Binary files /dev/null and b/doc/显示实时天气/活动图.png differ diff --git a/doc/显示实时天气/用例描述.docx b/doc/显示实时天气/用例描述.docx new file mode 100644 index 0000000..a85b82d Binary files /dev/null and b/doc/显示实时天气/用例描述.docx differ diff --git a/doc/显示实时天气/逻辑体系结构图.png b/doc/显示实时天气/逻辑体系结构图.png new file mode 100644 index 0000000..cf0b0b9 Binary files /dev/null and b/doc/显示实时天气/逻辑体系结构图.png differ diff --git a/doc/显示实时天气/顺序图.jpg b/doc/显示实时天气/顺序图.jpg new file mode 100644 index 0000000..126b9f0 Binary files /dev/null and b/doc/显示实时天气/顺序图.jpg differ diff --git a/doc/泛读报告.docx b/doc/泛读报告.docx index 3116784..39bb0ad 100644 Binary files a/doc/泛读报告.docx and b/doc/泛读报告.docx differ diff --git a/doc/精读报告/gtask/exception/ActionFailureException.doc b/doc/精读报告/gtask/exception/ActionFailureException.doc new file mode 100644 index 0000000..2dbfd26 --- /dev/null +++ b/doc/精读报告/gtask/exception/ActionFailureException.doc @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.exception;//小米便签行为异常处理 + +public class ActionFailureException extends RuntimeException {//从RuntimeException类派生出ActionFailureException类,用来处理行为异常 + private static final long serialVersionUID = 4425249765923293627L;//定义:serialVersionUID相当于java类的身份证,主要用于版本控制。 + + public ActionFailureException() {// 函数:交给父类的构造函数(包括下面的两个构造函数) + super();//super是指向父类的一个指针,与其相对的还有this,指向当前类。 + } + + public ActionFailureException(String paramString) { + super(paramString); + } + + public ActionFailureException(String paramString, Throwable paramThrowable) {//调用父类具有相同形参paramString和paramThrowable的构造方法 + super(paramString, paramThrowable); + } +} diff --git a/doc/精读报告/gtask/exception/NetworkFailureException.doc b/doc/精读报告/gtask/exception/NetworkFailureException.doc new file mode 100644 index 0000000..c427813 --- /dev/null +++ b/doc/精读报告/gtask/exception/NetworkFailureException.doc @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.exception;//小米便签网络异常处理包,该源文件里定义的所有类都属于这个包 + +public class NetworkFailureException extends Exception {//应该是处理网络异常的类,直接继承于Exception + private static final long serialVersionUID = 2107610287180234136L;//定义:serialVersionUID相当于java类的身份证,主要用于版本控制。作用:验证版本一致性,如果不一致会导致反序列化的时候版本不一致的异常。 + + public NetworkFailureException() { + super(); + }//构造函数(以下三个都是) + + public NetworkFailureException(String paramString) { + super(paramString);//调用父类具有相同形参paramString的构造方法,相当于Exception(paramString) + } + + public NetworkFailureException(String paramString, Throwable paramThrowable) { + super(paramString, paramThrowable);//调用父类具有相同形参paramString和paramThrowable的构造方法 + } +} diff --git a/doc/精读报告/gtask/remote/GTaskASyncTask.doc b/doc/精读报告/gtask/remote/GTaskASyncTask.doc new file mode 100644 index 0000000..f4a6654 --- /dev/null +++ b/doc/精读报告/gtask/remote/GTaskASyncTask.doc @@ -0,0 +1,123 @@ + +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote;//实现异步操作避免单个操作耗时过久而堵塞任务的关键路径,从而整体卡顿 + +import android.app.Notification;//以下几行都是引用基于数据库服务的类 +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.AsyncTask; + +import net.micode.notes.R; +import net.micode.notes.ui.NotesListActivity; +import net.micode.notes.ui.NotesPreferenceActivity; + + +public class GTaskASyncTask extends AsyncTask {//异步任务类:任务同步和取消,显示同步任务的进程、通知和结果 + + private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;//定义一个int变量,作用是存储GTASK同步通知ID + + public interface OnCompleteListener {//方法:声明了一个名为OnCompleteListener的接口,其内部的OnComplete方法在GTaskSyncService里面实现,用来初始化异步的功能 + void onComplete();//初始化 + } + + private Context mContext;//定义成员:文本内容 + + private NotificationManager mNotifiManager;//对象: 通知管理器类的实例化 + + private GTaskManager mTaskManager;//实例化任务管理器 + + private OnCompleteListener mOnCompleteListener;//实例化是否完成的监听器 + + public GTaskASyncTask(Context context, OnCompleteListener listener) {//传入两个变量,构造形成GtaskASyncTask类 + mContext = context;// 引入两个变量,构造形成GtaskASyncTask类 + mOnCompleteListener = listener; + mNotifiManager = (NotificationManager) mContext//getSystemService是Activity的一个方法,可根据传入的参数获得应服务的对象。这里以Context的NOTIFICATION_SERVICE为对象。 + .getSystemService(Context.NOTIFICATION_SERVICE);//getSystemService是一种可根据传入的参数获得应服务的对象的端口函数。 + mTaskManager = GTaskManager.getInstance();//getInstance ()函数用于使用单例模式创建类的实例。 + } + + public void cancelSync() {//取消同步 + mTaskManager.cancelSync();//调用类中的同名方法来取消同步 + } + + public void publishProgess(String message) {//显示消息(string message) + publishProgress(new String[] {//String[]创建java数组 + message + }); + } + + private void showNotification(int tickerId, String content) {//显示通知 + Notification notification = new Notification(R.drawable.notification, mContext//新建一个通知 + .getString(tickerId), System.currentTimeMillis());//新建一个通知并显示通知 + notification.defaults = Notification.DEFAULT_LIGHTS;// 默认调用系统自带灯光 + notification.flags = Notification.FLAG_AUTO_CANCEL; + PendingIntent pendingIntent;//描述了想要启动一个Activity、Broadcast或是Service的意图 + if (tickerId != R.string.ticker_success) {// 点击清除按钮或点击通知后会自动消失 + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,//若同步不成功,就从系统取得一个来启动NotesPreferenceActivity的对象 + NotesPreferenceActivity.class), 0);//获取首选项设置页 + + } else { + pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,//若同步成功,就从系统取得一个来启动一个NotesListActivity的对象 + NotesListActivity.class), 0); + } + notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content, + pendingIntent);//设置最新事件信息 + mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify()方法来执行一个notification的消息 + } + + @Override//这是Java5的元数据,自动加上去的一个标志,目的是告诉你下面这个方法是从父类/接口继承过来的,需要重写一次 + protected Integer doInBackground(Void... unused) {//执行后台操作 + publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity//利用getString,将把 字符串内容传进sync_progress_login中 + .getSyncAccountName(mContext))); + return mTaskManager.sync(mContext, this);//在后台进行同步 + } + + @Override//这是Java5的元数据,自动加上去的一个标志,目的是告诉你下面这个方法是从父类/接口继承过来的,需要重写一次 + protected void onProgressUpdate(String... progress) {//显示进度的更新 + showNotification(R.string.ticker_syncing, progress[0]);//显示进度的更新 + if (mContext instanceof GTaskSyncService) {//判断mContext是否是GTaskSyncService的实例 + ((GTaskSyncService) mContext).sendBroadcast(progress[0]);// 如果mContext是GTaskSyncService实例化的对象则发送一个广播 + } + } + + @Override//这是Java5的元数据,自动加上去的一个标志,目的是告诉你下面这个方同步失败,取消法是从父类/接口继承过来的,需要重写一次 + protected void onPostExecute(Integer result) {//设置任务,比如在用户界面显示一个进度条 + if (result == GTaskManager.STATE_SUCCESS) {//若匹配成功,则显示成功及展示出同步的账户 + showNotification(R.string.ticker_success, mContext.getString(//若匹配成功,则显示成功及展示出同步的账户 + R.string.success_sync_account, mTaskManager.getSyncAccount())); + NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis()); + } else if (result == GTaskManager.STATE_NETWORK_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));//设置最新同步的时间,防止时间出现更改。 + } else if (result == GTaskManager.STATE_INTERNAL_ERROR) { + showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));//网络故障导致同步出错 + } else if (result == GTaskManager.STATE_SYNC_CANCELLED) { + showNotification(R.string.ticker_cancel, mContext//同步失败,取消 + .getString(R.string.error_sync_cancelled)); + } + if (mOnCompleteListener != null) {//若监听器为空,则创建新进程 + new Thread(new Runnable() { + + public void run() { + mOnCompleteListener.onComplete(); + }//执行完后调用然后返回主线程中 + }).start(); + } + } +} diff --git a/doc/精读报告/gtask/remote/GTaskClient.doc b/doc/精读报告/gtask/remote/GTaskClient.doc new file mode 100644 index 0000000..dbc17f3 --- /dev/null +++ b/doc/精读报告/gtask/remote/GTaskClient.doc @@ -0,0 +1,584 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote;//这个函数用于自动登录账号并更新消息,创建或者获取任务列表 + +import android.accounts.Account;//引入包 +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.app.Activity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.GTaskStringUtils; +import net.micode.notes.ui.NotesPreferenceActivity; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.cookie.Cookie; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.apache.http.params.HttpProtocolParams; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.LinkedList; +import java.util.List; +import java.util.zip.GZIPInputStream; +import java.util.zip.Inflater; +import java.util.zip.InflaterInputStream;//引入包 + + +public class GTaskClient {//GTaskClient类:实现GTask的登录以及创建GTask任务和任务列表,从网络上获取任务内容 + private static final String TAG = GTaskClient.class.getSimpleName();//Google邮箱指定URL + + private static final String GTASK_URL = "https://mail.google.com/tasks/";//这个是获得URL + + private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";//这个是传递URL + + private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";//发布的uri + + private static GTaskClient mInstance = null;//后续使用的参数以及变量 + private DefaultHttpClient mHttpClient;//网络地址客户端 + + private String mGetUrl;//构造函数:初始化各属性 + + private String mPostUrl; + + private long mClientVersion; + + private boolean mLoggedin; + + private long mLastLoginTime; + + private int mActionId; + + private Account mAccount; + + private JSONArray mUpdateArray; + + private GTaskClient() {//getInstance:获取实例化对象并返回 + mHttpClient = null;//初始化客户端,使用 getInstance(),返回mInstance这个实例化对象,从而获取实例化对象 + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + mClientVersion = -1; + mLoggedin = false; + mLastLoginTime = 0; + mActionId = 1; + mAccount = null; + mUpdateArray = null; + } + + public static synchronized GTaskClient getInstance() {//获取实例,如果当前没有示例,则新建一个登陆的gtask,如果有直接返回 + if (mInstance == null) {// 若无实例,则新建一个 + mInstance = new GTaskClient(); + } + return mInstance; + } + + public boolean login(Activity activity) {//login:用于实现登录的方法,以activity作为参数 + // we suppose that the cookie would expire after 5 minutes//设置登录时间一旦超过5分钟即需要重新登录 + // then we need to re-login//实现登录:使用下面定义的loginGoogleAccount( )方法登录Google账户 ,使用下面定义的loginGtask( )方法登录gtask,登录成功返回true,登录失败返回false + final long interval = 1000 * 60 * 5;//interval:时间间隔为1000ns * 60 * 5 = 5min 即间隔5分钟时间 + if (mLastLoginTime + interval < System.currentTimeMillis()) {//判断距离上次登录的时间间隔,若超过5分钟,则重置登录状态 + mLoggedin = false;//取消登录 + } + + // need to re-login after account switch//need to re-login after account switch 重新登录操作 + if (mLoggedin//需要重新登录 + && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity + .getSyncAccountName(activity))) { + mLoggedin = false;//若未超时,不需要再次登录,输出已登录信息 + } + + if (mLoggedin) {//代码块,如果登录的时候符合上面的要求则让其显示已登录登陆 + Log.d(TAG, "already logged in");//显示已登录 + return true;//不需要再次登录 + } + + mLastLoginTime = System.currentTimeMillis();//更新登录时间为系统当前时间 + String authToken = loginGoogleAccount(activity, false);//获取登录令牌,判断是否登入google账号 + if (authToken == null) {//登录失败的情况 + Log.e(TAG, "login google account failed");//登录失败 + return false; + } + + // login with custom domain if necessary//利用自己的用户域名登陆 + if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()//使用用户域名进行登录 + .endsWith("googlemail.com"))) {// 判断是不是一个谷歌账户 + StringBuilder url = new StringBuilder(GTASK_URL).append("a/");//变为小写 + int index = mAccount.name.indexOf('@') + 1;//语句:返回@第一次出现的位置并把位置+1后记录在index里 + String suffix = mAccount.name.substring(index);//语句:substring() 方法用于提取字符串中介于两个指定下标之间的字符,此语句中index为start没有设置stop,所以提取了index开始到后面的字符,也就是账户名的后缀,例如qq.com 163.com之类的后缀 + url.append(suffix + "/");//均为字符串操作来构建url链接 + mGetUrl = url.toString() + "ig";//设置用户的getUrl + mPostUrl = url.toString() + "r/ig";//设置用户postURL + + if (tryToLoginGtask(activity, authToken)) {成功登入 + mLoggedin = true;//若不能使用用户域名登录,使用google官方url登录 + } + } + + // try to login with google official url//尝试使用谷歌的官方URL登录 + if (!mLoggedin) {//代码块: 若前面的尝试失败,则尝试使用官方的域名登陆 + mGetUrl = GTASK_GET_URL; + mPostUrl = GTASK_POST_URL; + if (!tryToLoginGtask(activity, authToken)) {//第二次登录失败,返回false + return false; + } + } + + mLoggedin = true;//如果没有报错就说明登陆成功 + return true; + } + + private String loginGoogleAccount(Activity activity, boolean invalidateToken) {//登陆Google的主函数,主要用于登陆成功后获取认证令牌 + String authToken; + AccountManager accountManager = AccountManager.get(activity);//在这里,账户管理器帮助我们集中管理注册账号 + Account[] accounts = accountManager.getAccountsByType("com.google");//获取谷歌账户 + + if (accounts.length == 0) {//如果没有这样的账号,输出日志信息“无有效的google账户” + Log.e(TAG, "there is no available google account");//显示没有该谷歌账户 + return null; + } + + String accountName = NotesPreferenceActivity.getSyncAccountName(activity);//代码块:匹配活动的账户里是否存在账户,存在的话把这个账户记在mAccount中,没有的话显示不能在设置中获取相同名字的账户 + Account account = null;//遍历account数组,寻找已登录过的信息 + for (Account a : accounts) {//找到后,为属性赋值 + if (a.name.equals(accountName)) {//没找到,输出例外信息 + account = a; + break; + } + } + if (account != null) {//若存在,把这个账户记在mAccount中;否则,显示“不能在设置中获取相同名字的账户”字样,并返回值为null的令牌 + mAccount = account;//若invalidateToken,则需调用invalidateAuthToken废除这个无效的token + } else { + Log.e(TAG, "unable to get an account with the same name in the settings");//语句: 若遍历完之后仍没有用户名匹配的账号,则直接返回 + return null; + } + + // get the token now//获取token + AccountManagerFuture accountManagerFuture = accountManager.getAuthToken(account,//getAuthToken方法: 获取令牌 + "goanna_mobile", null, activity, null, null); + try { + Bundle authTokenBundle = accountManagerFuture.getResult();//语句:bundle是一个key-value对,这里获取目标账户的最终结果集 + authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);//语句:这里获取bundle类的对象的String串并赋值给令牌对象 + if (invalidateToken) {//如果是非法的令牌,那么废除这个账号,取消登录状态 + accountManager.invalidateAuthToken("com.google", authToken);//删除存储AccountManager中此账号类型对应的authToken缓存,应用必须调用这个方法将缓存的authToken置为过期,否则getAuthToken获取到的一直是缓存的token + loginGoogleAccount(activity, false); + } + } catch (Exception e) {//捕捉令牌获取失败的异常 + Log.e(TAG, "get auth token failed");//错误,获取授权标记失败 + authToken = null;//tryToLoginGtask:尝试登录Gtask方法,这是一个试探方法,作为登录的预判 + } + + return authToken;//再次验证令牌。令牌可能是过期的,因此我们需要废除过期令牌 + } + + private boolean tryToLoginGtask(Activity activity, String authToken) {//方法:用于判断令牌对于登陆gtask账号是否有效 + if (!loginGtask(authToken)) {//代码块: 如果令牌不可用于登陆gtask账号,则需要重新登陆google账号获取令牌 + // maybe the auth token is out of date, now let's invalidate the//判断令牌对于登陆gtask账号是否有效 + // token and try again + authToken = loginGoogleAccount(activity, true);//删除过一个无效的authToken,申请一个新的后再次尝试登陆 + if (authToken == null) {//代码块:对再次登陆google账号失败的处理 + Log.e(TAG, "login google account failed");//错误,登录 google 帐户失败 + return false;//对再次登陆google账号失败的处理 + } + + if (!loginGtask(authToken)) {//代码块: 重新获取的令牌再次失效 + Log.e(TAG, "login gtask failed");//错误,登录 gtask 失败 + return false; + } + } + return true; + } + + private boolean loginGtask(String authToken) {//loginGtask:实现登录Gtask的方法 + int timeoutConnection = 10000;//连接超时为10000毫秒,即10秒 + int timeoutSocket = 15000;//socket:android与服务器的通信工具,与http的主要区别是,能够主动推送信息而不需要每次发送请求 + HttpParams httpParameters = new BasicHttpParams();//申请一个httpParameters参数类的对象 + HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//通过该方法设置连接超时的时间 + HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);//设置端口超时的时间 + mHttpClient = new DefaultHttpClient(httpParameters); + BasicCookieStore localBasicCookieStore = new BasicCookieStore();//为cookie申请存储对象 + mHttpClient.setCookieStore(localBasicCookieStore);//设置本地cookie + HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);//setUseExpectContinu方法:设置http协议1.1中的一个header属性Expect 100 Continue + + // login gtask//登录的实现 + try {//登录Gtask + String loginUrl = mGetUrl + "?auth=" + authToken;//设置登录的url以及令牌信息 + HttpGet httpGet = new HttpGet(loginUrl);//通过HttpGet向服务器申请 + HttpResponse response = null;//通过HttpGet向服务器申请 + response = mHttpClient.execute(httpGet);//从cookiestore中获取cookie + + // get the cookie now + List cookies = mHttpClient.getCookieStore().getCookies();//语句:获取cookie值 + boolean hasAuthCookie = false;//获取cookie值 + for (Cookie cookie : cookies) {//功能:遍历cookies集合中的每个Cookie对象,如果有一个Cookie对象的名中含有GTL,hasAuthCookie被赋给True + if (cookie.getName().contains("GTL")) {//验证cookie信息,这里通过GTL标志来验证 + hasAuthCookie = true;//验证cookie信息 + } + } + if (!hasAuthCookie) {//代码块:显示这是没有授权的cookie + Log.w(TAG, "it seems that there is no auth cookie");//显示没有授权的cookie + } + + // get the client version//获取client的版本号 + String resString = getResponseContent(response.getEntity());//获取客户端版本 + String jsBegin = "_setup(";//在取得的内容中,截取从_setup(到)}中间的部分,这是html语言格式,获取的是gtask_url + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin);//获取jsbegin中begin的序号 + int end = resString.lastIndexOf(jsEnd);//获取jsend中end的序号 + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + mClientVersion = js.getLong("v");//语句:设置客户端版本 + } catch (JSONException e) {//获取异常类型和异常详细消息 + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + return false; + } catch (Exception e) {//catch例外,GET失败 + // simply catch all exceptions + Log.e(TAG, "httpget gtask_url failed");//获取异常类型和异常详细消息 + return false; + } + + return true; + } + + private int getActionId() { + return mActionId++; + }//获取动作的id号码 + + private HttpPost createHttpPost() {//创建一个用来保存URL的httppost对象 + HttpPost httpPost = new HttpPost(mPostUrl);//创建一个httppost对象,用来保存URL + httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");//创建一个httppost对象保存URL + httpPost.setHeader("AT", "1"); + return httpPost; + } + + private String getResponseContent(HttpEntity entity) throws IOException {//getResponseContent:获取服务器响应的数据,主要通过方法getContentEncoding来获取网上资源,返回这些资源 + String contentEncoding = null;//通过URL得到HttpEntity对象,如果不为空则使用getContent方法创建一个流将数据从网络都过来 + if (entity.getContentEncoding() != null) {//代码块:如果获取的内容编码不为空,给内容编码赋值,显示encoding:内容编码 + contentEncoding = entity.getContentEncoding().getValue(); + Log.d(TAG, "encoding: " + contentEncoding);//gzip是使用deflate进行压缩数据的一个压缩库 + } + + InputStream input = entity.getContent(); + if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {//deflate是一种压缩算法,是huffman编码的一种加强 + input = new GZIPInputStream(entity.getContent()); + } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {//语句:deflate是一种压缩算法 + Inflater inflater = new Inflater(true); + input = new InflaterInputStream(entity.getContent(), inflater);//InflaterInputStream类:实现了一个流过滤器,用于以“deflate”压缩格式解压缩数据 + } + + try {//完成将字节流数据内容进行存储的功能 + InputStreamReader isr = new InputStreamReader(input);//InputStreamReader类:是从字节流到字符流的桥接器,它使用指定的字符集读取字节并将它们解码为字符 + BufferedReader br = new BufferedReader(isr);//缓存读取类,用于快速的读缓存操作 + StringBuilder sb = new StringBuilder(); + + while (true) {//将BufferedReader类br的内容逐行读取并存储StringBuilder类的sb中。然后返回sb的string格式。 + String buff = br.readLine(); + if (buff == null) { + return sb.toString(); + } + sb = sb.append(buff); + } + } finally { + input.close(); + } + } + + private JSONObject postRequest(JSONObject js) throws NetworkFailureException {//postRequest:利用JSON发送请求,返回获取的内容 + if (!mLoggedin) {//未登录,输出提示信息 + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + HttpPost httpPost = createHttpPost();//实例化一个httpPost的对象用来向服务器传输数据,发送在js里请求的内容 + try {//实例化一个对象,用于与服务器交互和发送请求 + LinkedList list = new LinkedList();//LinkedList 类:是一个继承于AbstractSequentialList的双向链表 + list.add(new BasicNameValuePair("r", js.toString())); + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");//形式比较单一,是普通的键值对"UTF-8" + httpPost.setEntity(entity);//语句:向httpPost对象中添加参数 + + // execute the post//响应请求 + HttpResponse response = mHttpClient.execute(httpPost);//执行请求 + String jsString = getResponseContent(response.getEntity()); + return new JSONObject(jsString); + + } catch (ClientProtocolException e) {//下面是几个异常 + Log.e(TAG, e.toString());//下面是对四种不同的异常出现时的处理 + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed");//post请求失败 + } catch (IOException e) {//post执行时发生异常 + Log.e(TAG, e.toString());//post执行时发生异常 + e.printStackTrace(); + throw new NetworkFailureException("postRequest failed");//createTask:创建一个任务对象 + } catch (JSONException e) {//创建任务 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("unable to convert response content to jsonobject"); + } catch (Exception e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("error occurs when posting request"); + } + } + + public void createTask(Task task) throws NetworkFailureException {//方法:创建Task,设置好action的链表、client_version、post + commitUpdate();//语句:提交更新 + try { + JSONObject jsPost = new JSONObject();//利用JSON获取Task中的内容,并创建相应的jspost + 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);//client的版本号 + + // post//通过postRequest获取任务的返回信息 + JSONObject jsResponse = postRequest(jsPost);//postRequest方法:获取任务的返回信息 + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) {//代码块:对异常情况的处理 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create task: handing jsonobject failed"); + } + } + + public void createTaskList(TaskList tasklist) throws NetworkFailureException {//createTaskList:创建任务列表,与createTask类似 + 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//post操作 + JSONObject jsResponse = postRequest(jsPost); + JSONObject jsResult = (JSONObject) jsResponse.getJSONArray( + GTaskStringUtils.GTASK_JSON_RESULTS).get(0); + tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID)); + + } catch (JSONException e) {//创建失败 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("create tasklist: handing jsonobject failed"); + } + } + + public void commitUpdate() throws NetworkFailureException {//提交更新数据,还是利用JSON + if (mUpdateArray != null) { + try {//新建JSONObject对象,使用jsPost.put( )添加对应关系,使用postRequest( )方法发送jspost,最后给mUpdateArray赋值NULL,表示现在没有内容要更新 + 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);//post操作 + mUpdateArray = null;//语句:更新处理完毕,列表置空 + } catch (JSONException e) {//代码块:对异常的处理 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("commit update: handing jsonobject failed"); + } + } + } + + public void addUpdateNode(Node node) throws NetworkFailureException {//添加更新节点,主要利用commitUpdate + if (node != null) {//更新太多内容可能导致出现异常 + // too many update items may result in an error + // set max to 10 items + if (mUpdateArray != null && mUpdateArray.length() > 10) {//提交后更新 + commitUpdate();//更新的阵列为空的话就使用JSONArray + } + + if (mUpdateArray == null) + mUpdateArray = new JSONArray(); + mUpdateArray.put(node.getUpdateAction(getActionId()));//语句:将更新节点加入列表 + } + } + + public void moveTask(Task task, TaskList preParent, TaskList curParent)//移动一个任务,通过getGid获取task所属的Id,还是通过JSONObject和postRequest实现 + throws NetworkFailureException {//把任务移动到指定的列表中 + commitUpdate();//方法:提交更新数据 + try { + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE, + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid()); + if (preParent == curParent && task.getPriorSibling() != null) {//只有当移动是发生在任务列表中且不是第一个时设置优先级 + // put prioring_sibing_id only if moving within the tasklist and + // it is not the first one + 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());//将动作列表放入jsPost中 + } + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);//用户版本 + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost);//postRequst()进行更新后的发送 + + } catch (JSONException e) {//代码块:异常处理 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("move task: handing jsonobject failed"); + } + } + + public void deleteNode(Node node) throws NetworkFailureException {//删除节点,过程类似移动 + commitUpdate(); + try {//代码块:新建jsPost,把除了node的其他节点都放入jsPost,并提交 + JSONObject jsPost = new JSONObject(); + JSONArray actionList = new JSONArray(); + + // action_list + node.setDeleted(true); + actionList.put(node.getUpdateAction(getActionId()));// 语句:将该节点要更新的操作的id加入操作列表 + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + postRequest(jsPost); + mUpdateArray = null; + } catch (JSONException e) {//代码块:异常处理 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("delete node: handing jsonobject failed"); + } + } + + public JSONArray getTaskLists() throws NetworkFailureException {//获取任务列表,首先通过getURI在网上获取数据,在截取所需部分内容返回 + if (!mLoggedin) {//检查是否在登录状态 + Log.e(TAG, "please login first"); + throw new ActionFailureException("not logged in"); + } + + try {//使用url实例化一个获取对象 + HttpGet httpGet = new HttpGet(mGetUrl);//通过发送HttpPost请求访问HTTP资源 + HttpResponse response = null;//语句:初始化Httpresponse (回复)为空 + response = mHttpClient.execute(httpGet);//语句:使用httpget发送一个请求,返回一个response对象 + + // get the task list//代码块:获取任务链表,判断resString的开头结尾格式对不对,正确的话则重建一个字符串赋值给jsString,然后用jsString新建一个JSONObject对象js,并通过js调用一系列方法把任务列表返回 + String resString = getResponseContent(response.getEntity());//获取任务列表 + String jsBegin = "_setup(";//截取字符串并放入到jsString里 + String jsEnd = ")}"; + int begin = resString.indexOf(jsBegin); + int end = resString.lastIndexOf(jsEnd); + String jsString = null; + if (begin != -1 && end != -1 && begin < end) { + jsString = resString.substring(begin + jsBegin.length(), end); + } + JSONObject js = new JSONObject(jsString); + return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);//获取GTASK_JSON_LISTS + } catch (ClientProtocolException e) {//捕捉httpget失败异常 + Log.e(TAG, e.toString());//处理异常 + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (IOException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new NetworkFailureException("gettasklists: httpget failed"); + } catch (JSONException e) { + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task lists: handing jasonobject failed"); + } + } + + public JSONArray getTaskList(String listGid) throws NetworkFailureException {//方法:对于已经获取的任务列表,可以通过其id来获取到 + commitUpdate(); + try {//设置为传入的listGid + JSONObject jsPost = new JSONObject();//设置为传入的listGid + JSONArray actionList = new JSONArray(); + JSONObject action = new JSONObject(); + + // action_list + action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,//通过action.pu()t对JSONObject对象action添加元素,通过jsPost.put()对jsPost添加相关元素,然后通过postRequest()提交更新后的请求并返回一个JSONObject的对象,最后使用jsResponse.getJSONArray( )获取jsResponse中的JSONArray值并作为函数返回值 + GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL); + action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId()); + action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);//这里设置为传入的listGid + action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false); + actionList.put(action); + jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList); + + // client_version + jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion); + + JSONObject jsResponse = postRequest(jsPost); + return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS); + } catch (JSONException e) {//代码块:处理异常 + Log.e(TAG, e.toString()); + e.printStackTrace(); + throw new ActionFailureException("get task list: handing jsonobject failed"); + } + } + + public Account getSyncAccount() { + return mAccount; + }//获得同步账户。 + + public void resetUpdateArray() { + mUpdateArray = null; + }//重置更新内容 +} diff --git a/doc/精读报告/gtask/remote/GTaskManager.doc b/doc/精读报告/gtask/remote/GTaskManager.doc new file mode 100644 index 0000000..d0ad4ed --- /dev/null +++ b/doc/精读报告/gtask/remote/GTaskManager.doc @@ -0,0 +1,800 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.gtask.remote;//实现同步功能的主函数 + +import android.app.Activity;//在包里引用各种类 +import android.content.ContentResolver; +import android.content.ContentUris; +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.util.Log; + +import net.micode.notes.R;//引用小米便签中的类 +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.gtask.data.MetaData; +import net.micode.notes.gtask.data.Node; +import net.micode.notes.gtask.data.SqlNote; +import net.micode.notes.gtask.data.Task; +import net.micode.notes.gtask.data.TaskList; +import net.micode.notes.gtask.exception.ActionFailureException; +import net.micode.notes.gtask.exception.NetworkFailureException; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.GTaskStringUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + + +public class GTaskManager {//声明一个类,类名称的命名规范:所有单词的首字母大写 + private static final String TAG = GTaskManager.class.getSimpleName();//定义了一系列静态变量来显示GTask当前的状态(1)设置GTask的TAG + + public static final int STATE_SUCCESS = 0;//成功 + + public static final int STATE_NETWORK_ERROR = 1;//网络错误 + + public static final int STATE_INTERNAL_ERROR = 2;//内部错误 + + public static final int STATE_SYNC_IN_PROGRESS = 3;//进程同步中 + + public static final int STATE_SYNC_CANCELLED = 4;//取消同步 + + private static GTaskManager mInstance = null;//private 定义一系列不可被外部的类访问的量 + + private Activity mActivity;//构造函数 + + private Context mContext; + + private ContentResolver mContentResolver; + + private boolean mSyncing; + + private boolean mCancelled; + + private HashMap mGTaskListHashMap; + + private HashMap mGTaskHashMap; + + private HashMap mMetaHashMap; + + private TaskList mMetaList; + + private HashSet mLocalDeleteIdMap; + + private HashMap mGidToNid; + + private HashMap mNidToGid; + + private GTaskManager() {//方法:类的构造函数,对其内部变量进行初始化 + mSyncing = false;//正在同步标识,false代表未同步 + mCancelled = false; + mGTaskListHashMap = new HashMap();//全局标识,flase代表可以执行 + mGTaskHashMap = new HashMap();//<>代表Java的泛型,就是创建一个用类型作为参数的类。 + mMetaHashMap = new HashMap();//创建一个删除本地ID的map + mMetaList = null;//创建一个删除本地ID的map + mLocalDeleteIdMap = new HashSet(); + mGidToNid = new HashMap();//建立一个google id到节点id的映射 + mNidToGid = new HashMap();//创建一个节点id到google id的映射 + } + + public static synchronized GTaskManager getInstance() {//synchronized指明该函数可以运行在多线程下 + if (mInstance == null) {//初始化mInstance + mInstance = new GTaskManager();//初始化 + } + return mInstance; + } + + public synchronized void setActivityContext(Activity activity) {//对类的当前实例进行加锁,防止其他线程同时访问该类的该实例的所有synchronized块 + // used for getting authtoken//获得操作指令 + mActivity = activity; + } + + public int sync(Context context, GTaskASyncTask asyncTask) {//实现本地和远程同步的操作 + if (mSyncing) {//正在同步时,日志中写入正在同步 + Log.d(TAG, "Sync is in progress");//debug,进程已在同步中 + return STATE_SYNC_IN_PROGRESS;//返回同步状态 + } + mContext = context;//代码块:对同步时GTaskManager的属性进行更新 + mContentResolver = mContext.getContentResolver();//对GTaskManager的属性进行更新 + mSyncing = true;//初始化各种标志变量 + mCancelled = false; + mGTaskListHashMap.clear();//各种环境清空 + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + + try {//异常处理程序 + GTaskClient client = GTaskClient.getInstance();//创建一个用户的实例 + client.resetUpdateArray();//getInstance即为创建一个实例 + + // login google task //更新数组操作 + if (!mCancelled) {//登陆用户端 + if (!client.login(mActivity)) {//执行登录程序,登录到google task + 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();//调用下面自定义的方法,初始化GTaskList + + // do content sync work + asyncTask.publishProgess(mContext.getString(R.string.sync_progress_syncing)); + syncContent();//同步便签内容 + } catch (NetworkFailureException e) {//网络连接中断 + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + return STATE_NETWORK_ERROR; + } catch (ActionFailureException e) {//操作未完成 + Log.e(TAG, e.toString()); + return STATE_INTERNAL_ERROR; + } catch (Exception e) {//处理各种异常 + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + return STATE_INTERNAL_ERROR; + } finally {//代码块:在同步操作结束之后,更新GTaskManager的属性 + mGTaskListHashMap.clear();//同步结束后清空环境 + mGTaskHashMap.clear(); + mMetaHashMap.clear(); + mLocalDeleteIdMap.clear(); + mGidToNid.clear(); + mNidToGid.clear(); + mSyncing = false; + } + + return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;//语句:若在同步时操作未取消,则说明同步成功,否则返回同步操作取消 + } + + private void initGTaskList() throws NetworkFailureException {//初始化GTask列表,将google上的JSONTaskList转为本地任务列表 + if (mCancelled)//是否中途取消 + return; + GTaskClient client = GTaskClient.getInstance();//创建一个用户的实例 + try {//客户端获取任务列表 + JSONArray jsTaskLists = client.getTaskLists();//客户端获取任务列表jsTaskLists + + // init meta list first + mMetaList = null;//初始化元数据列表 + for (int i = 0; i < jsTaskLists.length(); i++) {//代码块:对获取到任务列表中的每一个元素进行操作 + JSONObject object = jsTaskLists.getJSONObject(i);//取出单个JSON对象 + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);//获取它的id + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);//获取它的名字 + + if (name + .equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_META)) {//如果 name 等于 字符串 "[MIUI_Notes]" + "METADATA",执行if语句块 + mMetaList = new TaskList();//新建数组,并为新建的数组设定内容 + mMetaList.setContentByRemoteJSON(object);//新建一个元数据列表 + + // load meta data + JSONArray jsMetas = client.getTaskList(gid);//将JSON中部分数据复制到自己定义的对象中相对应的数据:name->mname... + for (int j = 0; j < jsMetas.length(); j++) {//代码块:把jsMetas里的每一个有识别码的metaData都放到哈希表中 + object = (JSONObject) jsMetas.getJSONObject(j);//获取一个JSON类型的对象 + MetaData metaData = new MetaData();//新建一个Metadata + metaData.setContentByRemoteJSON(object);//新建MetaData + if (metaData.isWorthSaving()) {//需要保存时,将子任务加入到主任务中 + mMetaList.addChildTask(metaData);//新建一个元数据列表。 + if (metaData.getGid() != null) {//操作getGid:取得组识别码函数 + mMetaHashMap.put(metaData.getRelatedGid(), metaData);//语句:把元数据放到哈希表中 + } + } + } + } + } + + // create meta list if not existed + if (mMetaList == null) {//代码块:若元数据列表不存在则创建一个 + mMetaList = new TaskList();//元数据列表不存在,则在客户端创建一个 + mMetaList.setName(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META); + GTaskClient.getInstance().createTaskList(mMetaList); + } + + // init task list + for (int i = 0; i < jsTaskLists.length(); i++) {//以下循环用于初始化任务列表 + JSONObject object = jsTaskLists.getJSONObject(i);//代码块:先获取列表中每一个节点的属性 + String gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);//通过getString函数传入本地某个标志数据的名称,获取其在远端的名称 + String name = object.getString(GTaskStringUtils.GTASK_JSON_NAME);//获取JSON名字 + + if (name.startsWith(GTaskStringUtils.MIUI_FOLDER_PREFFIX) + && !name.equals(GTaskStringUtils.MIUI_FOLDER_PREFFIX + + GTaskStringUtils.FOLDER_META)) { + TaskList tasklist = new TaskList();//语句: 创建一个新的任务列表 + tasklist.setContentByRemoteJSON(object);//语句:对任务列表的内容进行设置 + mGTaskListHashMap.put(gid, tasklist);//对任务列表的内容进行设置 + mGTaskHashMap.put(gid, tasklist); + + // load tasks + JSONArray jsTasks = client.getTaskList(gid);//获取任务id号 + for (int j = 0; j < jsTasks.length(); j++) {//任务id号 + object = (JSONObject) jsTasks.getJSONObject(j); + gid = object.getString(GTaskStringUtils.GTASK_JSON_ID);//语句:获取当前任务的gid + Task task = new Task(); + task.setContentByRemoteJSON(object);//语句:设置任务内容 + if (task.isWorthSaving()) {//语句:判断该任务有无价值保存 + task.setMetaInfo(mMetaHashMap.get(gid));//判断该任务是否有价值 + tasklist.addChildTask(task); + mGTaskHashMap.put(gid, task); + } + } + } + } + } catch (JSONException e) {//初始化时捕捉异常 + Log.e(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + throw new ActionFailureException("initGTaskList: handing JSONObject failed");//抛出异常,提交 JSONObject 失败 + } + } + + private void syncContent() throws NetworkFailureException {//实现内容同步 + int syncType;//本地内容同步操作 + Cursor c = null;//同步操作类 + String gid; + Node node;//Node包含Sync_Action的不同类型 + + 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[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, null); + if (c != null) {//代码块:若获取到的待删除便签不为空,则进行同步操作 + while (c.moveToNext()) {//通过while用指针遍历所有结点 + gid = c.getString(SqlNote.GTASK_ID_COLUMN);//语句:获取待删除便签的gid + node = mGTaskHashMap.get(gid);//语句:获取待删除便签的节点 + if (node != null) {//节点非空则从哈希表里删除,并进行同步操作 + mGTaskHashMap.remove(gid);//语句:将待删除的节点对应的google id从映射表中移除 + doContentSync(Node.SYNC_ACTION_DEL_REMOTE, node, c);//语句:在远程删除对应节点 + } + + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN));//查找不到时,在日志中记录信息 + } + } else {//若c结点为空,即寻找错误的时候,报错 + Log.w(TAG, "failed to query trash folder");//警告,询问垃圾文件夹失败 + } + } finally {//代码块:最后把c关闭并重置代码块: + if (c != null) {//结束操作之后,将指针指向内容关闭并将指针置空 + c.close();//记得关闭 cursor 所指文件 + c = null;//cursor 置空 + } + } + + // sync folder first + syncFolder();//语句:对文件夹进行同步 + + // for note existing in database + try {//对于数据库中已经存在的便签,采取以下操作 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,//语句:使c指针指向待操作的便签位置 + "(type=? AND parent_id<>?)", new String[] {//c指针指向待操作的位置 + String.valueOf(Notes.TYPE_NOTE), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) {//query语句的用法 + while (c.moveToNext()) {//语句:指针向后移动 + gid = c.getString(SqlNote.GTASK_ID_COLUMN);//语句:获取待操作的便签的gid + node = mGTaskHashMap.get(gid);//语句:获取待操作的便签的节点 + if (node != null) {//若结点不为空,将其对应的google id从映射表中移除,然后建立google id到节点id的映射(通过hashmap)、gid和nid之间的映射表 + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));//建立google id到节点id的映射 + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);//通过hashmap建立联系 + syncType = node.getSyncAction(c);//语句:更新此时的同步类型 + } else {//代码块:如果note是空的,则判断c的trim()的长度是否为0,如果是则设置同步类型为ADD REMOTE,否则设置为DEL LOCAL + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {//语句:若本地增加了内容,则远程也要增加内容 + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE;//远程增加内容 + } else {//语句:若本地删除了内容,则远程也要删除内容应的gid + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL;//本地删除 + } + } + doContentSync(syncType, node, c);//进行同步操作 + } + } else { + Log.w(TAG, "failed to query existing note in database");//查询失败时在日志中写回错误信息 + } + + } finally {//代码块:在最后关闭c并重置 + if (c != null) {//代码块:结束操作之后,将指针指向内容关闭并将指针置空 + c.close();//关闭 cursor 所指文件 + c = null;//cursor 置空 + } + } + + // go through remaining items + Iterator> iter = mGTaskHashMap.entrySet().iterator();//扫描剩下的项目,逐个进行同步 + while (iter.hasNext()) {//迭代 + Map.Entry entry = iter.next(); + node = entry.getValue();//getValue()可以获取指定对象的属性值 + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);//语句:在本地增加这些节点 + } + + // mCancelled can be set by another thread, so we neet to check one by + // one + // clear local delete table + if (!mCancelled) { + if (!DataUtils.batchDeleteNotes(mContentResolver, mLocalDeleteIdMap)) {//语句:终止标识有可能被其他进程改变,因此需要一个个进行检查 + throw new ActionFailureException("failed to batch-delete local deleted notes");//终止标识有可能被其他线程改变 + } + } + + // refresh local sync id + if (!mCancelled) {//更新同步表 + GTaskClient.getInstance().commitUpdate();//更新同步表 + refreshLocalSyncId();//更新同步的id + } + + } + + private void syncFolder() throws NetworkFailureException {//同步文件夹 + Cursor c = null;//同步文件夹 + String gid; + Node node; + int syncType; + + if (mCancelled) {//语句:判断是否取消该操作 + return; + } + + // for root folder + try {//对于根文件夹 + c = mContentResolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI,//语句:使指针指向根文件夹的位置 + Notes.ID_ROOT_FOLDER), SqlNote.PROJECTION_NOTE, null, null, null);//使指针指向根文件夹的位置 + if (c != null) { + c.moveToNext(); + gid = c.getString(SqlNote.GTASK_ID_COLUMN);//语句:获取指针指向内容对应的gid + node = mGTaskHashMap.get(gid);//语句:获取该gid所代表的节点 + if (node != null) {//获取gid所代表的节点 + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_ROOT_FOLDER);//语句:将该节点的gid到nid的映射加入映射表 + mNidToGid.put((long) Notes.ID_ROOT_FOLDER, gid); + // for system folder, only update remote name if necessary + if (!node.getName().equals(//添加MIUI文件前缀 + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);//语句:若非系统文件夹则在远程进行增加节点操作 + } + } else { + Log.w(TAG, "failed to query root folder");//出现异常时,在日志中写回出错信息 + } + } finally {//结束操作之后,最后将指针关闭,并将指针置空。方法与之前相同 + if (c != null) {//代码块:结束操作之后,将指针指向内容关闭并将指针置空 + c.close();//关闭 cursor 所指文件 + c = null;//cursor 置空 + } + } + + // for call-note folder + try {//对于电话号码数据文件 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, "(_id=?)",//语句:使指针指向文件夹的位置 + new String[] {//添加MIUI文件前缀 + String.valueOf(Notes.ID_CALL_RECORD_FOLDER)//添加MIUI文件前缀 + }, null); + if (c != null) { + if (c.moveToNext()) { + gid = c.getString(SqlNote.GTASK_ID_COLUMN);//语句:获取指针指向内容对应的gid + node = mGTaskHashMap.get(gid);//语句:获取指针指向内容对应的gid + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, (long) Notes.ID_CALL_RECORD_FOLDER);//语句:将该节点的gid到nid的映射加入映射表 + mNidToGid.put((long) Notes.ID_CALL_RECORD_FOLDER, gid); + // for system folder, only update remote name if + // necessary + if (!node.getName().equals(//语句:若当前访问的文件夹是系统文件夹则只需要更新 + GTaskStringUtils.MIUI_FOLDER_PREFFIX//若当前访问的文件夹是系统文件夹则只需更新 + + GTaskStringUtils.FOLDER_CALL_NOTE)) + doContentSync(Node.SYNC_ACTION_UPDATE_REMOTE, node, c); + } else { + doContentSync(Node.SYNC_ACTION_ADD_REMOTE, node, c);//语句:若非系统文件夹则在远程进行增加节点操作 + } + } + } else { + Log.w(TAG, "failed to query call note folder");//警告,询问通讯便签文件夹失败 + } + } finally { + if (c != null) {//代码块:结束操作之后,将指针指向内容关闭并将指针置空 + c.close();//关闭 cursor 所指文件 + c = null;//cursor 置空 + } + } + + // for local existing folders + try {//对于本地已存在的文件的操作 + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE,// 语句:使指针指向第一个文件夹的位置 + "(type=? AND parent_id<>?)", new String[] {//使指针指向第一个文件夹的位置 + String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC"); + if (c != null) { + while (c.moveToNext()) {//语句:使指针遍历所有的文件夹 + gid = c.getString(SqlNote.GTASK_ID_COLUMN); + node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + mGidToNid.put(gid, c.getLong(SqlNote.ID_COLUMN));//语句:获取指针指向内容对应的gid + mNidToGid.put(c.getLong(SqlNote.ID_COLUMN), gid);//语句:获取指针指向内容对应的gid + syncType = node.getSyncAction(c);//语句:更新同步类型 + } else {//更新同步类型 + if (c.getString(SqlNote.GTASK_ID_COLUMN).trim().length() == 0) {//语句:若本地增加了内容,则远程也要增加内容 + // local add + syncType = Node.SYNC_ACTION_ADD_REMOTE;//远程添加 + } else {//语句:若远程删除了内容,则本地也要删除内容 + // remote delete + syncType = Node.SYNC_ACTION_DEL_LOCAL;//本地删除 + } + } + doContentSync(syncType, node, c);//语句:进行同步操作 + } + } else {//进行同步操作 + Log.w(TAG, "failed to query existing folder");//警告,询问已创建的文件夹失败 + } + } finally { + if (c != null) {//代码块:结束操作之后,将指针指向内容关闭并将指针置空 + c.close();//关闭 cursor 所指文件 + c = null;//cursor 置空 + } + } + + // for remote add folders + Iterator> iter = mGTaskListHashMap.entrySet().iterator();//远程添加文件需要执行的操作 + while (iter.hasNext()) {//语句:使用迭代器对远程增添的内容进行遍 + Map.Entry entry = iter.next(); + gid = entry.getKey();//语句:获取对应的gid + node = entry.getValue();//语句:获取gid对应的节点 + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + doContentSync(Node.SYNC_ACTION_ADD_LOCAL, node, null);//语句:进行本地增添操作 + } + } + + if (!mCancelled) + GTaskClient.getInstance().commitUpdate();//语句:如果没有取消,在GTsk的客户端进行实例的提交更新 + } + + private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {//功能:syncType分类 + if (mCancelled) {//进行本地增添操作 + return; + } + + MetaData meta; + switch (syncType) {//根据同步类型选择操作 + case Node.SYNC_ACTION_ADD_LOCAL://远程添加 + addLocalNode(node);//本地添加 + break; + case Node.SYNC_ACTION_ADD_REMOTE://本地删除 + addRemoteNode(node, c);//本地删除 + break; + case Node.SYNC_ACTION_DEL_LOCAL://远程删除 + meta = mMetaHashMap.get(c.getString(SqlNote.GTASK_ID_COLUMN)); + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + mLocalDeleteIdMap.add(c.getLong(SqlNote.ID_COLUMN)); + break; + case Node.SYNC_ACTION_DEL_REMOTE://更新本地数据 + meta = mMetaHashMap.get(node.getGid());//更新本地数据 + if (meta != null) { + GTaskClient.getInstance().deleteNode(meta); + } + GTaskClient.getInstance().deleteNode(node); + break; + case Node.SYNC_ACTION_UPDATE_LOCAL://更新远程数据 + updateLocalNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_REMOTE: + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_UPDATE_CONFLICT://同步出错 + // merging both modifications maybe a good idea + // right now just use local update simply + updateRemoteNode(node, c); + break; + case Node.SYNC_ACTION_NONE://代码块:空操作 + break;//空操作 + case Node.SYNC_ACTION_ERROR://代码块:操作错误 + default://代码块:default:同步类型不在规定的类型范围内 + throw new ActionFailureException("unkown sync action type");//抛出异常,未知的同步行为类型 + } + } + + private void addLocalNode(Node node) throws NetworkFailureException {//功能:本地增加Node + if (mCancelled) {//这个函数是添加本地结点,参数node即为要添加的本地结点 + return; + } + + SqlNote sqlNote; + if (node instanceof TaskList) {//节点是任务列表中的一个节点 + if (node.getName().equals(//代码块:在根目录中增加节点 + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_DEFAULT)) { + sqlNote = new SqlNote(mContext, Notes.ID_ROOT_FOLDER); + } else if (node.getName().equals(//代码块:在存放电话号码便签的文件夹中增加节点 + GTaskStringUtils.MIUI_FOLDER_PREFFIX + GTaskStringUtils.FOLDER_CALL_NOTE)) { + sqlNote = new SqlNote(mContext, Notes.ID_CALL_RECORD_FOLDER); + } else {//代码块:如果在其他文件夹里则用一般操作设置sqlNote的参数 + sqlNote = new SqlNote(mContext);//代码块:若没有存放的文件夹,则将其放在根文件夹中 + sqlNote.setContent(node.getLocalJSONFromContent());//从本地任务列表中获取内容 + sqlNote.setParentId(Notes.ID_ROOT_FOLDER); + } + } else {//代码块:若待增添节点不是任务列表中的节点,进一步操作 + sqlNote = new SqlNote(mContext); + JSONObject js = node.getLocalJSONFromContent();//语句:从待增添节点中获取jsonobject对象 + try {//异常判断 + if (js.has(GTaskStringUtils.META_HEAD_NOTE)) { + JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);//语句:获取对应便签的jsonobject对象 + if (note.has(NoteColumns.ID)) {//语句:判断便签中是否有条目 + long id = note.getLong(NoteColumns.ID); + if (DataUtils.existInNoteDatabase(mContentResolver, id)) {//id存在时删除id + // the id is not available, have to create a new one + note.remove(NoteColumns.ID); + } + } + } + + if (js.has(GTaskStringUtils.META_HEAD_DATA)) {//以下为判断便签中的数据条目 + JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); + for (int i = 0; i < dataArray.length(); i++) {//依次删除存在的data的ID + JSONObject data = dataArray.getJSONObject(i);//语句:获取对应数据的jsonobject对象 + if (data.has(DataColumns.ID)) {//语句:判断数据中是否有条目 + long dataId = data.getLong(DataColumns.ID); + if (DataUtils.existInDataDatabase(mContentResolver, dataId)) {//data id存在时删除已建立的对应ID + // the data id is not available, have to create + // a new one + data.remove(DataColumns.ID); + } + } + } + + } + } catch (JSONException e) {//出现异常时,打印异常信息 + Log.w(TAG, e.toString());//获取异常类型和异常详细消息 + e.printStackTrace(); + } + sqlNote.setContent(js);//语句:将之前的操作获取到的js更新至该节点中 + + Long parentId = mGidToNid.get(((Task) node).getParent().getGid());//代码块:找到父任务的ID号,并作为sqlNote的父任务的ID,没有父任务则报错 + if (parentId == null) {//语句:当不能找到该任务上一级的id时报错 + Log.e(TAG, "cannot find task's parent id locally");//本地无法找到父进程id + throw new ActionFailureException("cannot add local node");//报告无法添加本地节点 + } + sqlNote.setParentId(parentId.longValue()); + } + + // create the local node + sqlNote.setGtaskId(node.getGid());//设置google task id + sqlNote.commit(false);//更新本地便签 + + // update gid-nid mapping + mGidToNid.put(node.getGid(), sqlNote.getId());//语句:更新gid与nid的映射表 + mNidToGid.put(sqlNote.getId(), node.getGid()); + + // update meta + updateRemoteMeta(node.getGid(), sqlNote);//语句:更新远程的数据 + } + + private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {//函数:更新本地节点,两个传入参数,一个是待更新的节点,一个是指向待增加位置的指针 + if (mCancelled) {//如果正在取消同步,直接返回 + return; + } + + SqlNote sqlNote;//新建一个sql节点并将内容存储进Node中 + // update the note locally + sqlNote = new SqlNote(mContext, c);//语句:在指针指向处创建一个新的节点 + sqlNote.setContent(node.getLocalJSONFromContent());//语句:利用待更新节点中的内容对数据库节点进行设置 + + Long parentId = (node instanceof Task) ? mGidToNid.get(((Task) node).getParent().getGid())//语句: 设置父任务的ID,通过判断node是不是Task的实例 + : new Long(Notes.ID_ROOT_FOLDER); + if (parentId == null) {//语句:当不能找到该任务上一级的id时报错 + Log.e(TAG, "cannot find task's parent id locally");//错误,不能在本地找到任务的父 id + throw new ActionFailureException("cannot update local node");//抛出异常,不能更新本地节点 + } + sqlNote.setParentId(parentId.longValue());//设置该任务节点上一级的id + sqlNote.commit(true);//抛出异常,不能更新本地节点 + + // update meta info + updateRemoteMeta(node.getGid(), sqlNote);//升级meta + } + + private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {//添加远程节点 + if (mCancelled) {//如果正在取消同步,直接返回 + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c);//新建一个sql节点并将内容存储进Node中 + Node n; + + // update remotely + if (sqlNote.isNoteType()) {//语句:若待增添的节点为任务节点,进一步操作 + Task task = new Task(); + task.setContentByLocalJSON(sqlNote.getContent()); + + String parentGid = mNidToGid.get(sqlNote.getParentId());//找不到parentID时,报错 + if (parentGid == null) { + Log.e(TAG, "cannot find task's parent tasklist");//错误,无法找到任务的父列表 + throw new ActionFailureException("cannot add remote task");//抛出异常,无法添加云端任务 + } + mGTaskListHashMap.get(parentGid).addChildTask(task);//在本地生成的GTaskList中增加子结点 + + GTaskClient.getInstance().createTask(task);//在本地生成的GTaskList中增加子结点 + n = (Node) task; + + // add meta//添加元数据 + updateRemoteMeta(task.getGid(), sqlNote); + } else { + TaskList tasklist = null; + + // we need to skip folder if it has already existed//当文件夹存在则跳过,若不存在则创建新的文件夹 + String folderName = GTaskStringUtils.MIUI_FOLDER_PREFFIX;//代码块:当文件夹已经存在则跳过处理,若不存在则创建新的文件夹 + if (sqlNote.getId() == Notes.ID_ROOT_FOLDER)//按照文件夹的形式进行命名 + folderName += GTaskStringUtils.FOLDER_DEFAULT;//语句:若为根文件夹则按根文件夹命名 + else if (sqlNote.getId() == Notes.ID_CALL_RECORD_FOLDER) + folderName += GTaskStringUtils.FOLDER_CALL_NOTE;//语句:若为电话号码便签文件夹则按电话号码便签命名 + else + folderName += sqlNote.getSnippet(); + + Iterator> iter = mGTaskListHashMap.entrySet().iterator();//使用iterator作为map接口,对map进行遍历 + while (iter.hasNext()) {//iterator迭代器,通过统一的接口迭代所有的map元素 + Map.Entry entry = iter.next(); + String gid = entry.getKey(); + TaskList list = entry.getValue(); + + if (list.getName().equals(folderName)) {//代码块:若寻找到的任务列表已存在,则直接在里面更新 + tasklist = list;//找不到可以匹配的任务链 + if (mGTaskHashMap.containsKey(gid)) { + mGTaskHashMap.remove(gid); + } + break; + } + } + + // no match we can add now + if (tasklist == null) {//若没有匹配的任务列表,则创建一个新的任务列表 + tasklist = new TaskList();//直接新建一个任务链 + tasklist.setContentByLocalJSON(sqlNote.getContent()); + GTaskClient.getInstance().createTaskList(tasklist); + mGTaskListHashMap.put(tasklist.getGid(), tasklist); + } + n = (Node) tasklist; + } + + // update local note//进行本地节点的更新 + sqlNote.setGtaskId(n.getGid());//创建id间的映射 + sqlNote.commit(false); + sqlNote.resetLocalModified(); + sqlNote.commit(true); + + // gid-id mapping//进行gid与nid映射关系的更新 + mGidToNid.put(n.getGid(), sqlNote.getId());//代码块:更新gid-nid映射表 + mNidToGid.put(sqlNote.getId(), n.getGid()); + } + + private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {//更新远程节点 + if (mCancelled) {//如果正在取消同步,直接返回 + return; + } + + SqlNote sqlNote = new SqlNote(mContext, c);//语句:在指针指向处创建一个新的节点 + + // update remotely + node.setContentByLocalJSON(sqlNote.getContent());//代码块:远程更新 + GTaskClient.getInstance().addUpdateNode(node);//GTaskClient用途为从本地登陆远端服务器 + + // update meta + updateRemoteMeta(node.getGid(), sqlNote);//语句:更新数据 + + // move task if necessary + if (sqlNote.isNoteType()) {//判断节点类型是否符合要求 + Task task = (Task) node;//新建一个task节点 + TaskList preParentList = task.getParent();//找到当前任务列表的父节点google id和之前父任务链 + + String curParentGid = mNidToGid.get(sqlNote.getParentId());//curParentGid为通过光标在数据库中找到sqlNote的mParentId,再通过mNidToGid由long类型转为String类型的Gid + if (curParentGid == null) {//代码块:找不到当前任务的上一级任务列表,报错 + Log.e(TAG, "cannot find task's parent tasklist");//错误,无法找到任务的父列表 + throw new ActionFailureException("cannot update remote task");//抛出异常,无法添加云端任务 + } + TaskList curParentList = mGTaskListHashMap.get(curParentGid);//通过HashMap找到对应Gid的TaskList + + if (preParentList != curParentList) {//语句:若两个上一级任务列表不一致,进行任务的移动,从之前的任务列表中移动到该列表中 + preParentList.removeChildTask(task); + curParentList.addChildTask(task); + GTaskClient.getInstance().moveTask(task, preParentList, curParentList); + } + } + + // clear local modified flag + sqlNote.resetLocalModified();//清除本地的modified flag + sqlNote.commit(true); + } + + private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {//更新远程元数组的google id和数据库节点 + if (sqlNote != null && sqlNote.isNoteType()) {//判断节点类型是否符合,类型符合时才进行更新操作 + MetaData metaData = mMetaHashMap.get(gid);//从google id获取任务列表 + if (metaData != null) {//语句:若元数据组为空,则创建一个新的元数据组 + metaData.setMeta(gid, sqlNote.getContent());//任务列表不存在时 新建一个空的任务列表,并将其放入google id中 + GTaskClient.getInstance().addUpdateNode(metaData); + } else {//语句:若元数据组不为空,则进行更新 + metaData = new MetaData(); + metaData.setMeta(gid, sqlNote.getContent()); + mMetaList.addChildTask(metaData); + mMetaHashMap.put(gid, metaData); + GTaskClient.getInstance().createTask(metaData); + } + } + } + + private void refreshLocalSyncId() throws NetworkFailureException {//刷新本地便签id,从远程同步 + if (mCancelled) { + return; + }//获取最近的gtask list + + // get the latest gtask list//获取最新的gtask列表 + mGTaskHashMap.clear();//否则,初始化hash表 + mGTaskListHashMap.clear(); + mMetaHashMap.clear(); + initGTaskList(); + + Cursor c = null; + try { + c = mContentResolver.query(Notes.CONTENT_NOTE_URI, SqlNote.PROJECTION_NOTE, + "(type<>? AND parent_id<>?)", new String[] { + String.valueOf(Notes.TYPE_SYSTEM), String.valueOf(Notes.ID_TRASH_FOLER) + }, NoteColumns.TYPE + " DESC");//query语句:五个参数,NoteColumns.TYPE + " DESC"-----为按类型递减顺序返回查询结果。newString[{String.valueOf(Notes.TYPE_SYSTEM),String.valueOf(Notes.ID_TRASH_FOLER)}------为选择参数。"(type<>? AND parent_id<>?)"-------指明返回行过滤器。SqlNote.PROJECTION_NOTE--------应返回的数据列的名字。Notes.CONTENT_NOTE_URI--------contentProvider包含所有数据集所对应的uri + if (c != null) { + while (c.moveToNext()) {//获取最新的GTask列表 + String gid = c.getString(SqlNote.GTASK_ID_COLUMN); + Node node = mGTaskHashMap.get(gid); + if (node != null) { + mGTaskHashMap.remove(gid); + ContentValues values = new ContentValues(); + values.put(NoteColumns.SYNC_ID, node.getLastModified());//在ContentValues中创建键值对。准备通过contentResolver写入数据 + mContentResolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, + c.getLong(SqlNote.ID_COLUMN)), values, null, null); + } else { + Log.e(TAG, "something is missed");//错误,部分内容丢失 + throw new ActionFailureException( + "some local items don't have gid after sync"); + } + } + } else {//进行批量更改,选择参数为NULL,应该可以用insert替换,参数分别为表名和需要更新的value对象。 + Log.w(TAG, "failed to query local note to refresh sync id");//警告,询问本地待同步更新的便签 id 失败 + } + } finally { + if (c != null) { + c.close(); + c = null; + } + } + } + + public String getSyncAccount() { + return GTaskClient.getInstance().getSyncAccount().name;//返回待同步帐户的名称 + }//获取同步账号 + + public void cancelSync() { + mCancelled = true; + }//取消同步,置mCancelled为true +} diff --git a/doc/精读报告/gtask/remote/GTaskSyncService.doc b/doc/精读报告/gtask/remote/GTaskSyncService.doc new file mode 100644 index 0000000..63967b9 --- /dev/null +++ b/doc/精读报告/gtask/remote/GTaskSyncService.doc @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)//GTask同步服务,用于提供同步服务(开始、取消同步),发送广播 + * + * 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;//Service是Android四大组件之一,通常用作在后台处理耗时的逻辑,不用与用户进行交互,即使应用被销毁依然可以继续工作。 + +import android.app.Activity;//引用包 +import android.app.Service; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.os.IBinder; + +public class GTaskSyncService extends Service {//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;//活动非法为2 + + public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";//服务广播的名称 + + public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";//正在同步中 + + public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";//进程消息 + + private static GTaskASyncTask mSyncTask = null; + + private static String mSyncProgress = ""; + + private void startSync() {//开始同步 + if (mSyncTask == null) {//若当前没有同步工作,申请一个task并把指针指向新任务,广播后执行 + mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { + public void onComplete() {//实现了在GTaskASyncTask类中定义的接口onComplete( ) + mSyncTask = null; + sendBroadcast("");//广播同步消息 + stopSelf();//当完成所有功能之后,将service停掉 + } + }); + sendBroadcast(""); + mSyncTask.execute();//语句:调用同步执行的函数 + } + } + + private void cancelSync() {//取消同步 + if (mSyncTask != null) {//同步的任务非空 + mSyncTask.cancelSync();//如果正在同步,结束当前同步 + } + } + + @Override + public void onCreate() { + mSyncTask = null; + }//初始化一个service + + @Override + public int onStartCommand(Intent intent, int flags, int startId) {//充当重启便签指令 + Bundle bundle = intent.getExtras();//Bundle类用作携带数据,用于存放key-value明值对应形式的值。 + if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {//判断当前的同步状态,根据开始或取消,执行对应操作 + switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {//判断当前同步状态,启动或取消 + case ACTION_START_SYNC://启动同步 + startSync(); + break; + case ACTION_CANCEL_SYNC://取消同步 + cancelSync(); + break; + default: + break; + } + return START_STICKY;//等待新的intent来是这个service继续运行 + } + return super.onStartCommand(intent, flags, startId);//调用父类的函数 + } + + @Override//处理内存不足的情况,即取消同步 + public void onLowMemory() {//广播信息msg + if (mSyncTask != null) { + mSyncTask.cancelSync(); + } + } + + public IBinder onBind(Intent intent) { + return null; + }//函数:用于绑定操作的函数 + + public void sendBroadcast(String msg) {//发送广播内容 + mSyncProgress = msg; + Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);//创建一个新的Intent + intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);//附加INTENT中的相应参数的值 + intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg); + sendBroadcast(intent);//发送这个通知 + } + + public static void startSync(Activity activity) {//启动同步 + GTaskManager.getInstance().setActivityContext(activity);//任务管理器获取活动的内容 + Intent intent = new Intent(activity, GTaskSyncService.class);//创建新intent + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);//将之前初始化的各种字符串加入intent + activity.startService(intent);//开始同步服务 + } + + public static void cancelSync(Context context) {//取消同步 + Intent intent = new Intent(context, GTaskSyncService.class);//显式构建intent,以函数参数context作为第一个参数,以自己GTaskSyncService.class作为目标活动 + intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);//把想要传递的数据暂存到intent中,传递数据以“键值对”形式传入。键为"sync_action_type",值为1 + context.startService(intent);//使用startService()执行intent,在本活动基础上打开GTaskSyncService活动 + } + + public static boolean isSyncing() { + return mSyncTask != null; + }//判断当前是否处于同步状态 + + public static String getProgressString() { + return mSyncProgress; + }//返回当前同步状态 +} diff --git a/doc/精读报告/model/Note.doc b/doc/精读报告/model/Note.doc new file mode 100644 index 0000000..e340c61 --- /dev/null +++ b/doc/精读报告/model/Note.doc @@ -0,0 +1,253 @@ +/*//单个便签项 + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model;//包的名称 +import android.content.ContentProviderOperation;//更新、插入、删除数据 +import android.content.ContentProviderResult;//操作结果 +import android.content.ContentUris;//用于添加和获取Uri后面的ID +import android.content.ContentValues;//存储基本数据类型数据 +import android.content.Context;//提供调用者的环境 +import android.content.OperationApplicationException;//操作数据容错 +import android.net.Uri;//远程容错 +import android.os.RemoteException;//远程容错 +import android.util.Log;//输出日志,比如说出错、警告等 + +import net.micode.notes.data.Notes;//以下5行都是对小米便签数据处理的一些数据或操作相关 +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; + +import java.util.ArrayList;//以上全是导入 + + +public class Note {//这个类是用来刻画单个Note的 + private ContentValues mNoteDiffValues;//ContentValues是用于给其他应用调用小米便签的内容的共享数据 + private NoteData mNoteData;//申明一个NoteData变量,用来记录note的一些基本信息 + private static final String TAG = "Note";//软件的名称 + /** + * Create a new note id for adding a new note to databases//创建一个新的便签id,以便把新便签加入数据库 + */ + public static synchronized long getNewNoteId(Context context, long folderId) {//获取新建便签的编号 + // Create a new note in the database + ContentValues values = new ContentValues();//在数据库中新建一个便签文件 + long createdTime = System.currentTimeMillis();//读取当前系统时间 + values.put(NoteColumns.CREATED_DATE, createdTime);//将创建时间和修改时间都更改为当前系统时间 + values.put(NoteColumns.MODIFIED_DATE, createdTime);//更改时间 + values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);//便签类型 + values.put(NoteColumns.LOCAL_MODIFIED, 1);//修改标志置为1 + values.put(NoteColumns.PARENT_ID, folderId);//将数据写入数据库表格 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);//外部应用对ContentProvider中的数据进行添加、删除、修改和查询操作 + + long noteId = 0;//实现外部应用对数据的插入删除等操作 + try {//异常处理 + noteId = Long.valueOf(uri.getPathSegments().get(1));//获取便签的id + } catch (NumberFormatException e) {//异常处理和提示 + Log.e(TAG, "Get note id error :" + e.toString());//获取id错误 + noteId = 0;//获取了错误的id + } + if (noteId == -1) {//块:错误ID,异常处理 + throw new IllegalStateException("Wrong note id:" + noteId);//非法状态时返回出错便签编号 + } + return noteId;//若没有异常,那么返回这个id + } + + public Note() {//定义两个变量用来存储便签的数据,一个是存储便签属性、一个是存储便签内容 + mNoteDiffValues = new ContentValues();//便签属性 + mNoteData = new NoteData();//便签内容 + } + + public void setNoteValue(String key, String value) {//设置数据库表格的标签属性数据 + mNoteDiffValues.put(key, value);//设置key值和对应的value值 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);//修改之后标志为1 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());//更新修改时间为当前系统时间 + } + + public void setTextData(String key, String value) { + mNoteData.setTextData(key, value); + }//设置数据库表格的标签文本内容的数据 + + public void setTextDataId(long id) { + mNoteData.setTextDataId(id); + }//设置文本数据的ID + + public long getTextDataId() { + return mNoteData.mTextDataId; + }//获取文本数据的id + + public void setCallDataId(long id) { + mNoteData.setCallDataId(id); + }//设置电话号码数据的ID + + public void setCallData(String key, String value) { + mNoteData.setCallData(key, value); + }//得到电话号码数据的ID + + public boolean isLocalModified() {//判断是否是本地修改 + return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();//相较上次存在修改size()>0 + } + + public boolean syncNote(Context context, long noteId) {//判断便签是否同步 + if (noteId <= 0) {//便签ID不合法时抛出异常 + throw new IllegalArgumentException("Wrong note id:" + noteId);//抛出异常,弹出对话框错误ID并显示错误ID号 + } + + if (!isLocalModified()) {//如果本地没有发现修改,直接返回1,指示已经同步到数据库中 + return true;//返回true + } + + /** + * In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and + * {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the + * note data info + */ + if (context.getContentResolver().update(//发现更新错误时,及时反馈错误信息 + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null, + null) == 0) { + Log.e(TAG, "Update note error, should not happen");//更新失败 + // Do not return, fall through + } + mNoteDiffValues.clear();//初始化便签特征值 + + if (mNoteData.isLocalModified()//判断未同步 + && (mNoteData.pushIntoContentResolver(context, noteId) == null)) {//如果向内容接收者推送上下文失败,则返回错误 + return false;//否则已经同步成功 + } + + return true;//成功则返回true + } + + private class NoteData {//定义一个基本的便签内容的数据类,主要包含文本数据和电话号码数据 + private long mTextDataId;//文本数据id + + private ContentValues mTextDataValues;//文本数据内容 + + private long mCallDataId;//电话号码数据ID + + private ContentValues mCallDataValues;//电话号码数据内容 + + private static final String TAG = "NoteData";//初始化 + + public NoteData() {// NoteData的构造函数,初始化四个变量 + mTextDataValues = new ContentValues();//初始化一个文本数据,为了储存文本 + mCallDataValues = new ContentValues();//初始化一个电话号码数据,为了储存电话号码 + mTextDataId = 0;//初始化文本数据ID,置为0 + mCallDataId = 0;//初始化电话号码ID,置为0 + } + + boolean isLocalModified() {//下面是上述几个函数的具体实现 + return mTextDataValues.size() > 0 || mCallDataValues.size() > 0; + } + + void setTextDataId(long id) {//设定文本数据id + if(id <= 0) {// id不能小于0 + throw new IllegalArgumentException("Text data id should larger than 0");//id保证大于0 + } + mTextDataId = id;//设定电话号码id + } + + void setCallDataId(long id) {//设置电话号码对应的id + if (id <= 0) {//判断ID是否合法 + throw new IllegalArgumentException("Call data id should larger than 0");//电话号码数据ID应大于0 + } + mCallDataId = id;//设定电话数据 + } + + void setCallData(String key, String value) {//设置电话号码数据内容,并且保存修改时间 + mCallDataValues.put(key, value);//修改之后,将属性值置为1 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);//系统修改时间 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());//设置修改时间为当前系统时间 + } + + void setTextData(String key, String value) {//设置文本数据 + mTextDataValues.put(key, value);//修改后标志置为1 + mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);//设置修改时间为当前系统时间 + mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());//设置修改时间为当前系统时间 + } + + Uri pushIntoContentResolver(Context context, long noteId) {//下面函数的作用是将新的数据通过Uri的操作存储到数据库 + /** + * Check for safety + */ + if (noteId <= 0) {//保证便器的编号为正数 + throw new IllegalArgumentException("Wrong note id:" + noteId);//判断数据是否合法 + } + + ArrayList operationList = new ArrayList();//数据库操作链表 + ContentProviderOperation.Builder builder = null;//数据库的操作列表 + + if(mTextDataValues.size() > 0) {//把文本数据存入DataColumns + mTextDataValues.put(DataColumns.NOTE_ID, noteId);//设定文本数据的属性 + if (mTextDataId == 0) {//uri插入文本数据 + mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);//把文本便签的类型填入文本数据库中的对应一行 + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,//uri内容接收器插入文本数据库,放在Notes.CONTENT_DATA_URI的路径下 + mTextDataValues); + try {//尝试重新给它设置id + setTextDataId(Long.valueOf(uri.getPathSegments().get(1))); + } catch (NumberFormatException e) { + Log.e(TAG, "Insert new text data fail with noteId" + noteId);//插入数据失败 + mTextDataValues.clear();//把电话号码数据存入DataColumns + return null; + } + } else { + builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(//内容提供者的更新操作,因为这个uri对应的数据是已经存在的,所以不需要向上面一样新建,而是更新即可 + Notes.CONTENT_DATA_URI, mTextDataId));//语句: 将uri和id合并后,更新 + builder.withValues(mTextDataValues); + operationList.add(builder.build());//操作队列添加上内容提供者 + } + mTextDataValues.clear();//设定电话号码的属性数据 + } + + if(mCallDataValues.size() > 0) {//对于电话号码的数据也是和文本数据一样的同步处理 + mCallDataValues.put(DataColumns.NOTE_ID, noteId);//写入noteID + if (mCallDataId == 0) {//将电话号码的id设定为uri提供的id + mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE); + Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI, + mCallDataValues); + try {//异常处理 + setCallDataId(Long.valueOf(uri.getPathSegments().get(1))); + } catch (NumberFormatException e) { + Log.e(TAG, "Insert new call data fail with noteId" + noteId);//插入电话号码数据失败 + mCallDataValues.clear(); + return null; + } + } else {//当电话号码不为新建时,更新电话号码ID + builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(//内容提供者的更新操作,这个uri对应的数据是已经存在的,因此进行更新即可 + Notes.CONTENT_DATA_URI, mCallDataId)); + builder.withValues(mCallDataValues); + operationList.add(builder.build());//存储过程中的异常处理 + } + mCallDataValues.clear(); + } + + if (operationList.size() > 0) {//存储过程中如果遇到异常,通过如下进行处理 + try {//抛出远程异常,并写回日志 + ContentProviderResult[] results = context.getContentResolver().applyBatch(//Android源码中对通讯录的操作,应用端使用ContentProvider提供的applyBatch,进行批量处理通讯录的联系人入库 + Notes.AUTHORITY, operationList); + return (results == null || results.length == 0 || results[0] == null) ? null//完成后返回一个URI + : ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId); + } catch (RemoteException e) {//捕捉操作异常并写回日志 + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));//异常日志 + return null; + } catch (OperationApplicationException e) { + Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));//异常日志 + return null; + } + } + return null; + } + } +} diff --git a/doc/精读报告/model/WorkingNote.doc b/doc/精读报告/model/WorkingNote.doc new file mode 100644 index 0000000..c12e7c7 --- /dev/null +++ b/doc/精读报告/model/WorkingNote.doc @@ -0,0 +1,368 @@ +/*//当前活动便签项 + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.model;//在model包中 + +import android.appwidget.AppWidgetManager;//需要调用的其他类 +import android.content.ContentUris; +import android.content.Context; +import android.database.Cursor;//游标的使用 +import android.text.TextUtils; +import android.util.Log; + +import net.micode.notes.data.Notes;//小米便签操作的整体属性 +import net.micode.notes.data.Notes.CallNote; +import net.micode.notes.data.Notes.DataColumns; +import net.micode.notes.data.Notes.DataConstants; +import net.micode.notes.data.Notes.NoteColumns; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.tool.ResourceParser.NoteBgResources; + + +public class WorkingNote {//声明一个workingnote类 + // Note for the working note + private Note mNote;//声明一个Note类型的变量 + // Note Id + private long mNoteId;//声明便签content + // Note content + private String mContent;//声明便签mode + // Note mode + private int mMode;//是否是清单模式 + + private long mAlertDate;//设置闹钟时间 + + private long mModifiedDate;// 最后修改时间 + + private int mBgColorId;//背景颜色ID + + private int mWidgetId;//控件ID + + private int mWidgetType;//桌面挂件的格式 + + private long mFolderId;//便签文件夹ID + + private Context mContext;//当前便签的上下文 + + private static final String TAG = "WorkingNote";//声明 DATA_PROJECTION字符串数组 + + private boolean mIsDeleted;//是否应该被删除 + + private NoteSettingChangedListener mNoteSettingStatusListener;//一个用来监听设置是否有变化的接口 + + public static final String[] DATA_PROJECTION = new String[] {//声明 NOTE_PROJECTION字符串数组 + 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, + NoteColumns.ALERTED_DATE, + NoteColumns.BG_COLOR_ID, + NoteColumns.WIDGET_ID, + NoteColumns.WIDGET_TYPE, + NoteColumns.MODIFIED_DATE + }; + + private static final int DATA_ID_COLUMN = 0;//规定每一个数据类型在哪一行 + + private static final int DATA_CONTENT_COLUMN = 1; + + private static final int DATA_MIME_TYPE_COLUMN = 2; + + private static final int DATA_MODE_COLUMN = 3; + + private static final int NOTE_PARENT_ID_COLUMN = 0;//以下6个常量表示便签投影的0-5列 + + private static final int NOTE_ALERTED_DATE_COLUMN = 1; + + private static final int NOTE_BG_COLOR_ID_COLUMN = 2; + + private static final int NOTE_WIDGET_ID_COLUMN = 3; + + private static final int NOTE_WIDGET_TYPE_COLUMN = 4; + + private static final int NOTE_MODIFIED_DATE_COLUMN = 5; + + // New note construct + private WorkingNote(Context context, long folderId) {//该方法初始化类里的各项变量 + mContext = context;//WorkingNote的构造函数 + mAlertDate = 0;//默认提醒日期为0 + mModifiedDate = System.currentTimeMillis();//系统现在的时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数 + mFolderId = folderId;//默认最后一次修改日期为当前时间 + mNote = new Note();//加载一个已存在的便签 + mNoteId = 0;//没有提供id所以默认为0 + mIsDeleted = false; + mMode = 0; + mWidgetType = Notes.TYPE_WIDGET_INVALIDE;//默认是不可见 + } + + // Existing note construct + private WorkingNote(Context context, long noteId, long folderId) {//加载Note + mContext = context;//调用query函数找到第一个条目 + mNoteId = noteId; + mFolderId = folderId; + mIsDeleted = false; + mNote = new Note(); + loadNote();//加载便签 + } + + private void loadNote() {//加载已有的便签 + Cursor cursor = mContext.getContentResolver().query(//存在第一个条目 + ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mNoteId), NOTE_PROJECTION, null, + null, null); + + if (cursor != null) {//通过数据库调用query函数找到第一个条目 + if (cursor.moveToFirst()) {//如果游标移动到第一行 + mFolderId = cursor.getLong(NOTE_PARENT_ID_COLUMN);//存储各项信息 + mBgColorId = cursor.getInt(NOTE_BG_COLOR_ID_COLUMN);//关闭cursor游标 + 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, "No note with id:" + mNoteId);//未能找到此note,返回异常 + throw new IllegalArgumentException("Unable to find note with id " + mNoteId);//抛出异常,找不到NoteID + } + loadNoteData();//调用方法loadNoteData,导入便签的内容。 + } + + private void loadNoteData() {//加载NoteData + Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, DATA_PROJECTION, + DataColumns.NOTE_ID + "=?", new String[] { + String.valueOf(mNoteId) + }, null);//判断信息是否为空 + + if (cursor != null) {//光标存在时,将光标移动到便签的起始位置 + if (cursor.moveToFirst()) {//do while循环将便签数据全部读取出来 + do { + String type = cursor.getString(DATA_MIME_TYPE_COLUMN);//获取存储内容的类型 + if (DataConstants.NOTE.equals(type)) {//数据类型为文本类型时,存为文本 + mContent = cursor.getString(DATA_CONTENT_COLUMN);//如果是便签文本类型,那么加载到相应的里面保存 + mMode = cursor.getInt(DATA_MODE_COLUMN); + mNote.setTextDataId(cursor.getLong(DATA_ID_COLUMN)); + } else if (DataConstants.CALL_NOTE.equals(type)) {//为电话号码类信息时 存为电话号码 + mNote.setCallDataId(cursor.getLong(DATA_ID_COLUMN));//否则,在日志中标志错误类型为note type错误 + } else {//如果类型错误,则提示异常 + Log.d(TAG, "Wrong note type with type:" + type);//再否则就是有错误 + } + } while (cursor.moveToNext());//查阅所有项,直到为空 + } + cursor.close();//查找失败时,在日志中记录错误信息为无法找到id号为mNoteId的便签 + } else {//否则记录异常日志,没有ID为mNoteId的数据 + Log.e(TAG, "No data with id:" + mNoteId);//否则记录异常日志,没有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) { + WorkingNote note = new WorkingNote(context, folderId);//根据环境和id创建一个空的便签 + note.setBgColorId(defaultBgColorId);//设定相关属性 + note.setWidgetId(widgetId);//设定widget id + note.setWidgetType(widgetType);//设置窗口类型 + return note; + } + + public static WorkingNote load(Context context, long id) {//导入一个新的正在写入的便签(WorkingNote) + return new WorkingNote(context, id, 0);//返回便签 + } + + public synchronized boolean saveNote() {//保存Note + if (isWorthSaving()) {//是否值得保存 + if (!existInDatabase()) {//是否存在数据库 + if ((mNoteId = Note.getNewNoteId(mContext, mFolderId)) == 0) {//没有成功创建一个便签时,返回出错日志 + Log.e(TAG, "Create new note fail with id:" + mNoteId); + return false; + } + } + + mNote.syncNote(mContext, mNoteId);//同步便签内容及便签id + + /** + * Update widget content if there exist any widget of this note + */ + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID//判断是否存在widget可以上传 + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE + && mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onWidgetChanged(); + } + return true; + } else { + return false; + } + } + + public boolean existInDatabase() { + return mNoteId > 0; + }//是否在数据库中存在判断是否在数据库中存储过,直接判定id大小即可 + + private boolean isWorthSaving() {//判断是否需要保存 + if (mIsDeleted || (!existInDatabase() && TextUtils.isEmpty(mContent))//被删除,或(不在数据库中 内容为空),或 本地已保存过 + || (existInDatabase() && !mNote.isLocalModified())) { + return false; + } else { + return true;//其余情况,要保存,返回true + } + } + + public void setOnSettingStatusChangedListener(NoteSettingChangedListener l) {//设置常量 + mNoteSettingStatusListener = l; + } + + public void setAlertDate(long date, boolean set) {//设置AlertDate;若 mAlertDate与data不同,则更改mAlertDate并设定NoteValue + if (date != mAlertDate) {//发现date与mAlertDate不一致时,设置mAlertDate为date + mAlertDate = date;//为设置的日期打标签 + mNote.setNoteValue(NoteColumns.ALERTED_DATE, String.valueOf(mAlertDate)); + } + if (mNoteSettingStatusListener != null) {//判断是否为空 + mNoteSettingStatusListener.onClockAlertChanged(date, set); + } + } + + public void markDeleted(boolean mark) {//设定删除标记 + mIsDeleted = mark;//设定标记 + if (mWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID + && mWidgetType != Notes.TYPE_WIDGET_INVALIDE && mNoteSettingStatusListener != null) {//调用mNoteSettingStatusListener的 onWidgetChanged方法 + mNoteSettingStatusListener.onWidgetChanged(); + } + } + + public void setBgColorId(int id) {//设定背景颜色 + if (id != mBgColorId) {//判断 + mBgColorId = id;//设置背景颜色 + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onBackgroundColorChanged(); + } + mNote.setNoteValue(NoteColumns.BG_COLOR_ID, String.valueOf(id)); + } + } + + public void setCheckListMode(int mode) {//设定检查列表模式 + if (mMode != mode) {//设定一个判断条件 + if (mNoteSettingStatusListener != null) { + mNoteSettingStatusListener.onCheckListModeChanged(mMode, mode);//设定之后更改mMode + } + mMode = mode;//把当前便签蛇者为清单模式的便签 + mNote.setTextData(TextNote.MODE, String.valueOf(mMode));//语句:重设文本数据,改变MODE项 + } + } + + public void setWidgetType(int type) {//设定WidgetType + if (type != mWidgetType) {//设定条件 + mWidgetType = type;//调用Note的setNoteValue方法更改WidgetType + mNote.setNoteValue(NoteColumns.WIDGET_TYPE, String.valueOf(mWidgetType)); + }//调用Note的setNoteValue方法更改WidgetType + } + + public void setWidgetId(int id) {//设定WidgetId + if (id != mWidgetId) {//设定条件 + mWidgetId = id;//调用Note的setNoteValue方法更改WidgetId + mNote.setNoteValue(NoteColumns.WIDGET_ID, String.valueOf(mWidgetId)); + }//调用Note的setNoteValue方法更改WidgetId + } + + public void setWorkingText(String text) {//设定WorkingText + if (!TextUtils.equals(mContent, text)) {//判断条件 + mContent = text;//调用Note的setTextData方法更改WorkingText + mNote.setTextData(DataColumns.CONTENT, mContent);//调用Note的setTextData方法更改WorkingText + } + } + + public void convertToCallNote(String phoneNumber, long callDate) {//转变mNote的CallData及CallNote信息 + 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; + }//获取修改的数据 + + public int getBgColorResId() { + return NoteBgResources.getNoteBgResource(mBgColorId); + }//获取背景颜色id + + public int getBgColorId() { + return mBgColorId; + }//获取背景颜色id + + public int getTitleBgResId() { + return NoteBgResources.getNoteTitleBgResource(mBgColorId); + }//获取标题背景颜色id + + public int getCheckListMode() { + return mMode; + }//获取CheckListMode + + public long getNoteId() { + return mNoteId; + }//获取便签id + + public long getFolderId() { + return mFolderId; + }//获取文件夹id + + public int getWidgetId() { + return mWidgetId; + }//获取WidgetType + + public int getWidgetType() { + return mWidgetType; + }//创建接口 NoteSettingChangedListener,便签更新监视;为NoteEditActivity提供接口 + + public interface NoteSettingChangedListener {//该类用于侦听关于Note的设置的改变 + /** + * Called when the background color of current note has just changed + */ + void onBackgroundColorChanged();//背景颜色改变按钮 + + /** + * Called when user set clock + */ + void onClockAlertChanged(long date, boolean set);// + + /** + * Call when user create note from widget + */ + void onWidgetChanged();//小部件的修改按钮 + + /** + * Call when switch between check list mode and normal mode + * @param oldMode is previous mode before change + * @param newMode is new mode + */ + void onCheckListModeChanged(int oldMode, int newMode);//mode的改变按键 + } +} diff --git a/doc/精读报告/ui/AlarmAlertActivity.doc b/doc/精读报告/ui/AlarmAlertActivity.doc new file mode 100644 index 0000000..d3f8954 --- /dev/null +++ b/doc/精读报告/ui/AlarmAlertActivity.doc @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.content.DialogInterface.OnDismissListener; +import android.content.Intent; +import android.media.AudioManager; +import android.media.MediaPlayer; +import android.media.RingtoneManager; +import android.net.Uri; +import android.os.Bundle; +import android.os.PowerManager; +import android.provider.Settings; +import android.view.Window; +import android.view.WindowManager; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.tool.DataUtils; + +import java.io.IOException; + + +public class AlarmAlertActivity extends Activity implements OnClickListener, OnDismissListener { + //. 继承了Activity类,改类实现了OnClickListener和 OnDismissListener两个接口,OnClickListener接口用来监听点击事件,OnDismissListener接口用来监听关闭对话框事件 + private long mNoteId;//文本在数据库中的ID号 + private String mSnippet;//闹钟提示时显示的文本 + private static final int SNIPPET_PREW_MAX_LEN = 60;//文本最大长度 + MediaPlayer mPlayer; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState);//Bundle类型的数据与Map类型的数据相似,都是以key-value的形式存储数据的 + //onsaveInstanceState方法是用来保存Activity的状态的 + //能从onCreate的参数savedInsanceState中获得状态数据 + requestWindowFeature(Window.FEATURE_NO_TITLE);//界面显示无标题 + + final Window win = getWindow(); + win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); + + if (!isScreenOn()) { + win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON + //保持屏幕亮屏 + | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON + //唤醒屏幕 + | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON + //允许亮屏时锁屏 + | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR); + }//手机息屏后若闹钟铃响则亮屏 + + Intent intent = getIntent(); + + try { + mNoteId = Long.valueOf(intent.getData().getPathSegments().get(1)); + mSnippet = DataUtils.getSnippetById(this.getContentResolver(), mNoteId); + //根据ID从数据库中获取标签的内容 + //getContentResolver()是实现数据共享,实例存储 + mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0, + SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info) + : mSnippet;//判断标签片段是否达到符合长度 + } catch (IllegalArgumentException e) { + e.printStackTrace(); + return; + } + + mPlayer = new MediaPlayer(); + if (DataUtils.visibleInNoteDatabase(getContentResolver(), mNoteId, Notes.TYPE_NOTE)) { + showActionDialog();//弹出对话框 + playAlarmSound();//闹钟发出提示音 + } else { + finish();//完成闹钟动作 + } + } + + private boolean isScreenOn() { + //判断屏幕是否锁屏,调用系统函数判断,最后返回值是布尔类型 + PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); + return pm.isScreenOn(); + } + + private void playAlarmSound() { + //闹钟发出提示音 + Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM); + //调用系统的铃声管理URI,得到闹钟提示音 + int silentModeStreams = Settings.System.getInt(getContentResolver(), + Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0); + + if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) { + mPlayer.setAudioStreamType(silentModeStreams); + } else { + mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); + } + try { + mPlayer.setDataSource(this, url); + //根据Uri设置多媒体数据来源 + mPlayer.prepare();//播放器准备 + mPlayer.setLooping(true);//设置循环播放 + mPlayer.start();//开始播放 + + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace();//e.printStackTrace()函数功能是抛出异常, 还将显示出更深的调用信息 + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + private void showActionDialog() { + AlertDialog.Builder dialog = new AlertDialog.Builder(this); + //AlertDialog的构造方法全部是Protected的 + //所以不能直接通过new一个AlertDialog来创建出一个AlertDialog。 + //要创建一个AlertDialog,就要用到AlertDialog.Builder中的create()方法 + //如这里的dialog就是新建了一个AlertDialog + dialog.setTitle(R.string.app_name);//为对话框设置标题 + dialog.setMessage(mSnippet);//为对话框设置内容 + dialog.setPositiveButton(R.string.notealert_ok, this);//给对话框添加"Yes"按钮 + if (isScreenOn()) { + dialog.setNegativeButton(R.string.notealert_enter, this); + }//对话框添加"No"按钮 + dialog.show().setOnDismissListener(this); + } + + public void onClick(DialogInterface dialog, int which) { + switch (which) { + //用which来选择click后下一步的操作 + case DialogInterface.BUTTON_NEGATIVE://这是取消操作 + Intent intent = new Intent(this, NoteEditActivity.class);//实现两个类间的数据传输 + intent.setAction(Intent.ACTION_VIEW);//设置动作属性 + intent.putExtra(Intent.EXTRA_UID, mNoteId);//实现key-value对 + //EXTRA_UID为key;mNoteId为键 + startActivity(intent);//开始动作 + break; + default://这是确定操作 + break; + } + } + + public void onDismiss(DialogInterface dialog) {//忽略 + stopAlarmSound();//停止闹钟声音 + finish();//完成该动作 + } + + private void stopAlarmSound() { + if (mPlayer != null) { + mPlayer.stop();//停止播放 + mPlayer.release();//释放MediaPlayer对象 + mPlayer = null; + } + } +} diff --git a/doc/精读报告/ui/AlarmInitReceiver.doc b/doc/精读报告/ui/AlarmInitReceiver.doc new file mode 100644 index 0000000..5c70518 --- /dev/null +++ b/doc/精读报告/ui/AlarmInitReceiver.doc @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.ContentUris; +import android.content.Context; +import android.content.Intent; +import android.database.Cursor; + +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +public class AlarmInitReceiver extends BroadcastReceiver { + + private static final String [] PROJECTION = new String [] { + NoteColumns.ID, + NoteColumns.ALERTED_DATE + }; + //对数据库的操作,调用标签ID和闹钟时间 + private static final int COLUMN_ID = 0; + private static final int COLUMN_ALERTED_DATE = 1; + + @Override + public void onReceive(Context context, Intent intent) { + long currentDate = System.currentTimeMillis();//System.currentTimeMillis()产生一个当前的毫秒 + Cursor c = context.getContentResolver().query(Notes.CONTENT_NOTE_URI, + PROJECTION, + NoteColumns.ALERTED_DATE + ">? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE, + new String[] { String.valueOf(currentDate) },//将long变量currentDate转化为字符串 + null); +//Cursor在这里的作用是通过查找数据库中的标签内容,找到和当前系统时间相等的标签 + if (c != null) {//当c != null的时候,将cursor移动到开始处,然后执行相关对信息的读取工作,直至读取结束,然后关闭该cursor + if (c.moveToFirst()) {//游标移动到开始位置 + do { + long alertDate = c.getLong(COLUMN_ALERTED_DATE);//获取便签的提醒时间 + Intent sender = new Intent(context, AlarmReceiver.class);//新建一个intent类 来指向alarmreceiver 来传输数据 + sender.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, c.getLong(COLUMN_ID)));//设置数据为便签的uri和id + PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, sender, 0); + //使用了PendingIntent方法,得到可以延时向之前定义的Intent sender发送广播的PendingIntent实例Pendingintent + AlarmManager alermManager = (AlarmManager) context//新建系统的闹钟服务 + .getSystemService(Context.ALARM_SERVICE); + alermManager.set(AlarmManager.RTC_WAKEUP, alertDate, pendingIntent); + //调用android系统方法AlarmManager,设置一个系统提醒事项,设置提醒时间为当前便签中所存alertdate,并设置激活提醒时,广播类Pendingintent + } while (c.moveToNext());//游标移动到下一位置 + } + c.close();//关闭游标 + } + } +} diff --git a/doc/精读报告/ui/AlarmReceiver.doc b/doc/精读报告/ui/AlarmReceiver.doc new file mode 100644 index 0000000..37f264c --- /dev/null +++ b/doc/精读报告/ui/AlarmReceiver.doc @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; + +public class AlarmReceiver extends BroadcastReceiver { + @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放入栈顶 + context.startActivity(intent);//使用intent启动activity + } +} diff --git a/doc/精读报告/ui/DateTimePicker.doc b/doc/精读报告/ui/DateTimePicker.doc new file mode 100644 index 0000000..9e6c5ee --- /dev/null +++ b/doc/精读报告/ui/DateTimePicker.doc @@ -0,0 +1,496 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.text.DateFormatSymbols; +import java.util.Calendar; + +import net.micode.notes.R; + + +import android.content.Context; +import android.text.format.DateFormat; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.NumberPicker; + +public class DateTimePicker extends FrameLayout { + //FrameLayout是布局模板之一 + //所有的子元素全部在屏幕的右上方 + private static final boolean DEFAULT_ENABLE_STATE = true; + + private static final int HOURS_IN_HALF_DAY = 12;//定义半天为12小时 + private static final int HOURS_IN_ALL_DAY = 24;//定义一天为24小时 + private static final int DAYS_IN_ALL_WEEK = 7;//定义一周为七天 + private static final int DATE_SPINNER_MIN_VAL = 0;//定义日期循环最小值为0 + private static final int DATE_SPINNER_MAX_VAL = DAYS_IN_ALL_WEEK - 1;//一周循环最大天数为一周天数减1天 + private static final int HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW = 0;//24小时制小时最小值为0 + private static final int HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW = 23;//定义24小时循环的最大值为23 + private static final int HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW = 1;// 12小时制下小时转轮最小值 + private static final int HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW = 12;// 12小时制下小时转轮最大值 + private static final int MINUT_SPINNER_MIN_VAL = 0;//分钟轮转最小值为0 + private static final int MINUT_SPINNER_MAX_VAL = 59;//分钟轮转最大值为59 + private static final int AMPM_SPINNER_MIN_VAL = 0;//标志上下午的轮转值,没有具体意义 + 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; + + private boolean mIs24HourView; + + private boolean mIsEnabled = DEFAULT_ENABLE_STATE; + + private boolean mInitialising; + + private OnDateTimeChangedListener mOnDateTimeChangedListener; + + private NumberPicker.OnValueChangeListener mOnDateChangedListener = new NumberPicker.OnValueChangeListener() { + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mDate.add(Calendar.DAY_OF_YEAR, newVal - oldVal); + updateDateControl(); + onDateTimeChanged(); + } + };//OnValueChangeListener,这是时间改变监听器,这里主要是对日期的监听 + //将现在日期的值传递给mDate;updateDateControl是同步操作 + + 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点交替时对日期的更改 + } 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 { + 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)); + setCurrentMonth(cal.get(Calendar.MONTH)); + setCurrentDay(cal.get(Calendar.DAY_OF_MONTH)); + } + } + }; + + private NumberPicker.OnValueChangeListener mOnMinuteChangedListener = new NumberPicker.OnValueChangeListener() { + @Override//这里是对 分钟(Minute)改变的监听 + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + int minValue = mMinuteSpinner.getMinValue(); + int maxValue = mMinuteSpinner.getMaxValue(); + int offset = 0;//设置offset,作为小时改变的一个记录数据 + 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()); + updateDateControl(); + int newHour = getCurrentHourOfDay(); + if (newHour >= HOURS_IN_HALF_DAY) { + mIsAm = false; + updateAmPmControl(); + } else { + mIsAm = true; + updateAmPmControl(); + } + } + mDate.set(Calendar.MINUTE, newVal); + onDateTimeChanged(); + } + }; + + private NumberPicker.OnValueChangeListener mOnAmPmChangedListener = new NumberPicker.OnValueChangeListener() { //对AM和PM的监听 + @Override + public void onValueChange(NumberPicker picker, int oldVal, int newVal) { + mIsAm = !mIsAm; + if (mIsAm) { + mDate.add(Calendar.HOUR_OF_DAY, -HOURS_IN_HALF_DAY); + } else { + mDate.add(Calendar.HOUR_OF_DAY, HOURS_IN_HALF_DAY); + } + updateAmPmControl(); + onDateTimeChanged(); + } + }; + + public interface OnDateTimeChangedListener { + void onDateTimeChanged(DateTimePicker view, int year, int month, + int dayOfMonth, int hourOfDay, int minute); + } + + public DateTimePicker(Context context) { + this(context, System.currentTimeMillis()); + }//通过对数据库的访问,获取当前的系统时间 + + + public DateTimePicker(Context context, long date) {//实例化时间日期选择器 + this(context, date, DateFormat.is24HourFormat(context)); + } + + public DateTimePicker(Context context, long date, boolean is24HourView) { + super(context);//获取系统时间 + mDate = Calendar.getInstance(); + mInitialising = true; + mIsAm = getCurrentHourOfDay() >= HOURS_IN_HALF_DAY; + inflate(context, R.layout.datetime_picker, this); + //如果当前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);//设置组件最大值属性为日期最大值 + mDateSpinner.setOnValueChangedListener(mOnDateChangedListener); + + mHourSpinner = (NumberPicker) findViewById(R.id.hour);//显示设置小时的视图 + mHourSpinner.setOnValueChangedListener(mOnHourChangedListener); + mMinuteSpinner = (NumberPicker) findViewById(R.id.minute);//显示设置分钟的视图 + mMinuteSpinner.setMinValue(MINUT_SPINNER_MIN_VAL);//设置组件最小值属性为分钟最小值 + mMinuteSpinner.setMaxValue(MINUT_SPINNER_MAX_VAL);//设置组件最大值属性为分钟最大值 + mMinuteSpinner.setOnLongPressUpdateInterval(100);//置监听长按时间间隔为100ms + mMinuteSpinner.setOnValueChangedListener(mOnMinuteChangedListener); + + String[] stringsForAmPm = new DateFormatSymbols().getAmPmStrings();//对24小时下的 am 与pm各属性值进行初始化 + mAmPmSpinner = (NumberPicker) findViewById(R.id.amPm);//显示设置上下午的视图 + mAmPmSpinner.setMinValue(AMPM_SPINNER_MIN_VAL);//设置组件最小值属性为上下午编码最小值 + mAmPmSpinner.setMaxValue(AMPM_SPINNER_MAX_VAL);//设置组件最大值属性为上下午编码最大值 + mAmPmSpinner.setDisplayedValues(stringsForAmPm);//设置显示上下午字符串的值 + mAmPmSpinner.setOnValueChangedListener(mOnAmPmChangedListener); + + // update controls to initial state将日期的各参数值更新为初始化状态 + updateDateControl(); + updateHourControl(); + updateAmPmControl(); + + set24HourView(is24HourView); + + // set to current time设置当前时间 + setCurrentDate(date); + + setEnabled(isEnabled()); + + // set the content descriptions + mInitialising = false;//表示初始化已经结束 + } + + @Override + public void setEnabled(boolean enabled) {//将当前监听器的状态设置为开启状态 + if (mIsEnabled == enabled) {//如果已经在开启状态,则返回 + return; + } + super.setEnabled(enabled);//将各部分设置为开启状态 + mDateSpinner.setEnabled(enabled); + mMinuteSpinner.setEnabled(enabled); + mHourSpinner.setEnabled(enabled); + mAmPmSpinner.setEnabled(enabled); + mIsEnabled = enabled; + } + + @Override + public boolean isEnabled() { + return mIsEnabled; + } + + /** + * Get the current date in millis + * + * @return the current date in millis + */ + public long getCurrentDateInTimeMillis() { + return mDate.getTimeInMillis(); + }//实现函数——得到当前的秒数 + + /** + * Set the current date + * + * @param date The current date in millis + */ + public void setCurrentDate(long date) { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(date); + setCurrentDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), + cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));//实现函数功能——设置当前的时间,参数是date + } + + /** + * Set the current date + * + * @param year The current year + * @param month The current month + * @param dayOfMonth The current dayOfMonth + * @param hourOfDay The current hourOfDay + * @param minute The current minute + */ + public void setCurrentDate(int year, int month, + int dayOfMonth, int hourOfDay, int minute) { + setCurrentYear(year); + setCurrentMonth(month); + setCurrentDay(dayOfMonth); + setCurrentHour(hourOfDay); + setCurrentMinute(minute); + }//实现函数功能——设置当前的时间,参数是各详细的变量 + + /** + * Get current year + * + * @return The current year + */ + //下面是得到year、month、day等值 + public int getCurrentYear() { + return mDate.get(Calendar.YEAR); + } + + /** + * Set current year + * + * @param year The current year + */ + public void setCurrentYear(int year) { + if (!mInitialising && year == getCurrentYear()) { + return; + } + mDate.set(Calendar.YEAR, year); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current month in the year + * + * @return The current month in the year + */ + public int getCurrentMonth() { + return mDate.get(Calendar.MONTH); + } + + /** + * Set current month in the year + * + * @param month The month in the year + */ + public void setCurrentMonth(int month) { + if (!mInitialising && month == getCurrentMonth()) { + return; + } + mDate.set(Calendar.MONTH, month); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current day of the month + * + * @return The day of the month + */ + public int getCurrentDay() { + return mDate.get(Calendar.DAY_OF_MONTH); + } + + /** + * Set current day of the month + * + * @param dayOfMonth The day of the month + */ + public void setCurrentDay(int dayOfMonth) { + if (!mInitialising && dayOfMonth == getCurrentDay()) { + return; + } + mDate.set(Calendar.DAY_OF_MONTH, dayOfMonth); + updateDateControl(); + onDateTimeChanged(); + } + + /** + * Get current hour in 24 hour mode, in the range (0~23) + * @return The current hour in 24 hour mode + */ + public int getCurrentHourOfDay() { + return mDate.get(Calendar.HOUR_OF_DAY); + } + + private int getCurrentHour() { + if (mIs24HourView){ + return getCurrentHourOfDay(); + } else { + int hour = getCurrentHourOfDay(); + if (hour > HOURS_IN_HALF_DAY) { + return hour - HOURS_IN_HALF_DAY; + } else { + return hour == 0 ? HOURS_IN_HALF_DAY : hour; + } + } + } + + /** + * Set current hour in 24 hour mode, in the range (0~23) + * + * @param hourOfDay + */ + public void setCurrentHour(int hourOfDay) { + if (!mInitialising && hourOfDay == getCurrentHourOfDay()) { + return; + } + mDate.set(Calendar.HOUR_OF_DAY, hourOfDay); + if (!mIs24HourView) { + if (hourOfDay >= HOURS_IN_HALF_DAY) { + mIsAm = false; + if (hourOfDay > HOURS_IN_HALF_DAY) { + hourOfDay -= HOURS_IN_HALF_DAY; + } + } else { + mIsAm = true; + if (hourOfDay == 0) { + hourOfDay = HOURS_IN_HALF_DAY; + } + } + updateAmPmControl(); + } + mHourSpinner.setValue(hourOfDay); + onDateTimeChanged(); + } + + /** + * Get currentMinute + * + * @return The Current Minute + */ + public int getCurrentMinute() { + return mDate.get(Calendar.MINUTE); + } + + /** + * Set current minute + */ + public void setCurrentMinute(int minute) { + if (!mInitialising && minute == getCurrentMinute()) { + return; + } + mMinuteSpinner.setValue(minute); + mDate.set(Calendar.MINUTE, minute); + onDateTimeChanged(); + } + + /** + * @return true if this is in 24 hour view else false. + */ + public boolean is24HourView () { + return mIs24HourView; + } + + /** + * Set whether in 24 hour or AM/PM mode. + * + * @param is24HourView True for 24 hour mode. False for AM/PM mode. + */ + public void set24HourView(boolean is24HourView) { + if (mIs24HourView == is24HourView) { + return; + } + mIs24HourView = is24HourView; + mAmPmSpinner.setVisibility(is24HourView ? View.GONE : View.VISIBLE); + int hour = getCurrentHourOfDay(); + updateHourControl(); + setCurrentHour(hour); + updateAmPmControl(); + } + + private void updateDateControl() { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(mDate.getTimeInMillis()); + cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1); + mDateSpinner.setDisplayedValues(null); + for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) { + cal.add(Calendar.DAY_OF_YEAR, 1); + mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal); + } + mDateSpinner.setDisplayedValues(mDateDisplayValues); + mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2); + mDateSpinner.invalidate();// 对于星期几的算法 + } + + private void updateAmPmControl() { + if (mIs24HourView) { + mAmPmSpinner.setVisibility(View.GONE); + } else { + int index = mIsAm ? Calendar.AM : Calendar.PM; + mAmPmSpinner.setValue(index); + mAmPmSpinner.setVisibility(View.VISIBLE); + }// 对于上下午操作的算法 + } + + private void updateHourControl() { + if (mIs24HourView) { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_24_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_24_HOUR_VIEW); + } else { + mHourSpinner.setMinValue(HOUR_SPINNER_MIN_VAL_12_HOUR_VIEW); + mHourSpinner.setMaxValue(HOUR_SPINNER_MAX_VAL_12_HOUR_VIEW); + } //对于小时的算法 + } + + /** + * Set the callback that indicates the 'Set' button has been pressed. + * @param callback the callback, if null will do nothing + */ + public void setOnDateTimeChangedListener(OnDateTimeChangedListener callback) { + mOnDateTimeChangedListener = callback; + } + + private void onDateTimeChanged() { + if (mOnDateTimeChangedListener != null) { + mOnDateTimeChangedListener.onDateTimeChanged(this, getCurrentYear(), + getCurrentMonth(), getCurrentDay(), getCurrentHourOfDay(), getCurrentMinute()); + } + } +} diff --git a/doc/精读报告/ui/DateTimePickerDialog.doc b/doc/精读报告/ui/DateTimePickerDialog.doc new file mode 100644 index 0000000..3c5bc83 --- /dev/null +++ b/doc/精读报告/ui/DateTimePickerDialog.doc @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import java.util.Calendar; + +import net.micode.notes.R; +import net.micode.notes.ui.DateTimePicker; +import net.micode.notes.ui.DateTimePicker.OnDateTimeChangedListener; + +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnClickListener; +import android.text.format.DateFormat; +import android.text.format.DateUtils; + +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) { + 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()); + } + + public void set24HourView(boolean is24HourView) { + mIs24HourView = is24HourView; + } + + 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; + 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是该对话框上的按钮 + +} \ No newline at end of file diff --git a/doc/精读报告/ui/DropdownMenu.doc b/doc/精读报告/ui/DropdownMenu.doc new file mode 100644 index 0000000..1d7851c --- /dev/null +++ b/doc/精读报告/ui/DropdownMenu.doc @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.PopupMenu; +import android.widget.PopupMenu.OnMenuItemClickListener; + +import net.micode.notes.R; + +public class DropdownMenu { + private Button mButton; + private PopupMenu mPopupMenu;//声明一个下拉菜单 + private Menu mMenu; + + 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(); + } + }); + } + + 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); + }//布局文件,设置标题 +} diff --git a/doc/精读报告/ui/FoldersListAdapter.doc b/doc/精读报告/ui/FoldersListAdapter.doc new file mode 100644 index 0000000..0088aa0 --- /dev/null +++ b/doc/精读报告/ui/FoldersListAdapter.doc @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context;//引用一些类,大多为与数据库的交互,对文件夹的列表名称等做调整 +import android.database.Cursor; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CursorAdapter; +import android.widget.LinearLayout; +import android.widget.TextView; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.NoteColumns; + + +public class FoldersListAdapter extends CursorAdapter { + //CursorAdapter是Cursor和ListView的接口 + //FoldersListAdapter继承了CursorAdapter的类 + //主要作用是便签数据库和用户的交互 + //这里就是用folder(文件夹)的形式展现给用户 + public static final String [] PROJECTION = { + NoteColumns.ID, + NoteColumns.SNIPPET + };//调用数据库中便签的ID和片段 + + public static final int ID_COLUMN = 0; + public static final int NAME_COLUMN = 1;//初始化Column的id和name,id唯一标识了Colum + + public FoldersListAdapter(Context context, Cursor c) { + super(context, c); + // TODO Auto-generated constructor stub + }//数据库操作 + + @Override + public View newView(Context context, Cursor cursor, ViewGroup parent) { + return new FolderListItem(context); + }//创建一个文件夹,对于各文件夹中子标签的初始化 + + @Override + public void bindView(View view, Context context, Cursor cursor) { + if (view instanceof FolderListItem) { + String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context + .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); + ((FolderListItem) view).bind(folderName); + } + }//将各个布局文件绑定起来 + + public String getFolderName(Context context, int position) { + 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); + } + + public void bind(String name) { + mName.setText(name); + } + } + +} diff --git a/doc/精读报告/ui/NoteEditActivity.doc b/doc/精读报告/ui/NoteEditActivity.doc new file mode 100644 index 0000000..1b32368 --- /dev/null +++ b/doc/精读报告/ui/NoteEditActivity.doc @@ -0,0 +1,877 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.app.Activity; +import android.app.AlarmManager; +import android.app.AlertDialog; +import android.app.PendingIntent; +import android.app.SearchManager; +import android.appwidget.AppWidgetManager; +import android.content.ContentUris; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.graphics.Paint; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.TextUtils; +import android.text.format.DateUtils; +import android.text.style.BackgroundColorSpan; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuItem; +import android.view.MotionEvent; +import android.view.View; +import android.view.View.OnClickListener; +import android.view.WindowManager; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + +import net.micode.notes.R; +import net.micode.notes.data.Notes; +import net.micode.notes.data.Notes.TextNote; +import net.micode.notes.model.WorkingNote; +import net.micode.notes.model.WorkingNote.NoteSettingChangedListener; +import net.micode.notes.tool.DataUtils; +import net.micode.notes.tool.ResourceParser; +import net.micode.notes.tool.ResourceParser.TextAppearanceResources; +import net.micode.notes.ui.DateTimePickerDialog.OnDateTimeSetListener; +import net.micode.notes.ui.NoteEditText.OnTextViewChangeListener; +import net.micode.notes.widget.NoteWidgetProvider_2x; +import net.micode.notes.widget.NoteWidgetProvider_4x; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +public class NoteEditActivity extends Activity implements OnClickListener, + NoteSettingChangedListener, OnTextViewChangeListener { + //该类主要是针对标签的编辑 + //继承了系统内部许多和监听有关的类 + private class HeadViewHolder { + public TextView tvModified; + + public ImageView ivAlertIcon; + + public TextView tvAlertDate; + + public ImageView ibSetBgColor; + } //使用Map实现数据存储 + + private static final Map sBgSelectorBtnsMap = new HashMap(); + static { + sBgSelectorBtnsMap.put(R.id.iv_bg_yellow, ResourceParser.YELLOW);//设置黄色的背景颜色资源选择器 + sBgSelectorBtnsMap.put(R.id.iv_bg_red, ResourceParser.RED);//设置红色的背景颜色资源选择器 + sBgSelectorBtnsMap.put(R.id.iv_bg_blue, ResourceParser.BLUE);//设置蓝色的背景颜色资源选择器 + sBgSelectorBtnsMap.put(R.id.iv_bg_green, ResourceParser.GREEN);//设置绿色的背景颜色资源选择器 + sBgSelectorBtnsMap.put(R.id.iv_bg_white, ResourceParser.WHITE);//设置白色的背景颜色资源选择器 + //put函数是将指定值和指定键相连 + } + + private static final Map sBgSelectorSelectionMap = new HashMap(); + static { + sBgSelectorSelectionMap.put(ResourceParser.YELLOW, R.id.iv_bg_yellow_select); + sBgSelectorSelectionMap.put(ResourceParser.RED, R.id.iv_bg_red_select); + sBgSelectorSelectionMap.put(ResourceParser.BLUE, R.id.iv_bg_blue_select); + sBgSelectorSelectionMap.put(ResourceParser.GREEN, R.id.iv_bg_green_select); + sBgSelectorSelectionMap.put(ResourceParser.WHITE, R.id.iv_bg_white_select); + } + + private static final Map sFontSizeBtnsMap = new HashMap(); + static { + sFontSizeBtnsMap.put(R.id.ll_font_large, ResourceParser.TEXT_LARGE); + sFontSizeBtnsMap.put(R.id.ll_font_small, ResourceParser.TEXT_SMALL); + sFontSizeBtnsMap.put(R.id.ll_font_normal, ResourceParser.TEXT_MEDIUM); + sFontSizeBtnsMap.put(R.id.ll_font_super, ResourceParser.TEXT_SUPER); + }//用户可以选择笔记本界面的大小,提供四个规格 + + private static final Map sFontSelectorSelectionMap = new HashMap(); + static { + sFontSelectorSelectionMap.put(ResourceParser.TEXT_LARGE, R.id.iv_large_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SMALL, R.id.iv_small_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_MEDIUM, R.id.iv_medium_select); + sFontSelectorSelectionMap.put(ResourceParser.TEXT_SUPER, R.id.iv_super_select); + } + + private static final String TAG = "NoteEditActivity"; + + private HeadViewHolder mNoteHeaderHolder; + + private View mHeadViewPanel; + //私有化一个界面操作mHeadViewPanel,对表头的操作 + private View mNoteBgColorSelector; + //私有化一个界面操作mNoteBgColorSelector,对背景颜色的操作 + private View mFontSizeSelector; + //私有化一个界面操作mFontSizeSelector,对标签字体的操作 + private EditText mNoteEditor; + //声明编辑控件,对文本操作 + private View mNoteEditorPanel; + //私有化一个界面操作mNoteEditorPanel,文本编辑的控制板 + private WorkingNote mWorkingNote; + //对模板WorkingNote的初始化 + private SharedPreferences mSharedPrefs;//私有化SharedPreferences的数据存储方式 + private int mFontSizeId;//用于操作字体的大小 + + private static final String PREFERENCE_FONT_SIZE = "pref_font_size";//定义常量 字体大小设置 + + private static final int SHORTCUT_ICON_TITLE_MAX_LEN = 10;//定义final常量,设置了桌面快捷方式标题的最大长度 + + public static final String TAG_CHECKED = String.valueOf('\u221A');//定义final字符串,表明已标记 + public static final String TAG_UNCHECKED = String.valueOf('\u25A1');//定义final字符串,表明未标记 + + private LinearLayout mEditTextList;//线性布局 + + private String mUserQuery;//用户请求 + private Pattern mPattern;//一个Pattern是一个正则表达式经编译后的表现模式 + + @Override + protected void onCreate(Bundle savedInstanceState) {//初始化系统的状态 + super.onCreate(savedInstanceState); + this.setContentView(R.layout.note_edit); + + if (savedInstanceState == null && !initActivityState(getIntent())) {//判断传入参数是否为空,且对activity进行初始化是否成功,满足则结束create函数 如果传入的保存的状态不为NULL时,则不会调用之后的initActivityState函数进行初始化操作 + finish(); + return; + } + initResources(); + } + + /** + * Current activity may be killed when the memory is low. Once it is killed, for another time + * user load this activity, we should restore the former state + */ + @Override + protected void onRestoreInstanceState(Bundle savedInstanceState) {//保存当前界面状态。当当前的活动界面因为释放内存而结束,再次加载活动时,可以根据保存的信息恢复到原来的状态 + super.onRestoreInstanceState(savedInstanceState); + if (savedInstanceState != null && savedInstanceState.containsKey(Intent.EXTRA_UID)) { + Intent intent = new Intent(Intent.ACTION_VIEW); + intent.putExtra(Intent.EXTRA_UID, savedInstanceState.getLong(Intent.EXTRA_UID)); + if (!initActivityState(intent)) { + finish(); + return; + } + Log.d(TAG, "Restoring from killed activity"); + } + } + + private boolean initActivityState(Intent intent) {//用户没有给出ID,就跳转到NoteListActivity + /** + * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id, + * then jump to the NotesListActivity + */ + mWorkingNote = null; + if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {//判断intent中的action是ACTION_VIEW还是ACTION_INSERT_OR_EDIT,分别进行不同的操作 + long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0); + mUserQuery = ""; + + /** + * Starting from the searched result + */ + if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {//查找intent中的数据。将数据标识符存在noteIId中,用户请求字符串存在mUserQuery中 + noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); + mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY); + } + + if (!DataUtils.visibleInNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {//如果没有找到便签标识符,就跳转到主界面 + Intent jump = new Intent(this, NotesListActivity.class); + startActivity(jump); + showToast(R.string.error_note_not_exist); + finish(); + return false; + } else { + mWorkingNote = WorkingNote.load(this, noteId);//根据noteId导入WorkingNote + if (mWorkingNote == null) {//noteId对应的活动标签为空,报错并结束活动,初始化活动返回false,即初始化活动状态位成功 + Log.e(TAG, "load note failed with note id" + noteId);//导出信息失败 反馈错误信息 + finish(); + return false; + } + } + getWindow().setSoftInputMode(//设置软键盘输入模式 + WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN//将软键盘进行隐藏 + | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);//调节Edit界面,使之适应软键盘弹出 + } else if(TextUtils.equals(Intent.ACTION_INSERT_OR_EDIT, intent.getAction())) {//判断intent的活动是INSERT OR EDIT,即新建便签 + // New note + long folderId = intent.getLongExtra(Notes.INTENT_EXTRA_FOLDER_ID, 0); + int widgetId = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_ID, + AppWidgetManager.INVALID_APPWIDGET_ID); + int widgetType = intent.getIntExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, + Notes.TYPE_WIDGET_INVALIDE); + int bgResId = intent.getIntExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, + ResourceParser.getDefaultBgId(this)); + + // Parse call-record note + String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);//下面的程序实现的功能是解析通话记录便签,首先获取intent里的电话号码 + long callDate = intent.getLongExtra(Notes.INTENT_EXTRA_CALL_DATE, 0);//获得通话日期 + if (callDate != 0 && phoneNumber != null) {//如果便签的通话日期和通话号码均存在,则把其当做通话便签进行处理,否则当做普通便签进行初始化 + if (TextUtils.isEmpty(phoneNumber)) {//如果记录的通话号码为空,则显示警告 + Log.w(TAG, "The call record number is null"); + } + long noteId = 0; + if ((noteId = DataUtils.getNoteIdByPhoneNumberAndCallDate(getContentResolver(),//根据电话号码和日期找到对应标识符,赋给noteId. + phoneNumber, callDate)) > 0) { + mWorkingNote = WorkingNote.load(this, noteId); + if (mWorkingNote == null) { + Log.e(TAG, "load call note failed with note id" + noteId); + finish(); + return false; + } + } else {//将电话号码与手机的号码簿相关联 + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, + widgetType, bgResId); + mWorkingNote.convertToCallNote(phoneNumber, callDate); + } + } else { + mWorkingNote = WorkingNote.createEmptyNote(this, folderId, widgetId, widgetType, + bgResId); + } + + getWindow().setSoftInputMode( + WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE + | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); + } else { + Log.e(TAG, "Intent not specified action, should not support");//显示错误信息,Intent没有指定动作,不应支持 + finish(); + return false; + } + mWorkingNote.setOnSettingStatusChangedListener(this); + return true; + } + + @Override + protected void onResume() {//重写Activity的onResume方法,将标签编辑界面作为界面的最上层呈现 + super.onResume(); + initNoteScreen(); + } + + private void initNoteScreen() {//初始化便签界面的窗口 + mNoteEditor.setTextAppearance(this, TextAppearanceResources + .getTexAppearanceResource(mFontSizeId)); + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果载入的workingnote对象模式为Check_List则调用switchToListMode函数 + switchToListMode(mWorkingNote.getContent());//切换到清单模式 + } else { + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));//设置文本选中的文字和长度 + mNoteEditor.setSelection(mNoteEditor.getText().length()); + } + for (Integer id : sBgSelectorSelectionMap.keySet()) {//对所有图片文件做遍历循环,将其可视性设为不可视 + findViewById(sBgSelectorSelectionMap.get(id)).setVisibility(View.GONE); + } + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId()); + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId()); + + mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this, + mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE + | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME + | DateUtils.FORMAT_SHOW_YEAR)); + + /** + * TODO: Add the menu for setting alert. Currently disable it because the DateTimePicker + * is not ready + */ + showAlertHeader(); + } + + private void showAlertHeader() {//显示便签提醒的标头 + if (mWorkingNote.hasClockAlert()) { + long time = System.currentTimeMillis();//获取当前时间,定义为long类型 + if (time > mWorkingNote.getAlertDate()) {//.如果系统时间大于了闹钟设置的时间,那么闹钟失效 + mNoteHeaderHolder.tvAlertDate.setText(R.string.note_alert_expired); + } else { + mNoteHeaderHolder.tvAlertDate.setText(DateUtils.getRelativeTimeSpanString( + mWorkingNote.getAlertDate(), time, DateUtils.MINUTE_IN_MILLIS));//如果提醒时间未到,则设置标题中显示提醒时间 + } + mNoteHeaderHolder.tvAlertDate.setVisibility(View.VISIBLE);//显示闹钟提醒的开始图标 + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.VISIBLE);//提醒时间图标显示可见 + } else { + mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE); + mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);//如果便签不包含提醒,则不显示 + }; + } + + @Override + protected void onNewIntent(Intent intent) {//当活动从后台切换但前台时会调用该函数,再次启动Activity的状态 + super.onNewIntent(intent); + initActivityState(intent); + } + + @Override + protected void onSaveInstanceState(Bundle outState) {//该函数用于分派触摸事件,其中参数MotionEvent是对屏幕触控的传递机制 + super.onSaveInstanceState(outState); + /** + * For new note without note id, we should firstly save it to + * generate a id. If the editing note is not worth saving, there + * is no id which is equivalent to create new note + */ + if (!mWorkingNote.existInDatabase()) {//当文字大小选择器可见,并且触控事件不在它的范围内时,执行下面代码 + saveNote(); + } + outState.putLong(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + Log.d(TAG, "Save working note id: " + mWorkingNote.getNoteId() + " onSaveInstanceState"); + } + + @Override + public boolean dispatchTouchEvent(MotionEvent ev) {//判断屏幕上的触控动作是否在视图范围内 + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mNoteBgColorSelector, ev)) { + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } + + if (mFontSizeSelector.getVisibility() == View.VISIBLE + && !inRangeOfView(mFontSizeSelector, ev)) { + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return super.dispatchTouchEvent(ev); + } + + private boolean inRangeOfView(View view, MotionEvent ev) { + int []location = new int[2]; + view.getLocationOnScreen(location);//获取屏幕上的起点位置 + int x = location[0]; + int y = location[1]; + if (ev.getX() < x//当触摸点的位置超出该控件的视图区域范围时,返回false + || ev.getX() > (x + view.getWidth()) + || ev.getY() < y + || ev.getY() > (y + view.getHeight())) { + return false; + } + return true; + } + + private void initResources() {//对标签各项属性内容的初始化 + mHeadViewPanel = findViewById(R.id.note_title); + mNoteHeaderHolder = new HeadViewHolder(); + mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date); + mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon); + mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date); + mNoteHeaderHolder.ibSetBgColor = (ImageView) findViewById(R.id.btn_set_bg_color); + mNoteHeaderHolder.ibSetBgColor.setOnClickListener(this); + mNoteEditor = (EditText) findViewById(R.id.note_edit_view); + mNoteEditorPanel = findViewById(R.id.sv_note_edit); + mNoteBgColorSelector = findViewById(R.id.note_bg_color_selector); + for (int id : sBgSelectorBtnsMap.keySet()) { + ImageView iv = (ImageView) findViewById(id); + iv.setOnClickListener(this); + } + + mFontSizeSelector = findViewById(R.id.font_size_selector);//为背景颜色选择界面的每一个按钮设置相对应的资源文件,并且设置了点击事件监听器 + for (int id : sFontSizeBtnsMap.keySet()) { + View view = findViewById(id); + view.setOnClickListener(this); + }; + mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);//得到用户的偏好信息,设置字体大小,如果大于资源的最大长度,设为默认大小 + mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE); + /** + * HACKME: Fix bug of store the resource id in shared preference. + * The id may larger than the length of resources, in this case, + * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE} + */ + if(mFontSizeId >= TextAppearanceResources.getResourcesSize()) {//如果Size大于TextAppearance的大小,则将之设置为默认大小 + mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE; + } + mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);//得到布局列表 + } + + @Override + protected void onPause() {//重写onPause方法,将便签编辑界面暂停 + super.onPause(); + if(saveNote()) { + Log.d(TAG, "Note data was saved with length:" + mWorkingNote.getContent().length());//暂停时即进行便签的存储,记录log文件 + } + clearSettingState(); + } + + private void updateWidget() {//更新窗口与桌面小窗口同步 + Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); + if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_2X) { + intent.setClass(this, NoteWidgetProvider_2x.class);//判断当前工作中的便签的桌面挂件的类型,并根据不同类型的桌面挂件指定Intent不同的目的组件 + } else if (mWorkingNote.getWidgetType() == Notes.TYPE_WIDGET_4X) { + intent.setClass(this, NoteWidgetProvider_4x.class); + } else { + Log.e(TAG, "Unspported widget type");//Log输出error信息,不支持的widget类型 + return; + } + + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { + mWorkingNote.getWidgetId() + }); + + sendBroadcast(intent); + setResult(RESULT_OK, intent); + } + + public void onClick(View v) {//事件点击时执行该方法 + int id = v.getId();//获取点击目标的id + if (id == R.id.btn_set_bg_color) {//如果点击的是设置背景颜色,执行下面的函数 + mNoteBgColorSelector.setVisibility(View.VISIBLE); + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + - View.VISIBLE); + } else if (sBgSelectorBtnsMap.containsKey(id)) {//将备选颜色界面设为不可见 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.GONE); + mWorkingNote.setBgColorId(sBgSelectorBtnsMap.get(id)); + mNoteBgColorSelector.setVisibility(View.GONE); + } else if (sFontSizeBtnsMap.containsKey(id)) {//判断是否是文字大小设置器中的文字大小选项按钮 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.GONE); + mFontSizeId = sFontSizeBtnsMap.get(id); + mSharedPrefs.edit().putInt(PREFERENCE_FONT_SIZE, mFontSizeId).commit(); + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE); + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//如果workingNote模式为核对列表模式,则执行下面函数 + getWorkingText(); + switchToListMode(mWorkingNote.getContent()); + } else { + mNoteEditor.setTextAppearance(this,//如果不是check模式,则设置文字编辑器中文字为相应字体大小 + TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + } + mFontSizeSelector.setVisibility(View.GONE); + } + } + + @Override + public void onBackPressed() {//点击返回键时的操作 + if(clearSettingState()) {//如果字体选择器和背景选择器均不可见,即为便签编辑界面,点击返回键退出,保存便签如果字体选择器和背景选择器可见,则点击返回键时关闭选择界面 + + return; + } + + saveNote(); + super.onBackPressed(); + } + + private boolean clearSettingState() {//清除设置状态 + if (mNoteBgColorSelector.getVisibility() == View.VISIBLE) {//将字体选择器和背景颜色选择器设为不可见 + mNoteBgColorSelector.setVisibility(View.GONE); + return true; + } else if (mFontSizeSelector.getVisibility() == View.VISIBLE) {//如果文字大小选择器可见,则将其设置为不可见 + mFontSizeSelector.setVisibility(View.GONE); + return true; + } + return false; + } + + public void onBackgroundColorChanged() {//设置背景颜色改变的监听 + findViewById(sBgSelectorSelectionMap.get(mWorkingNote.getBgColorId())).setVisibility( + View.VISIBLE);//将便签背景色设置为可见,并显示该视图 + mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());//将文件编辑区域的背景资源设置为便签背景色 + mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());//将便签头的背景资源设置为标题的背景色 + } + + @Override + public boolean onPrepareOptionsMenu(Menu menu) { + if (isFinishing()) {//如果窗口正在关闭,则不做处理 + return true; + } + clearSettingState();//清除设置状态 + menu.clear();//清除菜单项 + if (mWorkingNote.getFolderId() == Notes.ID_CALL_RECORD_FOLDER) {//如果便签所在的文件夹为便签的通话记录文件夹,执行下面函数 + getMenuInflater().inflate(R.menu.call_note_edit, menu); + } else { + getMenuInflater().inflate(R.menu.note_edit, menu); + } + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) {//判断语句判断条件为是否为清单模式,根据是否为清单模式填充不同的资源 + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_normal_mode); + } else { + menu.findItem(R.id.menu_list_mode).setTitle(R.string.menu_list_mode); + } + if (mWorkingNote.hasClockAlert()) {//如果便签中有闹钟的提醒。则菜单中的提醒按钮不可见。如果没有提醒,删除提醒按钮不可见 + menu.findItem(R.id.menu_alert).setVisible(false); + } else { + menu.findItem(R.id.menu_delete_remind).setVisible(false); + } + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) {//监听菜单中的项是否被选择 + switch (item.getItemId()) {//获得项的id,即根据菜单中不同的按钮设置不同的处理 + case R.id.menu_new_note: + createNewNote();//创建新的便签 + break; + case R.id.menu_delete: + AlertDialog.Builder builder = new AlertDialog.Builder(this);//新建一个提醒对话框实例,用于确认删除操作 + builder.setTitle(getString(R.string.alert_title_delete));//创建关于删除操作的对话框 + builder.setIcon(android.R.drawable.ic_dialog_alert);//设置对话框图标 + builder.setMessage(getString(R.string.alert_message_delete_note));//设置对话框消息内容 + builder.setPositiveButton(android.R.string.ok,//设置确认按钮,并监听它是否被点击 + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) {//设置对话框的点击函数 + deleteCurrentNote();//删除当前的便签 + finish();//结束这个activity + } + }); + builder.setNegativeButton(android.R.string.cancel, null);//设置取消按钮 + builder.show();//显示提醒对话框 + break; + case R.id.menu_font_size://菜单字体大小的设置 + mFontSizeSelector.setVisibility(View.VISIBLE);//将字体大小选择器设置为可见 + findViewById(sFontSelectorSelectionMap.get(mFontSizeId)).setVisibility(View.VISIBLE);//通过id找到相应字体的大小 + break; + case R.id.menu_list_mode://选择清单模式 + mWorkingNote.setCheckListMode(mWorkingNote.getCheckListMode() == 0 ?//设置清单模式,若当前为清单模式,则取消;否之则设为清单模式 + TextNote.MODE_CHECK_LIST : 0); + break; + case R.id.menu_share://选择分享 + getWorkingText();//获取当前便签的文本 + sendTo(this, mWorkingNote.getContent());//发送文本 + break; + case R.id.menu_send_to_desktop://选择发送到桌面 + sendToDesktop(); + break; + case R.id.menu_alert://选择设置提醒 + setReminder(); + break; + case R.id.menu_delete_remind://选择删除提醒 + mWorkingNote.setAlertDate(0, false); + break; + default: + break; + } + return true; + } + + private void setReminder() {//设置提醒器 + DateTimePickerDialog d = new DateTimePickerDialog(this, System.currentTimeMillis());//实例化一个时间日期选择器的对话框,进行提醒日期的设置 + d.setOnDateTimeSetListener(new OnDateTimeSetListener() { + public void OnDateTimeSet(AlertDialog dialog, long date) { + mWorkingNote.setAlertDate(date , true); + } + }); + d.show(); + } + + /** + * Share note to apps that support {@link Intent#ACTION_SEND} action + * and {@text/plain} type + */ + private void sendTo(Context context, String info) {//将便签的文本发送到其他支持plain类型文字显示的app中 + Intent intent = new Intent(Intent.ACTION_SEND); + intent.putExtra(Intent.EXTRA_TEXT, info); + intent.setType("text/plain"); + context.startActivity(intent); + } + + private void createNewNote() {//创建新的便签 + // Firstly, save current editing notes + saveNote(); + + // For safety, start a new NoteEditActivity + finish(); + Intent intent = new Intent(this, NoteEditActivity.class);//设置一个新的便签活动编辑器 + intent.setAction(Intent.ACTION_INSERT_OR_EDIT); + intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mWorkingNote.getFolderId()); + startActivity(intent); + } + + private void deleteCurrentNote() {//删除当前的便签 + if (mWorkingNote.existInDatabase()) { + HashSet ids = new HashSet(); + long id = mWorkingNote.getNoteId(); + if (id != Notes.ID_ROOT_FOLDER) { + ids.add(id); + } else { + Log.d(TAG, "Wrong note id, should not happen"); + } + if (!isSyncMode()) { + if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) { + Log.e(TAG, "Delete Note error"); + } + } else { + if (!DataUtils.batchMoveToFolder(getContentResolver(), ids, Notes.ID_TRASH_FOLER)) { + Log.e(TAG, "Move notes to trash folder error, should not happens"); + } + } + } + mWorkingNote.markDeleted(true); + } + + private boolean isSyncMode() {//判断是否为同步模式 + return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; + }//返回同步的用户名长度,如果大于0则有同步状态,否则非同步 + + public void onClockAlertChanged(long date, boolean set) {//设置闹钟提醒改变的监听 + /** + * User could set clock to an unsaved note, so before setting the + * alert clock, we should save the note first + */ + if (!mWorkingNote.existInDatabase()) {//如果设置提醒的便签未保存,则先保存 + saveNote(); + } + if (mWorkingNote.getNoteId() > 0) {//数据库中有该提醒的id,执行下面操作。否则,报错 + Intent intent = new Intent(this, AlarmReceiver.class); + intent.setData(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, mWorkingNote.getNoteId())); + PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); + AlarmManager alarmManager = ((AlarmManager) getSystemService(ALARM_SERVICE)); + showAlertHeader(); + if(!set) { + alarmManager.cancel(pendingIntent); + } else { + alarmManager.set(AlarmManager.RTC_WAKEUP, date, pendingIntent); + } + } else { + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Clock alert setting error"); + showToast(R.string.error_note_empty_for_clock); + } + } + + public void onWidgetChanged() { + updateWidget(); + }//当widget变化时,执行更新widget的函数 + + public void onEditTextDelete(int index, String text) {//当删除编辑文本时,执行这个函数 + int childCount = mEditTextList.getChildCount(); + if (childCount == 1) { + return; + } + + for (int i = index + 1; i < childCount; i++) { + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i - 1); + } + + mEditTextList.removeViewAt(index); + NoteEditText edit = null; + if(index == 0) { + edit = (NoteEditText) mEditTextList.getChildAt(0).findViewById( + R.id.et_edit_text); + } else { + edit = (NoteEditText) mEditTextList.getChildAt(index - 1).findViewById( + R.id.et_edit_text); + } + int length = edit.length(); + edit.append(text); + edit.requestFocus(); + edit.setSelection(length); + } + + public void onEditTextEnter(int index, String text) {//进入编辑文本框所触发的事件 + /** + * Should not happen, check for debug + */ + if(index > mEditTextList.getChildCount()) {//如果便签长度超过了限制,则提示错误 + Log.e(TAG, "Index out of mEditTextList boundrary, should not happen"); + } + + View view = getListItem(text, index); + mEditTextList.addView(view, index); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.requestFocus(); + edit.setSelection(0); + for (int i = index + 1; i < mEditTextList.getChildCount(); i++) {//遍历子文本框并设置对应对下标 + ((NoteEditText) mEditTextList.getChildAt(i).findViewById(R.id.et_edit_text)) + .setIndex(i); + } + } + + private void switchToListMode(String text) {//切换至列表模式 + mEditTextList.removeAllViews(); + String[] items = text.split("\n"); + int index = 0; + for (String item : items) { + if(!TextUtils.isEmpty(item)) { + mEditTextList.addView(getListItem(item, index)); + index++; + } + } + mEditTextList.addView(getListItem("", index)); + mEditTextList.getChildAt(index).findViewById(R.id.et_edit_text).requestFocus(); + + mNoteEditor.setVisibility(View.GONE); + mEditTextList.setVisibility(View.VISIBLE); + }//清空所有视图 初始化下标 遍历所有文本单元并添加到文本框中 优先请求此操作 便签编辑器不可见 将文本编辑框置为可见 + + private Spannable getHighlightQueryResult(String fullText, String userQuery) {//获取高亮效果的反馈结果 + SpannableString spannable = new SpannableString(fullText == null ? "" : fullText); + if (!TextUtils.isEmpty(userQuery)) { + mPattern = Pattern.compile(userQuery); + Matcher m = mPattern.matcher(fullText); + int start = 0; + while (m.find(start)) { + spannable.setSpan( + new BackgroundColorSpan(this.getResources().getColor( + R.color.user_query_highlight)), m.start(), m.end(), + Spannable.SPAN_INCLUSIVE_EXCLUSIVE); + start = m.end(); + } + } + return spannable; + } + + private View getListItem(String item, int index) {//获取列表项 + View view = LayoutInflater.from(this).inflate(R.layout.note_edit_list_item, null); + final NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + edit.setTextAppearance(this, TextAppearanceResources.getTexAppearanceResource(mFontSizeId)); + CheckBox cb = ((CheckBox) view.findViewById(R.id.cb_edit_item)); + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {//如果CheckBox已勾选,则执行下面函数,设置显示方式 + if (isChecked) {//如果已经被标记 + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + } else { + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + } + } + }); + + if (item.startsWith(TAG_CHECKED)) {//判断是否勾选 + cb.setChecked(true); + edit.setPaintFlags(edit.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); + item = item.substring(TAG_CHECKED.length(), item.length()).trim(); + } else if (item.startsWith(TAG_UNCHECKED)) { + cb.setChecked(false); + edit.setPaintFlags(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG); + item = item.substring(TAG_UNCHECKED.length(), item.length()).trim(); + } + + edit.setOnTextViewChangeListener(this); + edit.setIndex(index); + edit.setText(getHighlightQueryResult(item, mUserQuery)); + return view; + } + + public void onTextChange(int index, boolean hasText) {//便签内容发生改变所触发的事件 越界报错 如果内容不为空则将其子编辑框可见性置为可见,否则不可见 + if (index >= mEditTextList.getChildCount()) { + Log.e(TAG, "Wrong index, should not happen"); + return; + } + if(hasText) { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.VISIBLE); + } else { + mEditTextList.getChildAt(index).findViewById(R.id.cb_edit_item).setVisibility(View.GONE); + } + } + + public void onCheckListModeChanged(int oldMode, int newMode) {//监听清单模式的变化 + if (newMode == TextNote.MODE_CHECK_LIST) { + switchToListMode(mNoteEditor.getText().toString()); + } else { + if (!getWorkingText()) { + mWorkingNote.setWorkingText(mWorkingNote.getContent().replace(TAG_UNCHECKED + " ", + "")); + } + mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery)); + mEditTextList.setVisibility(View.GONE); + mNoteEditor.setVisibility(View.VISIBLE); + } + }//如果新模式为列表模式,则调用switchToListMode()方法将便签编辑器的文本切换到列表模式,否则若是获取到文本就改变其检查标记,修改文本编辑器的内容和可见性 + + private boolean getWorkingText() {//获取当前活动便签的文本并保存到数据库中 + boolean hasChecked = false;//初始化check标记 + if (mWorkingNote.getCheckListMode() == TextNote.MODE_CHECK_LIST) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mEditTextList.getChildCount(); i++) { + View view = mEditTextList.getChildAt(i); + NoteEditText edit = (NoteEditText) view.findViewById(R.id.et_edit_text); + if (!TextUtils.isEmpty(edit.getText())) { + if (((CheckBox) view.findViewById(R.id.cb_edit_item)).isChecked()) { + sb.append(TAG_CHECKED).append(" ").append(edit.getText()).append("\n"); + hasChecked = true; + } else { + sb.append(TAG_UNCHECKED).append(" ").append(edit.getText()).append("\n"); + } + } + } + mWorkingNote.setWorkingText(sb.toString()); + } else { + mWorkingNote.setWorkingText(mNoteEditor.getText().toString()); + } + return hasChecked; + }//如果当前工作便签为清单模式,转化为文字形式保存其数据否则直接保存文字数据到数据库中 + + private boolean saveNote() {//保存便签 + getWorkingText(); + boolean saved = mWorkingNote.saveNote(); + if (saved) { + /** + * There are two modes from List view to edit view, open one note, + * create/edit a node. Opening node requires to the original + * position in the list when back from edit view, while creating a + * new node requires to the top of the list. This code + * {@link #RESULT_OK} is used to identify the create/edit state + */ + setResult(RESULT_OK); + } + return saved; + } + + private void sendToDesktop() {//将便签发送至桌面 + /** + * Before send message to home, we should make sure that current + * editing note is exists in databases. So, for new note, firstly + * save it + */ + if (!mWorkingNote.existInDatabase()) { + saveNote(); + }//核对正编辑的便签是否存在于数据库中,若不存在,则先保存便签 + + if (mWorkingNote.getNoteId() > 0) {//若便签的id大于0,则执行以下程序 + Intent sender = new Intent(); + Intent shortcutIntent = new Intent(this, NoteEditActivity.class); + shortcutIntent.setAction(Intent.ACTION_VIEW); + shortcutIntent.putExtra(Intent.EXTRA_UID, mWorkingNote.getNoteId()); + sender.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); + sender.putExtra(Intent.EXTRA_SHORTCUT_NAME, + makeShortcutIconTitle(mWorkingNote.getContent())); + sender.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, + Intent.ShortcutIconResource.fromContext(this, R.drawable.icon_app)); + sender.putExtra("duplicate", true); + sender.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); + showToast(R.string.info_note_enter_desktop); + sendBroadcast(sender);//建立发送到桌面的连接器 链接为一个视图 将便签的相关信息都添加到要发送的文件里 设置sneder的行为是发送 + } else {//如果便签的id错误,则保存提醒用户 + /** + * There is the condition that user has input nothing (the note is + * not worthy saving), we have no note id, remind the user that he + * should input something + */ + Log.e(TAG, "Send to desktop error"); + showToast(R.string.error_note_empty_for_send_to_desktop); + } + } + + private String makeShortcutIconTitle(String content) {//编辑小图标的标题 + content = content.replace(TAG_CHECKED, ""); + content = content.replace(TAG_UNCHECKED, ""); + return content.length() > SHORTCUT_ICON_TITLE_MAX_LEN ? content.substring(0, + SHORTCUT_ICON_TITLE_MAX_LEN) : content; + }//直接设置为content中的内容并返回,有勾选和未勾选2种 + + private void showToast(int resId) { + showToast(resId, Toast.LENGTH_SHORT); + }//显示提示的视图 + + private void showToast(int resId, int duration) {//持续显示提示的视图 + Toast.makeText(this, resId, duration).show(); + } +} diff --git a/doc/精读报告/ui/NoteEditText.doc b/doc/精读报告/ui/NoteEditText.doc new file mode 100644 index 0000000..9318ea6 --- /dev/null +++ b/doc/精读报告/ui/NoteEditText.doc @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.micode.notes.ui; + +import android.content.Context; +import android.graphics.Rect; +import android.text.Layout; +import android.text.Selection; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.style.URLSpan; +import android.util.AttributeSet; +import android.util.Log; +import android.view.ContextMenu; +import android.view.KeyEvent; +import android.view.MenuItem; +import android.view.MenuItem.OnMenuItemClickListener; +import android.view.MotionEvent; +import android.widget.EditText; + +import net.micode.notes.R; + +import java.util.HashMap; +import java.util.Map; +//继承edittext,设置便签设置文本框 +public class NoteEditText extends EditText { + private static final String TAG = "NoteEditText"; + private int mIndex; + private int mSelectionStartBeforeDelete; + + private static final String SCHEME_TEL = "tel:" ; + private static final String SCHEME_HTTP = "http:" ; + private static final String SCHEME_EMAIL = "mailto:" ; + //建立一个字符和整数的hash表,用于链接电话,网站,还有邮箱 + private static final Map sSchemaActionResMap = new HashMap(); + //一个字符串和文本的静态映射的哈希表,将字符串转化成文本内容,然后放在弹出文本框内 + static { + sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); + sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); + sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); + } + + /** + * Call by the {@link NoteEditActivity} to delete or add edit text + */ + public interface OnTextViewChangeListener {//该接口用于实现对TextView组件中的文字信息进行修改 + /** + * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens + * and the text is null + */ + void onEditTextDelete(int index, String text);//当delete键按下时删除当前编辑的文字块 + + /** + * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} + * happen + */ + void onEditTextEnter(int index, String text);//当enter键按下时添加一个文字编辑块 + + /** + * Hide or show item option when text change + */ + void onTextChange(int index, boolean hasText);//当文字发生变化时隐藏或者显示设置 + } + + private OnTextViewChangeListener mOnTextViewChangeListener;//声明文本视图变化监听器 + + public NoteEditText(Context context) {//下面有三个构造函数,继承父类的方法,各个参数不同 + super(context, null); + mIndex = 0; + } + + public void setIndex(int index) { + mIndex = index; + } + + public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { + mOnTextViewChangeListener = listener; + } + + public NoteEditText(Context context, AttributeSet attrs) {//下面两个函数都是NoteEditText的构造函数,它们同样继承了父类的构造函数,不同的是它们调用的参数不一样 + super(context, attrs, android.R.attr.editTextStyle); + } + + public NoteEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO Auto-generated constructor stub + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + //触摸屏幕编辑便签时触发,参数event为手机屏幕触摸事件封装类的对象,其中封装了该事件的所有信息,例如触摸的位置、触摸的类型以及触摸的时间等。该对象会在用户触摸手机屏幕时被创 + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN://重写屏幕触发事件 + + int x = (int) event.getX(); + int y = (int) event.getY(); + x -= getTotalPaddingLeft();//减去左边控件的距离 + y -= getTotalPaddingTop(); + x += getScrollX();//加上滚轮滚过的距离 + y += getScrollY(); + + Layout layout = getLayout();//用布局控件layout根据x,y的新值设置新的位置 + int line = layout.getLineForVertical(y); + int off = layout.getOffsetForHorizontal(line, x); + Selection.setSelection(getText(), off); + break; + } + + return super.onTouchEvent(event);//这是调用父类的方法,当屏幕有Touch事件时,此方法就会被调用 + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + //mOnTextViewChangeListener是上面接口OnTextViewChangeListener的引用,指向初始化时的listener对象,该对象是OnTextViewChangeListener的实现类的对象,接口无法直接实例化。mOnTextViewChangeListener标志着文本是否被改变。 + return false; + } + break; + case KeyEvent.KEYCODE_DEL: + mSelectionStartBeforeDelete = getSelectionStart();//获取删除文本开始位置 + break; + default: + break; + } + return super.onKeyDown(keyCode, event);//调用父类的方法,响应其他按键,如数字键和字母键等 + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) {//处理用户松开一个键盘按键时会触发的事件 + switch(keyCode) { + case KeyEvent.KEYCODE_DEL: + if (mOnTextViewChangeListener != null) {//如果文本视图发生变化 + if (0 == mSelectionStartBeforeDelete && mIndex != 0) {//若之前有被修改并且文档不为空 + mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString());//监听文本的删除 + return true; + } + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted");////其他情况报错,文档的改动监听器并没有建立 + } + break; + case KeyEvent.KEYCODE_ENTER: + if (mOnTextViewChangeListener != null) { + int selectionStart = getSelectionStart();////获取当前位置 + String text = getText().subSequence(selectionStart, length()).toString();//获取选择区域后面的文本信息 + setText(getText().subSequence(0, selectionStart));//根据获取的文本设置当前文本 + mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text);//将选择区域内的文字移到下一行 + } else { + Log.d(TAG, "OnTextViewChangeListener was not seted");//其他情况报错,监听器OnTextViewChangeListener并没有建立 + } + break; + default: + break; + } + return super.onKeyUp(keyCode, event);//继续执行父类的其他按键弹起的事件 + } + + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {//当焦点发生变化时,会自动调用该方法来处理焦点改变的事件 + if (mOnTextViewChangeListener != null) { + if (!focused && TextUtils.isEmpty(getText())) { + mOnTextViewChangeListener.onTextChange(mIndex, false);//mOnTextViewChangeListener子函数,置false隐藏事件选项 + } else { + mOnTextViewChangeListener.onTextChange(mIndex, true);//mOnTextViewChangeListener子函数,置true显示事件选项 + + } + } + super.onFocusChanged(focused, direction, previouslyFocusedRect);//继续执行父类的其他焦点变化的事件 + } + + @Override + protected void onCreateContextMenu(ContextMenu menu) {//生成上下文菜单 + if (getText() instanceof Spanned) {//如果有文本存在 + int selStart = getSelectionStart(); + int selEnd = getSelectionEnd();//获取文本开始和结尾位置 + + int min = Math.min(selStart, selEnd); + int max = Math.max(selStart, selEnd);//获取开始到结尾的最大、最小值 + + final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class);//获取一段text内容,并且把这段内容强制转换为Spanned类型,并存入URLSpan数组urls中 + if (urls.length == 1) { + int defaultResId = 0; + for(String schema: sSchemaActionResMap.keySet()) { + if(urls[0].getURL().indexOf(schema) >= 0) {//若url可以添加则在添加后将defaultResId置为key所映射的值 + defaultResId = sSchemaActionResMap.get(schema); + break; + } + } + + if (defaultResId == 0) {//defaultResId == 0则说明url并没有添加任何东西,所以置为连接其他SchemaActionResMap的值 + defaultResId = R.string.note_link_other; + } + + menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( + new OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) {//如果点击菜单执行操作 + // goto a new intent + urls[0].onClick(NoteEditText.this);//根据相应的文本设置菜单的按键 + return true; + } + }); + } + } + super.onCreateContextMenu(menu);//继续执行父类的其他菜单创建的事件 + } +}