精读了remote和tool中java源代码

pull/4/head^2
chenjr 2 years ago
parent aeca8eaadb
commit ca74da689a

@ -29,7 +29,7 @@ import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { public class GTaskASyncTask extends AsyncTask<Void, String, Integer> { //异步操作类实现Gtask异步操作过程
private static int GTASK_SYNC_NOTIFICATION_ID = 5234235; private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;
@ -57,7 +57,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
mTaskManager.cancelSync(); mTaskManager.cancelSync();
} }
public void publishProgess(String message) { public void publishProgess(String message) {//发布进度单位系统将会调用onProgressUpdate()方法更新这些值
publishProgress(new String[] { publishProgress(new String[] {
message message
}); });
@ -82,13 +82,13 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); // mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
// } // }
private void showNotification(int tickerId, String content) { private void showNotification(int tickerId, String content) {//向用户提示当前同步的状态,是一个交互的方法
PendingIntent pendingIntent; PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) { if (tickerId != R.string.ticker_success) {//如果同步不成功那么从系统取得一个用于启动一个NotesPreferenceActivity的PendingIntent对象
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), 0); NotesPreferenceActivity.class), 0);
} else { } else {//如果同步成功那么从系统取得一个用于启动一个NotesListActivity的PendingIntent对象
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), 0); NotesListActivity.class), 0);
} }
@ -102,17 +102,17 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
.setWhen(System.currentTimeMillis()) .setWhen(System.currentTimeMillis())
.setOngoing(true); .setOngoing(true);
Notification notification=builder.getNotification(); Notification notification=builder.getNotification();
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification); mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify方法来执行一个notification的消息
} }
@Override @Override
protected Integer doInBackground(Void... unused) { protected Integer doInBackground(Void... unused) {//完成任务的主要工作
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext))); .getSyncAccountName(mContext)));
return mTaskManager.sync(mContext, this); return mTaskManager.sync(mContext, this);
} }
@Override @Override
protected void onProgressUpdate(String... progress) { protected void onProgressUpdate(String... progress) {//显示任务执行进度,增加进度条的功能
showNotification(R.string.ticker_syncing, progress[0]); showNotification(R.string.ticker_syncing, progress[0]);
if (mContext instanceof GTaskSyncService) { if (mContext instanceof GTaskSyncService) {
((GTaskSyncService) mContext).sendBroadcast(progress[0]); ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
@ -120,7 +120,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
} }
@Override @Override
protected void onPostExecute(Integer result) { protected void onPostExecute(Integer result) {//得到结果处理操作ui管理操作ui的方式
if (result == GTaskManager.STATE_SUCCESS) { if (result == GTaskManager.STATE_SUCCESS) {
showNotification(R.string.ticker_success, mContext.getString( showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount())); R.string.success_sync_account, mTaskManager.getSyncAccount()));
@ -138,7 +138,7 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
public void run() { public void run() {
mOnCompleteListener.onComplete(); mOnCompleteListener.onComplete();
} }//完成后的操作使用onComplete()将所有值都重新初始化,相当于完成一次操作
}).start(); }).start();
} }
} }

@ -60,7 +60,7 @@ import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater; import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
//主要功能实现GTASK的登录操作进行GTASK任务的创建创建任务列表从网络上获取任务和任务列表的内容
public class GTaskClient { public class GTaskClient {
private static final String TAG = GTaskClient.class.getSimpleName(); private static final String TAG = GTaskClient.class.getSimpleName();
@ -102,49 +102,51 @@ public class GTaskClient {
mUpdateArray = null; mUpdateArray = null;
} }
public static synchronized GTaskClient getInstance() { public static synchronized GTaskClient getInstance() {//用来获取的实例化对象
if (mInstance == null) { if (mInstance == null) {
mInstance = new GTaskClient(); mInstance = new GTaskClient();
} }
return mInstance; return mInstance;
} }
public boolean login(Activity activity) { public boolean login(Activity activity) {//实现登录操作的函数传入参数activity
// we suppose that the cookie would expire after 5 minutes // we suppose that the cookie would expire after 5 minutes
// then we need to re-login // then we need to re-login
final long interval = 1000 * 60 * 5; final long interval = 1000 * 60 * 5;//判断最后一次登录是否超过五分钟
if (mLastLoginTime + interval < System.currentTimeMillis()) { if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false; mLoggedin = false;
} }
// need to re-login after account switch // need to re-login after account switch
// 重新登录
if (mLoggedin if (mLoggedin
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity && !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) { .getSyncAccountName(activity))) {
mLoggedin = false; mLoggedin = false;
} }
//如果没超时就不用登录
if (mLoggedin) { if (mLoggedin) {
Log.d(TAG, "already logged in"); Log.d(TAG, "already logged in");
return true; return true;
} }
mLastLoginTime = System.currentTimeMillis(); mLastLoginTime = System.currentTimeMillis();//更新登录时间即为系统时间
String authToken = loginGoogleAccount(activity, false); String authToken = loginGoogleAccount(activity, false);//判断是否登录google账户
if (authToken == null) { if (authToken == null) {
Log.e(TAG, "login google account failed"); Log.e(TAG, "login google account failed");
return false; return false;
} }
// login with custom domain if necessary // login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase() //尝试使用用户自己的域名登录
.endsWith("googlemail.com"))) { if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()//将用户名改为统一格式后判断是否为googl账户
.endsWith("googlemail.com"))) {//
StringBuilder url = new StringBuilder(GTASK_URL).append("a/"); StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
int index = mAccount.name.indexOf('@') + 1; int index = mAccount.name.indexOf('@') + 1;
String suffix = mAccount.name.substring(index); String suffix = mAccount.name.substring(index);
url.append(suffix + "/"); url.append(suffix + "/");
mGetUrl = url.toString() + "ig"; mGetUrl = url.toString() + "ig";//设置用户对应的geturl
mPostUrl = url.toString() + "r/ig"; mPostUrl = url.toString() + "r/ig";//设置用户对应的posturl
if (tryToLoginGtask(activity, authToken)) { if (tryToLoginGtask(activity, authToken)) {
mLoggedin = true; mLoggedin = true;
@ -152,6 +154,7 @@ public class GTaskClient {
} }
// try to login with google official url // try to login with google official url
//如果用户无法登录使用官方的url进行登录
if (!mLoggedin) { if (!mLoggedin) {
mGetUrl = GTASK_GET_URL; mGetUrl = GTASK_GET_URL;
mPostUrl = GTASK_POST_URL; mPostUrl = GTASK_POST_URL;
@ -163,11 +166,14 @@ public class GTaskClient {
mLoggedin = true; mLoggedin = true;
return true; return true;
} }
//具体实现登录账户方法
private String loginGoogleAccount(Activity activity, boolean invalidateToken) { //使用令牌
//使用accountmanager进行管理注册账号
//返回账号的令牌
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {//使用令牌登录google账号
String authToken; String authToken;
AccountManager accountManager = AccountManager.get(activity); AccountManager accountManager = AccountManager.get(activity);//提供给用户注册的接口
Account[] accounts = accountManager.getAccountsByType("com.google"); Account[] accounts = accountManager.getAccountsByType("com.google");//获取全部以com.google结尾的account
if (accounts.length == 0) { if (accounts.length == 0) {
Log.e(TAG, "there is no available google account"); Log.e(TAG, "there is no available google account");
@ -176,6 +182,7 @@ public class GTaskClient {
String accountName = NotesPreferenceActivity.getSyncAccountName(activity); String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
Account account = null; Account account = null;
//查询是否已经注册过,查找注册库信息
for (Account a : accounts) { for (Account a : accounts) {
if (a.name.equals(accountName)) { if (a.name.equals(accountName)) {
account = a; account = a;
@ -190,6 +197,7 @@ public class GTaskClient {
} }
// get the token now // get the token now
//获取选中账号的令牌
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null); "goanna_mobile", null, activity, null, null);
try { try {
@ -204,9 +212,9 @@ public class GTaskClient {
authToken = null; authToken = null;
} }
return authToken; return authToken;//令牌
} }
//尝试登陆Gtask这只是一个预先判断令牌是否是有效以及是否能登上GTask的方法,而不是具体实现登陆的方法
private boolean tryToLoginGtask(Activity activity, String authToken) { private boolean tryToLoginGtask(Activity activity, String authToken) {
if (!loginGtask(authToken)) { if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the // maybe the auth token is out of date, now let's invalidate the
@ -224,26 +232,27 @@ public class GTaskClient {
} }
return true; return true;
} }
//实现登录GTask的具体操作
private boolean loginGtask(String authToken) { private boolean loginGtask(String authToken) {
int timeoutConnection = 10000; int timeoutConnection = 10000;
int timeoutSocket = 15000; int timeoutSocket = 15000;//socket是一种通信连接实现数据的交换的端口
HttpParams httpParameters = new BasicHttpParams(); HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);//设置连接超时时间
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);//设置设置端口超时时间
mHttpClient = new DefaultHttpClient(httpParameters); mHttpClient = new DefaultHttpClient(httpParameters);
BasicCookieStore localBasicCookieStore = new BasicCookieStore(); BasicCookieStore localBasicCookieStore = new BasicCookieStore();//设置本地cookie
mHttpClient.setCookieStore(localBasicCookieStore); mHttpClient.setCookieStore(localBasicCookieStore);
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false); HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask // login gtask
try { try {
String loginUrl = mGetUrl + "?auth=" + authToken; String loginUrl = mGetUrl + "?auth=" + authToken;//设置登录的url
HttpGet httpGet = new HttpGet(loginUrl); HttpGet httpGet = new HttpGet(loginUrl);//通过登录的uri实例化网页上资源的查找
HttpResponse response = null; HttpResponse response = null;
response = mHttpClient.execute(httpGet); response = mHttpClient.execute(httpGet);
// get the cookie now // get the cookie now
//获取CookieStore里存放的cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies(); List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
boolean hasAuthCookie = false; boolean hasAuthCookie = false;
for (Cookie cookie : cookies) { for (Cookie cookie : cookies) {
@ -256,6 +265,7 @@ public class GTaskClient {
} }
// get the client version // get the client version
//获取client的内容具体操作是在返回的Content中截取从_setup(开始到)}</script>中间的字符串内容也就是gtask_url的内容
String resString = getResponseContent(response.getEntity()); String resString = getResponseContent(response.getEntity());
String jsBegin = "_setup("; String jsBegin = "_setup(";
String jsEnd = ")}</script>"; String jsEnd = ")}</script>";
@ -290,7 +300,7 @@ public class GTaskClient {
httpPost.setHeader("AT", "1"); httpPost.setHeader("AT", "1");
return httpPost; return httpPost;
} }
//通过URL获取响应后返回的数据也就是网络上的数据和资源
private String getResponseContent(HttpEntity entity) throws IOException { private String getResponseContent(HttpEntity entity) throws IOException {
String contentEncoding = null; String contentEncoding = null;
if (entity.getContentEncoding() != null) { if (entity.getContentEncoding() != null) {
@ -299,7 +309,7 @@ public class GTaskClient {
} }
InputStream input = entity.getContent(); InputStream input = entity.getContent();
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) { if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {//压缩数据库
input = new GZIPInputStream(entity.getContent()); input = new GZIPInputStream(entity.getContent());
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) { } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
Inflater inflater = new Inflater(true); Inflater inflater = new Inflater(true);
@ -322,7 +332,10 @@ public class GTaskClient {
input.close(); input.close();
} }
} }
//通过JSON发送请求请求的具体内容在json的实例化对象js中然后传入
// 利用UrlEncodedFormEntity entity和httpPost.setEntity(entity)方法把js中的内容放置到httpPost中
//执行请求后使用getResponseContent方法得到返回的数据和资源
// 将资源再次放入json后返回
private JSONObject postRequest(JSONObject js) throws NetworkFailureException { private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -359,7 +372,7 @@ public class GTaskClient {
throw new ActionFailureException("error occurs when posting request"); throw new ActionFailureException("error occurs when posting request");
} }
} }
//创建单个任务,传入的参数是.gtask.data.task包里的task类对象利用json获取task里的内容并且创建相应的jsPost
public void createTask(Task task) throws NetworkFailureException { public void createTask(Task task) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -385,7 +398,7 @@ public class GTaskClient {
throw new ActionFailureException("create task: handing jsonobject failed"); throw new ActionFailureException("create task: handing jsonobject failed");
} }
} }
//创建一个任务列表与createTask几乎一样区别就是最后设置的是tasklist的gid
public void createTaskList(TaskList tasklist) throws NetworkFailureException { public void createTaskList(TaskList tasklist) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -411,7 +424,7 @@ public class GTaskClient {
throw new ActionFailureException("create tasklist: handing jsonobject failed"); throw new ActionFailureException("create tasklist: handing jsonobject failed");
} }
} }
//同步更新操作使用jsonobject进行数据存储
public void commitUpdate() throws NetworkFailureException { public void commitUpdate() throws NetworkFailureException {
if (mUpdateArray != null) { if (mUpdateArray != null) {
try { try {
@ -432,7 +445,7 @@ public class GTaskClient {
} }
} }
} }
//添加更新事项
public void addUpdateNode(Node node) throws NetworkFailureException { public void addUpdateNode(Node node) throws NetworkFailureException {
if (node != null) { if (node != null) {
// too many update items may result in an error // too many update items may result in an error
@ -446,7 +459,12 @@ public class GTaskClient {
mUpdateArray.put(node.getUpdateAction(getActionId())); 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) public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException { throws NetworkFailureException {
commitUpdate(); commitUpdate();
@ -485,7 +503,11 @@ public class GTaskClient {
throw new ActionFailureException("move task: handing jsonobject failed"); throw new ActionFailureException("move task: handing jsonobject failed");
} }
} }
/*
*
* JSON
* 使postRequest
*/
public void deleteNode(Node node) throws NetworkFailureException { public void deleteNode(Node node) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -508,7 +530,11 @@ public class GTaskClient {
throw new ActionFailureException("delete node: handing jsonobject failed"); throw new ActionFailureException("delete node: handing jsonobject failed");
} }
} }
/*
*
* GetURI使getResponseContent
* "_setup(")}</script>GTASK_JSON_LISTS
*/
public JSONArray getTaskLists() throws NetworkFailureException { public JSONArray getTaskLists() throws NetworkFailureException {
if (!mLoggedin) { if (!mLoggedin) {
Log.e(TAG, "please login first"); Log.e(TAG, "please login first");
@ -546,7 +572,7 @@ public class GTaskClient {
throw new ActionFailureException("get task lists: handing jasonobject failed"); throw new ActionFailureException("get task lists: handing jasonobject failed");
} }
} }
//通过传入的TASKList的gid,从网络上获取相应属于这个任务列表的任务
public JSONArray getTaskList(String listGid) throws NetworkFailureException { public JSONArray getTaskList(String listGid) throws NetworkFailureException {
commitUpdate(); commitUpdate();
try { try {
@ -579,6 +605,7 @@ public class GTaskClient {
return mAccount; return mAccount;
} }
//重置更新的内容
public void resetUpdateArray() { public void resetUpdateArray() {
mUpdateArray = null; mUpdateArray = null;
} }

@ -88,15 +88,15 @@ public class GTaskManager {
private HashMap<Long, String> mNidToGid; private HashMap<Long, String> mNidToGid;
private GTaskManager() { private GTaskManager() {
mSyncing = false; mSyncing = false; //正在同步,flase代表未执行
mCancelled = false; mCancelled = false; //全局标识flase代表可以执行
mGTaskListHashMap = new HashMap<String, TaskList>(); mGTaskListHashMap = new HashMap<String, TaskList>(); //<>代表Java的泛型,就是创建一个用类型作为参数的类。
mGTaskHashMap = new HashMap<String, Node>(); mGTaskHashMap = new HashMap<String, Node>();
mMetaHashMap = new HashMap<String, MetaData>(); mMetaHashMap = new HashMap<String, MetaData>();
mMetaList = null; mMetaList = null;
mLocalDeleteIdMap = new HashSet<Long>(); mLocalDeleteIdMap = new HashSet<Long>();
mGidToNid = new HashMap<String, Long>(); mGidToNid = new HashMap<String, Long>(); //GoogleID to NodeID??
mNidToGid = new HashMap<Long, String>(); mNidToGid = new HashMap<Long, String>(); //NodeID to GoogleID???通过hashmap散列表建立映射
} }
public static synchronized GTaskManager getInstance() { public static synchronized GTaskManager getInstance() {
@ -105,12 +105,12 @@ public class GTaskManager {
} }
return mInstance; return mInstance;
} }
//指明该函数可能运行在多线程的环境下
public synchronized void setActivityContext(Activity activity) { public synchronized void setActivityContext(Activity activity) {
// used for getting authtoken // used for getting authtoken
mActivity = activity; mActivity = activity;
} }
//实现了本地同步操作和远端同步操作
public int sync(Context context, GTaskASyncTask asyncTask) { public int sync(Context context, GTaskASyncTask asyncTask) {
if (mSyncing) { if (mSyncing) {
Log.d(TAG, "Sync is in progress"); Log.d(TAG, "Sync is in progress");
@ -167,7 +167,7 @@ public class GTaskManager {
return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS; return mCancelled ? STATE_SYNC_CANCELLED : STATE_SUCCESS;
} }
//初始化GtaskList获取Google上的JSONtasklist转为本地TaskList
private void initGTaskList() throws NetworkFailureException { private void initGTaskList() throws NetworkFailureException {
if (mCancelled) if (mCancelled)
return; return;
@ -246,7 +246,7 @@ public class GTaskManager {
throw new ActionFailureException("initGTaskList: handing JSONObject failed"); throw new ActionFailureException("initGTaskList: handing JSONObject failed");
} }
} }
//本地内容同步操作
private void syncContent() throws NetworkFailureException { private void syncContent() throws NetworkFailureException {
int syncType; int syncType;
Cursor c = null; Cursor c = null;
@ -475,7 +475,7 @@ public class GTaskManager {
if (!mCancelled) if (!mCancelled)
GTaskClient.getInstance().commitUpdate(); GTaskClient.getInstance().commitUpdate();
} }
//功能syncType分类addLocalNodeaddRemoteNodedeleteNodeupdateLocalNodeupdateRemoteNode
private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException { private void doContentSync(int syncType, Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -521,7 +521,7 @@ public class GTaskManager {
throw new ActionFailureException("unkown sync action type"); throw new ActionFailureException("unkown sync action type");
} }
} }
//本地增加Node
private void addLocalNode(Node node) throws NetworkFailureException { private void addLocalNode(Node node) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -595,7 +595,7 @@ public class GTaskManager {
// update meta // update meta
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
//功能update本地node
private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException { private void updateLocalNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -618,7 +618,7 @@ public class GTaskManager {
// update meta info // update meta info
updateRemoteMeta(node.getGid(), sqlNote); updateRemoteMeta(node.getGid(), sqlNote);
} }
//功能远程增加Node
private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void addRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -691,7 +691,7 @@ public class GTaskManager {
mGidToNid.put(n.getGid(), sqlNote.getId()); mGidToNid.put(n.getGid(), sqlNote.getId());
mNidToGid.put(sqlNote.getId(), n.getGid()); mNidToGid.put(sqlNote.getId(), n.getGid());
} }
//功能更新远端的Node包含meta更新(updateRemoteMeta)
private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException { private void updateRemoteNode(Node node, Cursor c) throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -729,7 +729,7 @@ public class GTaskManager {
sqlNote.resetLocalModified(); sqlNote.resetLocalModified();
sqlNote.commit(true); sqlNote.commit(true);
} }
//功能升级远程meta。 meta---元数据----计算机文件系统管理数据---管理数据的数据
private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException { private void updateRemoteMeta(String gid, SqlNote sqlNote) throws NetworkFailureException {
if (sqlNote != null && sqlNote.isNoteType()) { if (sqlNote != null && sqlNote.isNoteType()) {
MetaData metaData = mMetaHashMap.get(gid); MetaData metaData = mMetaHashMap.get(gid);
@ -745,7 +745,7 @@ public class GTaskManager {
} }
} }
} }
//功能刷新本地给sync的ID对应上最后更改过的对象
private void refreshLocalSyncId() throws NetworkFailureException { private void refreshLocalSyncId() throws NetworkFailureException {
if (mCancelled) { if (mCancelled) {
return; return;
@ -789,7 +789,7 @@ public class GTaskManager {
} }
} }
} }
//功能:获取同步账号,mAccount.name
public String getSyncAccount() { public String getSyncAccount() {
return GTaskClient.getInstance().getSyncAccount().name; return GTaskClient.getInstance().getSyncAccount().name;
} }

@ -22,7 +22,7 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.os.IBinder; import android.os.IBinder;
//Service是在一段不定的时间运行在后台不和用户交互的应用组件
public class GTaskSyncService extends Service { public class GTaskSyncService extends Service {
public final static String ACTION_STRING_NAME = "sync_action_type"; public final static String ACTION_STRING_NAME = "sync_action_type";
@ -41,7 +41,7 @@ public class GTaskSyncService extends Service {
private static GTaskASyncTask mSyncTask = null; private static GTaskASyncTask mSyncTask = null;
private static String mSyncProgress = ""; private static String mSyncProgress = "";
//启动一个同步工作
private void startSync() { private void startSync() {
if (mSyncTask == null) { if (mSyncTask == null) {
mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() { mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
@ -55,7 +55,7 @@ public class GTaskSyncService extends Service {
mSyncTask.execute(); mSyncTask.execute();
} }
} }
//取消同步
private void cancelSync() { private void cancelSync() {
if (mSyncTask != null) { if (mSyncTask != null) {
mSyncTask.cancelSync(); mSyncTask.cancelSync();
@ -66,7 +66,7 @@ public class GTaskSyncService extends Service {
public void onCreate() { public void onCreate() {
mSyncTask = null; mSyncTask = null;
} }
//service生命周期的组成部分相当于重启service比如在被暂停之后而不是创建一个新的service
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Bundle bundle = intent.getExtras(); Bundle bundle = intent.getExtras();
@ -85,7 +85,7 @@ public class GTaskSyncService extends Service {
} }
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
} }
//在没有内存的情况下如果存在service则结束掉这的service
@Override @Override
public void onLowMemory() { public void onLowMemory() {
if (mSyncTask != null) { if (mSyncTask != null) {
@ -96,7 +96,7 @@ public class GTaskSyncService extends Service {
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
return null; return null;
} }
//发送同步的相关通知
public void sendBroadcast(String msg) { public void sendBroadcast(String msg) {
mSyncProgress = msg; mSyncProgress = msg;
Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME); Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
@ -117,7 +117,7 @@ public class GTaskSyncService extends Service {
intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC); intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
context.startService(intent); context.startService(intent);
} }
//判读是否在进行同步
public static boolean isSyncing() { public static boolean isSyncing() {
return mSyncTask != null; return mSyncTask != null;
} }

@ -42,6 +42,9 @@ public class BackupUtils {
private static BackupUtils sInstance; private static BackupUtils sInstance;
public static synchronized BackupUtils getInstance(Context context) { public static synchronized BackupUtils getInstance(Context context) {
//ynchronized 关键字,代表这个方法加锁,相当于不管哪一个线程例如线程A
//运行到这个方法时,都要检查有没有其它线程B或者C、 D等正在用这个方法(或者该类的其他同步方法)有的话要等正在使用synchronized方法的线程B或者C 、D运行完这个方法后再运行此线程A,没有的话,锁定调用者,然后直接运行。
//它包括两种用法synchronized 方法和 synchronized 块。
if (sInstance == null) { if (sInstance == null) {
sInstance = new BackupUtils(context); sInstance = new BackupUtils(context);
} }
@ -139,6 +142,7 @@ public class BackupUtils {
/** /**
* Export the folder identified by folder id to text * Export the folder identified by folder id to text
*/ */
//通过查询parent id是文件夹id的note来选出制定ID文件夹下的Note
private void exportFolderToText(String folderId, PrintStream ps) { private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder // Query notes belong to this folder
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI, Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
@ -218,6 +222,7 @@ public class BackupUtils {
/** /**
* Note will be exported as text which is user readable * Note will be exported as text which is user readable
*/ */
//注释将导出为用户可读的文本
public int exportToText() { public int exportToText() {
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted"); Log.d(TAG, "Media was not mounted");
@ -229,7 +234,7 @@ public class BackupUtils {
Log.e(TAG, "get print stream error"); Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR;
} }
// First export folder and its notes // First export folder and its notes导出文件夹
Cursor folderCursor = mContext.getContentResolver().query( Cursor folderCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
@ -258,6 +263,7 @@ public class BackupUtils {
} }
// Export notes in root's folder // Export notes in root's folder
// 将根目录里的便签导出(由于不属于任何文件夹,因此无法通过文件夹导出来实现这一部分便签的导出)
Cursor noteCursor = mContext.getContentResolver().query( Cursor noteCursor = mContext.getContentResolver().query(
Notes.CONTENT_NOTE_URI, Notes.CONTENT_NOTE_URI,
NOTE_PROJECTION, NOTE_PROJECTION,
@ -314,16 +320,16 @@ public class BackupUtils {
*/ */
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) { private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(Environment.getExternalStorageDirectory()); sb.append(Environment.getExternalStorageDirectory()); //外部SD卡的存储路径
sb.append(context.getString(filePathResId)); sb.append(context.getString(filePathResId)); //文件的存储路径
File filedir = new File(sb.toString()); File filedir = new File(sb.toString()); //filedir应该就是用来存储路径信息
sb.append(context.getString( sb.append(context.getString(
fileNameFormatResId, fileNameFormatResId,
DateFormat.format(context.getString(R.string.format_date_ymd), DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis()))); System.currentTimeMillis())));
File file = new File(sb.toString()); File file = new File(sb.toString());
try { try {//如果这些文件不存在,则新建
if (!filedir.exists()) { if (!filedir.exists()) {
filedir.mkdir(); filedir.mkdir();
} }
@ -337,6 +343,7 @@ public class BackupUtils {
e.printStackTrace(); e.printStackTrace();
} }
// try catch 异常处理
return null; return null;
} }
} }

@ -37,7 +37,7 @@ import java.util.HashSet;
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils"; public static final String TAG = "DataUtils";
public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) { public static boolean batchDeleteNotes(ContentResolver resolver, HashSet<Long> ids) {//直接删除多个笔记
if (ids == null) { if (ids == null) {
Log.d(TAG, "the ids is null"); Log.d(TAG, "the ids is null");
return true; return true;
@ -46,7 +46,7 @@ public class DataUtils {
Log.d(TAG, "no id is in the hashset"); Log.d(TAG, "no id is in the hashset");
return true; return true;
} }
//提供一个任务列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) { for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) { if(id == Notes.ID_ROOT_FOLDER) {
@ -54,11 +54,12 @@ public class DataUtils {
continue; continue;
} }
ContentProviderOperation.Builder builder = ContentProviderOperation ContentProviderOperation.Builder builder = ContentProviderOperation
.newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id)); .newDelete(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id));//用newDelete实现删除功能
operationList.add(builder.build()); operationList.add(builder.build());
} }
try { try {//主机名或叫Authority用于唯一标识这个ContentProvider外部调用者可以根据这个标识来找到它。
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList); ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
//数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行
if (results == null || results.length == 0 || results[0] == null) { if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString()); Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false; return false;
@ -114,7 +115,7 @@ public class DataUtils {
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
*/ */
public static int getUserFolderCount(ContentResolver resolver) { public static int getUserFolderCount(ContentResolver resolver) {//通过withAppendedId方法为该Uri加上ID
Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor =resolver.query(Notes.CONTENT_NOTE_URI,
new String[] { "COUNT(*)" }, new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?", NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
@ -145,7 +146,7 @@ public class DataUtils {
boolean exist = false; boolean exist = false;
if (cursor != null) { if (cursor != null) {
if (cursor.getCount() > 0) { if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空
exist = true; exist = true;
} }
cursor.close(); cursor.close();
@ -187,6 +188,7 @@ public class DataUtils {
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?", " AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null); new String[] { name }, null);
//通过名字查询文件是否存在
boolean exist = false; boolean exist = false;
if(cursor != null) { if(cursor != null) {
if(cursor.getCount() > 0) { if(cursor.getCount() > 0) {
@ -250,7 +252,7 @@ public class DataUtils {
+ CallNote.PHONE_NUMBER + ",?)", + CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber }, new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null); null);
//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) { if (cursor != null) {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
try { try {

@ -15,7 +15,7 @@
*/ */
package net.micode.notes.tool; package net.micode.notes.tool;
//为jsonObject提供Key把这些定义全部写到一个类里方便查看管理
public class GTaskStringUtils { public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id"; public final static String GTASK_JSON_ACTION_ID = "action_id";

@ -21,7 +21,7 @@ import android.preference.PreferenceManager;
import net.micode.notes.R; import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity; import net.micode.notes.ui.NotesPreferenceActivity;
//获取资源并且在程序中使用,比如颜色图片等
public class ResourceParser { public class ResourceParser {
public static final int YELLOW = 0; public static final int YELLOW = 0;

Loading…
Cancel
Save