Compare commits

...

7 Commits

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

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

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

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

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

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

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

@ -0,0 +1,955 @@
/*
* 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;//这个类包含在net.micode.notes.ui这个包里
import android.app.Activity;//引入了一系列实现这个类功能所必须的类
import android.app.AlertDialog;
import android.app.Dialog;
import android.appwidget.AppWidgetManager;//APP的界宽
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;//文本
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;//光标
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;//文本观察器
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;//文本菜单
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;//菜单条款
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;//主界面,一进入就是这个界面
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;//输入方法
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;//点击监听
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;//文本视图
import android.widget.Toast;
import net.micode.notes.R;//Android自动生成的R类在该类中根据不同的资源类型又生成了相应的内部类该类包含了系统中使用到的所有资源文件的标示。
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;//远程
import net.micode.notes.model.WorkingNote;
import net.micode.notes.tool.BackupUtils;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;
import java.io.BufferedReader;
import java.io.IOException;//输入板块
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;//引入了一系列实现这个类功能所必须的类
//小米便签主页面
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {//这个类继承于Activity类实现了两个接口分别是点击监听器和长按监听器即在这个类的界面实现对这两种操作的响应这是整个project的主类
private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;//声明并赋值一些不可更改的私有属性
private static final int FOLDER_LIST_QUERY_TOKEN = 1;//查询记号,同上,文件夹请求时使用(如:长按便签然后点移动到文件夹调用)
private static final int MENU_FOLDER_DELETE = 0;//删除菜单文件
private static final int MENU_FOLDER_VIEW = 1;//菜单中的查看文件夹对应的int值
private static final int MENU_FOLDER_CHANGE_NAME = 2;//.菜单中改文件夹名项对应的int值
private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";//用于第一次打开小米便签的判断
private enum ListEditState {//列表编辑状态类
NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
};
private ListEditState mState;//利用其它类声明一些私有对象
private BackgroundQueryHandler mBackgroundQueryHandler;//后台疑问处理
private NotesListAdapter mNotesListAdapter;//便签列表配适器
private ListView mNotesListView;//主界面的视图
private Button mAddNewNote;//最下方添加便签的按钮
private boolean mDispatch;//是否调度的判断变量
private int mOriginY;//首次触摸时屏幕上的垂直距离y值
private int mDispatchY;//重新调度时的触摸的在屏幕上的垂直距离
private TextView mTitleBar;//子文件夹下的 标头
private long mCurrentFolderId;//当前文件夹的ID
private ContentResolver mContentResolver;//提供内容分析
private ModeCallback mModeCallBack;//返回调用方法
private static final String TAG = "NotesListActivity";//名称(可用于日志文件调试)
public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;//列表滚动速度
private NoteItemData mFocusNoteDataItem;//光标指向的物件的数据内容
private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";//定义私有字符串变量
private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"//用于表明处于父文件夹下(主列表)
+ Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
+ NoteColumns.NOTES_COUNT + ">0)";
private final static int REQUEST_CODE_OPEN_NODE = 102;//请求代码开放节点
private final static int REQUEST_CODE_NEW_NODE = 103;//请求代码新节点
@Override
protected void onCreate(Bundle savedInstanceState) {//创建类
super.onCreate(savedInstanceState);//super调用父类的protected函数,创建窗口时使用
setContentView(R.layout.note_list);//设置内容的视图
initResources();//初始化资源
/**
* Insert an introduction when user firstly use this application
*/
setAppInfoFromRawRes();//当第一次使用这个app的时候插入介绍信息
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {//对子模块的一些数据进行分析
if (resultCode == RESULT_OK
&& (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {//当被销毁的活动是打开便签或者新建便签,且结果码匹配时,把从编辑界面的光标数据删除
mNotesListAdapter.changeCursor(null);
} else {//super调用父类的protected函数,创建窗口时使用
super.onActivityResult(requestCode, resultCode, data);// 调用父类的方法
}
}
private void setAppInfoFromRawRes() {//通过原生资源设置APP信息
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);//SharedPreferences类用于保存配置参数
if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {//添加新的偏好设置
StringBuilder sb = new StringBuilder();//读取原生资源信息
InputStream in = null;//输入流初始设置为空
try {//从原始配置文件当中获取基本信息
in = getResources().openRawResource(R.raw.introduction);//加载Welcome to use MIUI notes!本地xml文件
if (in != null) {//如果信息不为空
InputStreamReader isr = new InputStreamReader(in);// 使用指定的字符集读取字节并将它们解码为字符
BufferedReader br = new BufferedReader(isr);//构建输入管道
char [] buf = new char[1024];
int len = 0;
while ((len = br.read(buf)) > 0) {//read读取一个字符若读取到末尾则返回-1这里是加载到buf中
sb.append(buf, 0, len);//使用append函数在指定元素的结尾插入内容
}
} else {
Log.e(TAG, "Read introduction file error");//报错,读取文件错误
return;
}
} catch (IOException e) {//IO出错打印异常信息
e.printStackTrace();//在命令行打印异常信息在程序中出错的位置及原因
return;
} finally {//close语句会自动执行不需要显示的调用
if(in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();//输出栈轨迹
}
}
}
WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,//创建新便签
AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
ResourceParser.RED);
note.setWorkingText(sb.toString());//设置文本数据
if (note.saveNote()) {//这是一个判断语句,判断便签是否保存成功
sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();//保存note的数据信息
} else {
Log.e(TAG, "Save introduction note error");//如果便签保存不成功,则把错误信息打印到日志里面。
return;
}
}
}
@Override
protected void onStart() {//在OnCreate函数运行完之后执行。用于获取便签列表
super.onStart();//调用父类,启动活动
startAsyncNotesListQuery();//同步列表中的便签信息
}
private void initResources() {//初始化资源
mContentResolver = this.getContentResolver();//获取应用程序的数据,得到类似数据表的东西
mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());//动态创建后台请求处理器的实例
mCurrentFolderId = Notes.ID_ROOT_FOLDER;//当前文件夹ID是根目录ID
mNotesListView = (ListView) findViewById(R.id.notes_list);//根据R文件中的id值查询到相应的View,然后返回
mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null),
null, false);//使用布局填充器增加页脚视图
mNotesListView.setOnItemClickListener(new OnListItemClickListener());// 设置视图点击监听器
mNotesListView.setOnItemLongClickListener(this);//设置长按监听器
mNotesListAdapter = new NotesListAdapter(this);//创建便签视图配置器
mNotesListView.setAdapter(mNotesListAdapter);//.设置便签视图配置器
mAddNewNote = (Button) findViewById(R.id.btn_new_note);//在activity中要获取该按钮
mAddNewNote.setOnClickListener(this);//屏幕点击监视
mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());//屏幕点击监听
mDispatch = false;//是否调度,主要用于新建便签模块
mDispatchY = 0;//初始y值设置为0
mOriginY = 0;//加载文件夹下的标头资源
mTitleBar = (TextView) findViewById(R.id.tv_title_bar);//设置Title bar也就是app页面顶部的返回、选项、信息描述
mState = ListEditState.NOTE_LIST;//功能描述:设置状态
mModeCallBack = new ModeCallback();//.implements是一个类实现连接一个接口用的关键字它是用来实现接口中定义的抽象方法
}
private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {// implements声明自己使用一个或多个接口
private DropdownMenu mDropDownMenu;//下拉菜单
private ActionMode mActionMode;//动作方式
private MenuItem mMoveMenu;//移动菜单
public boolean onCreateActionMode(ActionMode mode, Menu menu) {// 根据菜单和动作创建新动作
getMenuInflater().inflate(R.menu.note_list_options, menu);//layout的xml布局文件实例化为View类对象
menu.findItem(R.id.delete).setOnMenuItemClickListener(this);//为便签删除模块设定监听器
mMoveMenu = menu.findItem(R.id.move);//调用下面的更新菜单函数
if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
|| DataUtils.getUserFolderCount(mContentResolver) == 0) {//如果父类id在文件夹中保存或者用户文件数量为零设置移动菜单为不可见否者设为可见
mMoveMenu.setVisible(false);
} else {//设置菜单项目为可见
mMoveMenu.setVisible(true);//当长按某一标签时,会执行这个,让 移动到文件夹 按键变得可见
mMoveMenu.setOnMenuItemClickListener(this);//设置菜单项监听器
}
mActionMode = mode;
mNotesListAdapter.setChoiceMode(true);//进入选择模式
mNotesListView.setLongClickable(false);//关闭长按列表项发生事件功能
mAddNewNote.setVisibility(View.GONE);//隐藏了新增便签按钮
View customView = LayoutInflater.from(NotesListActivity.this).inflate(//设置用户界面
R.layout.note_list_dropdown_menu, null);//加载下拉菜单的布局
mode.setCustomView(customView);
mDropDownMenu = new DropdownMenu(NotesListActivity.this,//创建新的下拉菜单
(Button) customView.findViewById(R.id.selection_menu),
R.menu.note_list_dropdown);//为view添加dropDownMenu包含一个全选操作
mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
public boolean onMenuItemClick(MenuItem item) {//点击菜单时,设置为全选并更新菜单
mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());// 对应下拉菜单里的全选按键
updateMenu();//更新菜单
return true;
}
});//更新下拉菜单
return true;
}
private void updateMenu() {//在多选便签/便签文件夹时调用,用于更新多选下拉菜单
int selectedCount = mNotesListAdapter.getSelectedCount();//获取被勾选的条目数量
// Update dropdown menu
String format = getResources().getString(R.string.menu_select_title, selectedCount);//从原始资源中读取信息更改下拉菜单内容
mDropDownMenu.setTitle(format);//更改标题
MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);//通过判断是否全选选项
if (item != null) {//当全选成功,则将“全选”菜单项改为“取消全选”菜单,否则仍保持“全选”菜单项。
if (mNotesListAdapter.isAllSelected()) {//若便签被全选,则给出全不选按钮, 否则给出全选按钮
item.setChecked(true);//若便签被全选,则给出全不选按钮, 否则给出全选按钮
item.setTitle(R.string.menu_deselect_all);
} else {
item.setChecked(false);
item.setTitle(R.string.menu_select_all);
}
}
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {//准备动作模式
// TODO Auto-generated method stub
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {//菜单动作触发标记
// TODO Auto-generated method stub
return false;
}
public void onDestroyActionMode(ActionMode mode) {//销毁动作模式,设置便签可见
mNotesListAdapter.setChoiceMode(false);//设置笔记列表适配器选择方式
mNotesListView.setLongClickable(true);//长按操作
mAddNewNote.setVisibility(View.VISIBLE);//调整新建笔记为可见
}
public void finishActionMode() {
mActionMode.finish();
}//菜单勾选状态改变
public void onItemCheckedStateChanged(ActionMode mode, int position, long id,//勾选状态改变时,更改勾选标志,更新菜单
boolean checked) {//点击菜单选项触发操作
mNotesListAdapter.setCheckedItem(position, checked);//改变勾选的状态
updateMenu();//更新菜单
}
public boolean onMenuItemClick(MenuItem item) {//判断菜单是否被点击
if (mNotesListAdapter.getSelectedCount() == 0) {//如果一次都没有点击,创建新的文本显示出来
Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),//Toast-Android系统中一种消息框类型
Toast.LENGTH_SHORT).show();
return true;
}
switch (item.getItemId()) {//根据id号判断是删除还是移动
case R.id.delete://删除菜单项
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);//警告对话框
builder.setTitle(getString(R.string.alert_title_delete));//设置“删除选中的便签”的title
builder.setIcon(android.R.drawable.ic_dialog_alert);//设置提醒删除的图片
builder.setMessage(getString(R.string.alert_message_delete_notes,
mNotesListAdapter.getSelectedCount()));//设置警告对话框的图标
builder.setPositiveButton(android.R.string.ok,//设置否定按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
batchDelete();//执行批量删除操作
}
});
builder.setNegativeButton(android.R.string.cancel, null);//取消按键的视图
builder.show();
break;
case R.id.move:// 移动便签到文件夹
startQueryDestinationFolders();//启动查询目标文件函数
break;
default://defaultswitch语句结束
return false;
}
return true;
}
}
private class NewNoteOnTouchListener implements OnTouchListener {//触摸便签监听器
public boolean onTouch(View v, MotionEvent event) {//新建便签的触摸事件的处理
switch (event.getAction()) {//获取不同动作对应不同操作
case MotionEvent.ACTION_DOWN: {//如果是创建新便签,通过计算调整界面大小
Display display = getWindowManager().getDefaultDisplay();
int screenHeight = display.getHeight();//获取屏幕高度
int newNoteViewHeight = mAddNewNote.getHeight();// 获取新增便签的高度
int start = screenHeight - newNoteViewHeight;//起始的y值
int eventY = start + (int) event.getY();//event.getY相当于点击到的地方的y值
/**
* Minus TitleBar's height
*/
if (mState == ListEditState.SUB_FOLDER) {//减去标题栏的高度
eventY -= mTitleBar.getHeight();
start -= mTitleBar.getHeight();
}
/**
* HACKME:When click the transparent part of "New Note" button, dispatch//点击某个区域
* the event to the list view behind this button. The transparent part of
* "New Note" button could be expressed by formula y=-0.12x+94Unit:pixel
* and the line top of the button. The coordinate based on left of the "New
* Note" button. The 94 represents maximum height of the transparent part.//点击按键
* Notice that, if the background of the button changes, the formula should
* also change. This is very bad, just for the UI designer's strong requirement.
*/
if (event.getY() < (event.getX() * (-0.12) + 94)) {//如果当前点击的位置不在“写便签”区域内
View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1//最后得到最后一个元素的view视图
- mNotesListView.getFooterViewsCount());//减去页脚下元素布局数量
if (view != null && view.getBottom() > start// 如果不在新建便签的按钮上,重新调度响应按键
&& (view.getTop() < (start + 94))) {
mOriginY = (int) event.getY();//初始按下时的垂直距离
mDispatchY = eventY;//调度时的垂直距离
event.setLocation(event.getX(), mDispatchY);//重新给触摸事件定位
mDispatch = true;//触摸事件定位
return mNotesListView.dispatchTouchEvent(event);//重新调度,即重新执行
}
}
break;
}
case MotionEvent.ACTION_MOVE: {// 如果是移动操作,调度动作顺序
if (mDispatch) {
mDispatchY += (int) event.getY() - mOriginY;//移动后,触摸事件位置发生变换
event.setLocation(event.getX(), mDispatchY);//重新赋值
return mNotesListView.dispatchTouchEvent(event);//重新调度,即重新执行
}
break;
}
default: {//其他情况
if (mDispatch) {
event.setLocation(event.getX(), mDispatchY);// 重新赋值
mDispatch = false;
return mNotesListView.dispatchTouchEvent(event);// 重新调度,即重新执行
}
break;
}
}
return false;
}
};
private void startAsyncNotesListQuery() {//开始NoteList对数据库的异步查询
String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION
: NORMAL_SELECTION;//如果当前文件id与保存在文件夹的id相同selection为文件夹模式否则为常规模式
mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,//后台异步对数据库进行操作,加快数据处理速度
Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] {
String.valueOf(mCurrentFolderId)
}, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
}
private final class BackgroundQueryHandler extends AsyncQueryHandler {//背景请求处理器
public BackgroundQueryHandler(ContentResolver contentResolver) {
super(contentResolver);
}//调用父类的方法
@Override//查询完成后对光标的处理
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {//查询完成后对光标的处理
switch (token) {
case FOLDER_NOTE_LIST_QUERY_TOKEN //如果是便签查询被采用,更改光标位置
mNotesListAdapter.changeCursor(cursor);//如果是便签查询被采用,更改光标位置
break;
case FOLDER_LIST_QUERY_TOKEN://获取文件夹请求
if (cursor != null && cursor.getCount() > 0) {//如果下面有便签,打开文件夹列表弹窗
showFolderListMenu(cursor);//显示文件夹列表菜单,以提示对话框的形式
} else {
Log.e(TAG, "Query folder failed");//写入错误异常日志
}
break;//创建新便签
default:
return;
}
}
}
private void showFolderListMenu(Cursor cursor) {//执行批量删除的操作
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);//声明一个警告对话框
builder.setTitle(R.string.menu_title_select_folder);//对话框的title是“选择文件夹”
final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);//文件夹列表配适器
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {//为对话框设置监听事件
public void onClick(DialogInterface dialog, int which) {//点击事件的处理方法
DataUtils.batchMoveToFolder(mContentResolver,//移动到文件夹下
mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
Toast.makeText(
NotesListActivity.this,
getString(R.string.format_move_notes_to_folder,//移动便签进入文件夹
mNotesListAdapter.getSelectedCount(),
adapter.getFolderName(NotesListActivity.this, which)),
Toast.LENGTH_SHORT).show();
mModeCallBack.finishActionMode();//批量移动操作完成
}
});
builder.show();//显示对话框
}
private void createNewNote() {//创建新的便签
Intent intent = new Intent(this, NoteEditActivity.class);//新建一个意图与NoteEditActivity相关联
intent.setAction(Intent.ACTION_INSERT_OR_EDIT);//参数为键名
intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);//设置键对值
this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);//这个活动发出请求,等待下一个活动返回数据
}
private void batchDelete() {//批量删除便签
new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {//批量删除:删除时候,会判断是否为桌面挂件
protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
if (!isSyncMode()) {//异步处理任务
// if not synced, delete notes directly
if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
.getSelectedItemIds())) {
} else {//如果不是同步模式则将笔记移到垃圾文件夹,若转移失败打印错误信息
Log.e(TAG, "Delete notes error, should not happens");//处于同步模式则将删除的便签移入回收文件夹
}
} else {
// in sync mode, we'll move the deleted note into the trash//如果在同步模式,会将便签移动到“垃圾箱”文件夹
// folder
if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter//同步状态先放入垃圾箱
.getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {//同步状态先放入回收站
Log.e(TAG, "Move notes to trash folder error, should not happens");
}
}
return widgets;//桌面widget修改
}
@Override
protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {//遍历所有的widget
if (widgets != null) {
for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID//此处判断是否为一个widget
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {//更新widget信息
updateWidget(widget.widgetId, widget.widgetType);//更新桌面挂件
}
}
}//结束动作
mModeCallBack.finishActionMode();//结束动作
}
}.execute();
}
private void deleteFolder(long folderId) {//删除文件夹
if (folderId == Notes.ID_ROOT_FOLDER) {//不在列表里,输出错误信息
Log.e(TAG, "Wrong folder id, should not happen " + folderId);
return;
}
HashSet<Long> ids = new HashSet<Long>();//初始化一个哈希表
ids.add(folderId);// 把文件夹id加入进去
HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
folderId);
if (!isSyncMode()) {//如果不同步,直接删除
// if not synced, delete folder directly
DataUtils.batchDeleteNotes(mContentResolver, ids);//如同步将被删除的文件夹放入trash文件夹中
} else {//否则放到回收站
// in sync mode, we'll move the deleted folder into the trash folder//处于同步模式则放到“垃圾桶”文件夹里
DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);//处于同步模式则放到回收站
}
if (widgets != null) {//如果存在对应桌面挂件那么判断挂件信息如果挂件id有效且挂件类型有效则更新挂件信息
for (AppWidgetAttribute widget : widgets) {
if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
&& widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
updateWidget(widget.widgetId, widget.widgetType);
}
}
}
}
private void openNode(NoteItemData data) {//打开节点,参数为数据
Intent intent = new Intent(this, NoteEditActivity.class);//打开便签,创建新的活动,并且等待返回值
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(Intent.EXTRA_UID, data.getId());//目的数据
this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
}
private void openFolder(NoteItemData data) {//打开文件夹
mCurrentFolderId = data.getId();//获取当前文件夹的ID
startAsyncNotesListQuery();//开始异步的便签列表反馈
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//如果当前id是保存在文件夹的id将列表编辑状态置为call文件夹否则设置为镜像文件夹
mState = ListEditState.CALL_RECORD_FOLDER;//对标题栏的操作
mAddNewNote.setVisibility(View.GONE);//将button“新建便签”置为不可见
} else {//不然状态设置为子文件夹
mState = ListEditState.SUB_FOLDER;
}
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//如果当前id是保存在文件夹的id设置标题内容为文件夹名字否则设置为文本的前部片段内容
mTitleBar.setText(R.string.call_record_folder_name);//title设置为call notes
} else {
mTitleBar.setText(data.getSnippet());//否则文本的前部片段内容,即文件夹名称
}
mTitleBar.setVisibility(View.VISIBLE);//将Activity的title设置为可见
}
public void onClick(View v) {//点击时进行的响应
switch (v.getId()) {//得到我们所点击组件的ID号并进行判断
case R.id.btn_new_note://当点击的组件是btn_new_note的时候创建一个新的标签
createNewNote();//创建一个新的便签
break;
default:
break;
}
}
private void showSoftInput() {//显示软键盘
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);//获取方法的管理者对象
if (inputMethodManager != null) {//若输入为空,进行对应操作
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);//使软键盘显示第二个参数hideFlags用来设置是否隐藏等于0
}
}
private void hideSoftInput(View view) {//关闭键盘
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);//隐藏软键盘
}
private void showCreateOrModifyFolderDialog(final boolean create) {//显示创建或者修改文件夹的对话框
final AlertDialog.Builder builder = new AlertDialog.Builder(this);//初始化对话框
View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);//图形创建,编辑对话框
final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);//编辑文本通过ID获取名称.
showSoftInput();//显示键盘
if (!create) {//如果create==false将对话框标题设置为 修改文件夹名称,否则设置为新建文件夹
if (mFocusNoteDataItem != null) {//如果长按的对象focus对象不等于null
etName.setText(mFocusNoteDataItem.getSnippet());//获取片段来设置文档
builder.setTitle(getString(R.string.menu_folder_change_name));//通过构建器设置标题
} else {//显示此次点击显示为空
Log.e(TAG, "The long click data item is null");//载入标签tag报错
return;
}
} else {//新建一个目录文件夹
etName.setText("");//否则设置空文本
builder.setTitle(this.getString(R.string.menu_create_folder));//设置“创建文件”的标题
}
builder.setPositiveButton(android.R.string.ok, null);//对话框设置确定和取消按钮
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {//构建器_创建取消的按键
public void onClick(DialogInterface dialog, int which) {//点击触发软键盘隐藏
hideSoftInput(etName);//:隐藏输入法软键盘
}
});
final Dialog dialog = builder.setView(view).show();//将上述对话框实例化并显示在屏幕上
final Button positive = (Button)dialog.findViewById(android.R.id.button1);//创建对话框的确认按钮
positive.setOnClickListener(new OnClickListener() {//设置点击监听器
public void onClick(View v) {//新建文件夹或者修改文件夹名同时判断其是否合法
hideSoftInput(etName);//点击确定后收起软键盘
String name = etName.getText().toString();//获取当前可编辑文本框etName的文本内容
if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {//检测可视文件夹的名字
Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),//显示提示信息“文件夹name已存在请重新命名
Toast.LENGTH_LONG).show();
etName.setSelection(0, etName.length());//全选当前字符串
return;
}
if (!create) {//若未创建
if (!TextUtils.isEmpty(name)) {//如果输入不为空
ContentValues values = new ContentValues();//创建内容取值
values.put(NoteColumns.SNIPPET, name);//将片段名字添加入value
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);//将文件夹类型添加入value
values.put(NoteColumns.LOCAL_MODIFIED, 1);//将本地修改添加入value
mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
+ "=?", new String[] {//将内容笔记URI及笔记专栏ID更新至内容解决器
String.valueOf(mFocusNoteDataItem.getId())//如果修改文件夹名字操作成功,则更新数据库内容
});
}
} else if (!TextUtils.isEmpty(name)) {//如果是新建文件夹操作
ContentValues values = new ContentValues();
values.put(NoteColumns.SNIPPET, name);//将SNIPPET加入内容值中
values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);//将TYPE加入内容值中
mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);//将内容_笔记的URI插入到内容解决器
}
dialog.dismiss();//撤销对话框
}
});
if (TextUtils.isEmpty(etName.getText())) {//若文本为空确认按钮设置使能为false
positive.setEnabled(false);
}
/**
* When the name edit text is null, disable the positive button
*/
etName.addTextChangedListener(new TextWatcher() {//添加文本改变监听器
public void beforeTextChanged(CharSequence s, int start, int count, int after) {//判断是否在文本更改之前
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {//当前文本改变触发,文本为空按键不可用,不为空则可用
if (TextUtils.isEmpty(etName.getText())) {//如果文件夹名称为空,那么便不可用
positive.setEnabled(false);
} else {
positive.setEnabled(true);//监听输入字符串如果大于零则button可以点击
}
}
public void afterTextChanged(Editable s) {//判断是否在文本更改之后
// TODO Auto-generated method stub
}
});
}
@Override
public void onBackPressed() {//点击后退键时的操作
switch (mState) {//判断目前所处的状态
case SUB_FOLDER://前两个状态返回到初始界面最后一个状态返回到桌面
mCurrentFolderId = Notes.ID_ROOT_FOLDER;//如果是在文件夹中的状态
mState = ListEditState.NOTE_LIST;//将当前文件夹id修改为根文件夹
startAsyncNotesListQuery();//将当前状态改为一般状态
mTitleBar.setVisibility(View.GONE);//隐藏TitleBar设置为不可见
break;
case CALL_RECORD_FOLDER://响应已记录文件夹的操作
mCurrentFolderId = Notes.ID_ROOT_FOLDER;//将当前文件夹id修改为根文件夹
mState = ListEditState.NOTE_LIST;//便签列表的返回
mAddNewNote.setVisibility(View.VISIBLE);//设置button“新增便签”可见
mTitleBar.setVisibility(View.GONE);//隐藏TitleBar设置为不可见
startAsyncNotesListQuery();
break;
case NOTE_LIST://从主界面退出
super.onBackPressed();//调用原来的onBackPressed方法
break;
default://其他情况直接break
break;
}
}
private void updateWidget(int appWidgetId, int appWidgetType) {//更新桌面widget小工具设置内容、格式
Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);//初始化部件大小管理
if (appWidgetType == Notes.TYPE_WIDGET_2X) {//下面是判断不同类型widget的操作并建立不同的类型
intent.setClass(this, NoteWidgetProvider_2x.class);//将便签插件提供器的类型设置成内容的类型
} else if (appWidgetType == Notes.TYPE_WIDGET_4X) {//判断不同类型widget的操作并建立不同的类型
intent.setClass(this, NoteWidgetProvider_4x.class);
} else {
Log.e(TAG, "Unspported widget type");//否则显示“不支持的插件类型
return;//返回错误日志信息
}
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {//putExtra中两个参数为键对值第一个参数为键名
appWidgetId
});
sendBroadcast(intent);//设置成功的结果
setResult(RESULT_OK, intent);//返回给上一个活动数据
}
private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {//对文件夹进行操作的菜单
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {//创建目录的视图
if (mFocusNoteDataItem != null) {//当笔记数据项不为空时,设置菜单
menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());//设置菜单的题目是当前文件夹名字
menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);//在菜单中新增项目“查看文件夹”
menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);//在菜单中新增项目“删除文件夹”
menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name);//在菜单中新增项目“修改文件夹名称”
}
}
};
@Override
public void onContextMenuClosed(Menu menu) {//关闭菜单
if (mNotesListView != null) {
mNotesListView.setOnCreateContextMenuListener(null);//不设置监听事件
}
super.onContextMenuClosed(menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {//对菜单项进行选择对应的相应
if (mFocusNoteDataItem == null) {//若笔记数据项为空
Log.e(TAG, "The long click data item is null");//设置标签“长按数据项为空
return false;
}
switch (item.getItemId()) {//通过获取项目ID进行switch
case MENU_FOLDER_VIEW://打开文件夹
openFolder(mFocusNoteDataItem);
break;
case MENU_FOLDER_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_folder));//设置警告信息文本“确认删除文件夹及所包含的便签”
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {//设置取消按键
public void onClick(DialogInterface dialog, int which) {
deleteFolder(mFocusNoteDataItem.getId());//点击删除文件夹
}
});
builder.setNegativeButton(android.R.string.cancel, null);//设置button“取消”
builder.show();
break;
case MENU_FOLDER_CHANGE_NAME://修改目录文件夹的名称
showCreateOrModifyFolderDialog(false);//不显示创建or修改文件夹的对话框
break;
default:
break;
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {//创建菜单这个方法在每一次调用菜单的时候都会执行
menu.clear();//把原先的菜单删除
if (mState == ListEditState.NOTE_LIST) {//当状态为当前笔记列表状态时,设置同步或取消同步
getMenuInflater().inflate(R.menu.note_list, menu);//加载目录的布局
// set sync or sync_cancel//设置同步标题
menu.findItem(R.id.menu_sync).setTitle(
GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);//为同步菜单项设置标题,如果正在同步中则显示“取消同步”,否则显示“同步”
} else if (mState == ListEditState.SUB_FOLDER) {//当状态为当前子文件夹状态时,扩充子文件夹
getMenuInflater().inflate(R.menu.sub_folder, menu);//采用布局文件R.menu.sub_folder来构建菜单项
} else if (mState == ListEditState.CALL_RECORD_FOLDER) {//当状态为当调用记录文件夹时,扩充记录文件夹的菜单
getMenuInflater().inflate(R.menu.call_record_folder, menu);//采用布局文件R.menu.call_record_folder来构建菜单项
} else {//否则设置标签为“错误状态”+当前状态
Log.e(TAG, "Wrong state:" + mState);//报错日志信息
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {//实现菜单项目的操作通过case语句对各个菜单项目分别设置事件
switch (item.getItemId()) {//选择不同的项目名称
case R.id.menu_new_folder: {//创建新目录的选项
showCreateOrModifyFolderDialog(true);
break;
}
case R.id.menu_export_text: {//目录中输出文本内容的选项
exportNoteToText();
break;
}
case R.id.menu_sync: {//同步菜单
if (isSyncMode()) {//同步
if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {//如果项目title与菜单同步相同则进行同步
GTaskSyncService.startSync(this);//利用到GTaskSyncService的类
} else {//否则取消同步
GTaskSyncService.cancelSync(this);
}
} else {//如果不是同步模式,则开始设置动作
startPreferenceActivity();//.否则进行Preference活动
}
break;
}
case R.id.menu_setting: {//设置菜单
startPreferenceActivity();
break;
}
case R.id.menu_new_note: {//新建便签
createNewNote();
break;
}
case R.id.menu_search://搜索
onSearchRequested();//查询
break;
default:
break;
}
return true;
}
@Override
public boolean onSearchRequested() {//根据关键字搜索便签(还未实现)
startSearch(null, false, null /* appData */, false);
return true;
}
private void exportNoteToText() {//将便签导出
final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);//备份笔记信息
new AsyncTask<Void, Void, Integer>() {//异步任务
@Override
protected Integer doInBackground(Void... unused) {
return backup.exportToText();
}//未被占用的话后台进行
@Override
protected void onPostExecute(Integer result) {//设置备份的结果响应
if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {//如果SD卡无响应则提示用户 “导出失败SD卡繁忙”
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_unmounted));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
} else if (result == BackupUtils.STATE_SUCCESS) {//如果导出成功,则显示相应对话框
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);//如果导出成功,则显示成功
//并且会显示“Export text file 《便签名称》 to SD 《目录名称》 directory”
builder.setTitle(NotesListActivity.this//设置标题
.getString(R.string.success_sdcard_export));
builder.setMessage(NotesListActivity.this.getString(
R.string.format_exported_file_location, backup
.getExportedTextFileName(), backup.getExportedTextFileDir()));
builder.setPositiveButton(android.R.string.ok, null);//设置响应按钮
builder.show();
} else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
builder.setTitle(NotesListActivity.this
.getString(R.string.failed_sdcard_export));
builder.setMessage(NotesListActivity.this
.getString(R.string.error_sdcard_export));
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
}
}
}.execute();
}
private boolean isSyncMode() {//判断是否处于同步模式
return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;//转到PreferenceActivity
}
private void startPreferenceActivity() {//跳转到设置界面
Activity from = getParent() != null ? getParent() : this;//设置便签函数
Intent intent = new Intent(from, NotesPreferenceActivity.class);
from.startActivityIfNeeded(intent, -1);//请求码为-1表示此活动结束后不会通知原活动
}
private class OnListItemClickListener implements OnItemClickListener {//当短按标签列表项时的响应
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//项目被点击的响应
if (view instanceof NotesListItem) {//判断view是否是NotesListItem的一个实例如果是就获取他的项目信息装入item中
NoteItemData item = ((NotesListItem) view).getItemData();
if (mNotesListAdapter.isInChoiceMode()) {//如果列表适配器被选择并且项是便签类型的,则修改位置和状态信息
if (item.getType() == Notes.TYPE_NOTE) {//如果点到的item是便签
position = position - mNotesListView.getHeaderViewsCount();//减去头部视图的元素项,得到列表的元素索引值
mModeCallBack.onItemCheckedStateChanged(null, position, id,//改变对应索引的Item是否被选中的状态
!mNotesListAdapter.isSelectedItem(position));
}
return;
}
switch (mState) {//区别情况进行处理
case NOTE_LIST://便签列表
if (item.getType() == Notes.TYPE_FOLDER
|| item.getType() == Notes.TYPE_SYSTEM) {
openFolder(item);//查询目标文件夹
} else if (item.getType() == Notes.TYPE_NOTE) {
openNode(item);
} else {
Log.e(TAG, "Wrong note type in NOTE_LIST");
}
break;
case SUB_FOLDER:
case CALL_RECORD_FOLDER:
if (item.getType() == Notes.TYPE_NOTE) {
openNode(item);
} else {
Log.e(TAG, "Wrong note type in SUB_FOLDER");
}
break;
default:
break;
}
}
}
}
private void startQueryDestinationFolders() {//查询目标文件
String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";//按下移动便签后,开始查找所有的文件夹
selection = (mState == ListEditState.NOTE_LIST) ? selection:
"(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";
mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
null,
Notes.CONTENT_NOTE_URI,//长按某一项时进行的操作如果长按的是便签则通过ActionMode菜单实现
FoldersListAdapter.PROJECTION,
selection,//长按某一项时进行的操作 如果长按的是便签则通过ActionMode菜单实现如果长按的是文件夹则通过ContextMenu菜单实现
new String[] {//新建字符列表
String.valueOf(Notes.TYPE_FOLDER),
String.valueOf(Notes.ID_TRASH_FOLER),
String.valueOf(mCurrentFolderId)
},
NoteColumns.MODIFIED_DATE + " DESC");
}
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {//长按的响应
if (view instanceof NotesListItem) {//判断view是否是NotesListItem的一个实例如果是就获取他的项目信息装入item中
mFocusNoteDataItem = ((NotesListItem) view).getItemData();//聚焦的Item对象
if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) {//长按的对象是便签时的处理通过ActionMode实现
if (mNotesListView.startActionMode(mModeCallBack) != null) {
mModeCallBack.onItemCheckedStateChanged(null, position, id, true);//开始对单个便签进行操作
mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
} else {//长按的对象是文件夹时的处理通过ContextMenu实现
Log.e(TAG, "startActionMode fails");
}
} else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {//如果长按的的项目是文件夹类型则执行ContextMenu菜单的实现
mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
}
}
return false;
}
}

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

@ -0,0 +1,122 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.ui;//引入需要用到的包
import android.content.Context;//第19到30行导入各种类
import android.text.format.DateUtils;
import android.view.View;//导入类
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;//标签列表项目选项
import android.widget.TextView;
import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser.NoteItemBgResources;
public class NotesListItem extends LinearLayout {//构建便签列表的各个项目的详细具体信息
private ImageView mAlert;//闹钟图片
private TextView mTitle;//标题
private TextView mTime;//时间
private TextView mCallName;//名字
private NoteItemData mItemData;//标签数据
private CheckBox mCheckBox;//勾选框
public NotesListItem(Context context) {//初始化
super(context);//super()它的主要作用是调整调用父类构造函数的顺序
inflate(context, R.layout.note_item, this);//Inflate()作用就是将xml定义的一个布局找出来
mAlert = (ImageView) findViewById(R.id.iv_alert_icon);//findViewById用于从contentView中查找指定ID的View转换出来的形式根据需要而定
mTitle = (TextView) findViewById(R.id.tv_title);// 获取题目(文件夹或便签项上的文本)
mTime = (TextView) findViewById(R.id.tv_time);//获取创建或修改时间
mCallName = (TextView) findViewById(R.id.tv_name);//获取联系人姓名
mCheckBox = (CheckBox) findViewById(android.R.id.checkbox);//获取复选框
}
public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) {//根据data的属性对各个控件的属性的控制主要是可见性Visibility内容setText格式setTextAppearance
if (choiceMode && data.getType() == Notes.TYPE_NOTE) {//如果当前处于选择模式下且数据类型为便签
mCheckBox.setVisibility(View.VISIBLE);//设置View可见
mCheckBox.setChecked(checked);//设置勾选
} else {
mCheckBox.setVisibility(View.GONE);//设置复选框不可见
}
mItemData = data;//把数据传给标签
if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {//设置控件属性通过判断保存到文件夹的ID、当前ID以及父ID之间关系决定
mCallName.setVisibility(View.GONE);//设置联系人名字不可见
mAlert.setVisibility(View.VISIBLE);//设置闹钟图标可见
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);//设置外观风格
mTitle.setText(context.getString(R.string.call_record_folder_name)
+ context.getString(R.string.format_folder_files_count, data.getNotesCount()));//设置title的内容文件夹名字+数量)
mAlert.setImageResource(R.drawable.call_record);//设置图片来源
} else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) {//设置闹钟
mCallName.setVisibility(View.VISIBLE);//设置联系人姓名可见
mCallName.setText(data.getCallName());//设置联系人姓名的文本内容
mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem);//设置title文本风格
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));//设置title的文本内容为便签内容的前面片段
if (data.hasAlert()) {//如果当前便签存在提醒时间
mAlert.setImageResource(R.drawable.clock);//图片来源的设置
mAlert.setVisibility(View.VISIBLE);//将提醒图标设置为可见
} else {
mAlert.setVisibility(View.GONE);//否则将提醒图标设置为不可见
}
} else {
mCallName.setVisibility(View.GONE);//设置联系人姓名不可见
mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem);//设置title的文本格式
if (data.getType() == Notes.TYPE_FOLDER) {//设置Type格式
mTitle.setText(data.getSnippet()
+ context.getString(R.string.format_folder_files_count,
data.getNotesCount()));//设置便签标题内容为便签的前面部分的内容+文件数+便签数
mAlert.setVisibility(View.GONE);//设置图标不可见
} else {
mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet()));
if (data.hasAlert()) {
mAlert.setImageResource(R.drawable.clock);
mAlert.setVisibility(View.VISIBLE);
} else {
mAlert.setVisibility(View.GONE);//否则设置提醒图标不可见
}
}
}
mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate()));//将时间设置为编辑便签的时间
setBackground(data);//设置背景
}
private void setBackground(NoteItemData data) {//通过data设置背景
int id = data.getBgColorId();//获取id用此id用来获取背景颜色
if (data.getType() == Notes.TYPE_NOTE) {//若是note型文件则4种情况对于4种不同情况的背景来源
if (data.isSingle() || data.isOneFollowingFolder()) {//单个数据或只有一个子文件夹
setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id));
} else if (data.isLast()) {//最后一个数据
setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id));
} else if (data.isFirst() || data.isMultiFollowingFolder()) {//设置背景来源为id的最后一个数据
setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id));//.若不是Note类型则使用文件夹背景来源
} else {
setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id));//设置背景来源为id的普通数据
}
} else {//如果不是便签类型的数据
setBackgroundResource(NoteItemBgResources.getFolderBgRes());//设置背景来源为文件夹
}
}
public NoteItemData getItemData() {
return mItemData;
}//返回当前便签的数据信息
}

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

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

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

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