Compare commits

...

17 Commits

@ -1,31 +1,4 @@
<<<<<<< HEAD
<<<<<<< HEAD
# gitProject1
1.精读小米便签源代码,写泛读报告
<<<<<<< HEAD
2.
=======
=======
<<<<<<< HEAD
<<<<<<< HEAD
# gitProject1
abc
=======
# gitProject1
>>>>>>> 9219e5ac71f6be25d7e582668d694b98d6c6b249
>>>>>>> 56b7401c41e8a93705075c2dec372535147025bf
=======
# gitProject1
>>>>>>> 678e0f2fc21bc4a1625205602371ca421396ceee
>>>>>>> 856149d31b3fdb3d65ebb0c2da0a49c2b8417f9e
=======
# gitProject1
=======
# gitProject1
# 小米便签
1.精读小米便签源代码,写泛读报告
>>>>>>> ec5b092c2fe5adbe24627fc2992503627dc1795b
>>>>>>> 5f5cff49fcbaa1b5df8823143d84bbfcc52cd49f
>>>>>>> 63fc6f227a94c2fab6101a51858ced17a7619c89

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

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

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

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

@ -56,60 +56,62 @@ public class Note {
values.put(NoteColumns.LOCAL_MODIFIED, 1);//把LOCAL_MODIFIED 本地修改 的值赋为1
values.put(NoteColumns.PARENT_ID, folderId);//把文件夹id赋给PARENT_ID 父类id
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
//getContentResolver()函数是实现外部应用对于ContentProvider中的数据进行增删查改的操作
long noteId = 0;
long noteId = 0;//用于标记错误信息
try {
noteId = Long.valueOf(uri.getPathSegments().get(1));
}
catch (NumberFormatException e) {
Log.e(TAG, "Get note id error :" + e.toString());
noteId = 0;
}
}//异常处理
if (noteId == -1) {
throw new IllegalStateException("Wrong note id:" + noteId);
}
} // 如果发生错误输出错误ID
return noteId;
}
public Note() {
mNoteDiffValues = new ContentValues();
mNoteData = new NoteData();
mNoteDiffValues = new ContentValues(); //定义一个新变量,存储便签属性
mNoteData = new NoteData();//定义一个新变量,存出便签内容
}
public void setNoteValue(String key, String value) {
mNoteDiffValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mNoteDiffValues.put(key, value); //设置便签属性传入ket和value
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); //设置新创建的便签更改次数为1
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); //设置新创建的更改日期为系统当前时间
}
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
mNoteData.setTextData(key, value); //设置便签的内容和数据
}
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
mNoteData.setTextDataId(id); //设置便签数据的ID
}
public long getTextDataId() {
return mNoteData.mTextDataId;
return mNoteData.mTextDataId; //获取便签数据的ID
}
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
mNoteData.setCallDataId(id); //设置电话的数据的ID
}
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
mNoteData.setCallData(key, value); //设置电话的内容和数据
}
public boolean isLocalModified() {
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified();
}
return mNoteDiffValues.size() > 0 || mNoteData.isLocalModified(); //
}//判断是否为本地产生的修改
public boolean syncNote(Context context, long noteId) {
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
} //报告错误信息
if (!isLocalModified()) {
return true;
@ -120,6 +122,13 @@ public class Note {
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
*/
/*
{@link NoteColumns#LOCAL_MODIFIED}
{@link NotesColumns#MODIFIED_DATE}
*/
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
@ -134,16 +143,16 @@ public class Note {
}
return true;
}
}//用于判断便签是否正确同步
private class NoteData {
private long mTextDataId;
private long mTextDataId; //定义便签数据的文件数据ID
private ContentValues mTextDataValues;
private ContentValues mTextDataValues; //定义文件数据
private long mCallDataId;
private long mCallDataId;//定义便签电话ID
private ContentValues mCallDataValues;
private ContentValues mCallDataValues;//定义便签电话数据
private static final String TAG = "NoteData";
@ -152,57 +161,62 @@ public class Note {
mCallDataValues = new ContentValues();
mTextDataId = 0;
mCallDataId = 0;
}
} //构造函数定义文件数据ID和电话数据ID为0创建便签电话数据和文件数据类
boolean isLocalModified() {
return mTextDataValues.size() > 0 || mCallDataValues.size() > 0;
}
}//判断是否被本地修改,返回是否修改文本数据或者电话数据
void setTextDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Text data id should larger than 0");
}
mTextDataId = id;
} //为文本数据ID的定义提供错误判断
mTextDataId = id; //设置文本数据ID
}
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
}
mCallDataId = id;
}//为电话数据ID的定义提供错误判断
mCallDataId = id;//设置电话数据ID
}
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mCallDataValues.put(key, value); //设置电话数据的数据和内容
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1); //设置电话数据的本地修改为1
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis()); //设置修改时间为本地时间
}
void setTextData(String key, String value) {
mTextDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());
mTextDataValues.put(key, value); //设置文本数据
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 1);//设置文本数据的本地修改为1
mNoteDiffValues.put(NoteColumns.MODIFIED_DATE, System.currentTimeMillis());//设置修改时间为本地时间
}
Uri pushIntoContentResolver(Context context, long noteId) {
/*
*Uri
*/
/**
* Check for safety
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
}//显示错误代码
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>(); //定义一个新的可变数组
ContentProviderOperation.Builder builder = null; //数据库的操作列表设置为空
if (mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
if (mTextDataValues.size() > 0) { //如果文本数据的值不为0
mTextDataValues.put(DataColumns.NOTE_ID, noteId); //存入note数据ID
if (mTextDataId == 0) {
mTextDataValues.put(DataColumns.MIME_TYPE, TextNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mTextDataValues);
try {
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
setTextDataId(Long.valueOf(uri.getPathSegments().get(1)));
}
catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
@ -217,7 +231,7 @@ public class Note {
operationList.add(builder.build());
}
mTextDataValues.clear();
}
}//把文本数据存入到DataColumns
if (mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
@ -241,7 +255,7 @@ public class Note {
operationList.add(builder.build());
}
mCallDataValues.clear();
}
}//把电话数据存入到DataColumns
if (operationList.size() > 0) {
try {
@ -260,6 +274,6 @@ public class Note {
}
}
return null;
}
}//存储过程中对于异常情况的处理
}
}

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

@ -37,7 +37,7 @@ import java.util.HashSet;
public class 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) {
Log.d(TAG, "the ids is null");
return true;
@ -46,7 +46,7 @@ public class DataUtils {
Log.d(TAG, "no id is in the hashset");
return true;
}
//提供一个任务列表
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
for (long id : ids) {
if(id == Notes.ID_ROOT_FOLDER) {
@ -54,11 +54,12 @@ public class DataUtils {
continue;
}
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());
}
try {
try {//主机名或叫Authority用于唯一标识这个ContentProvider外部调用者可以根据这个标识来找到它。
ContentProviderResult[] results = resolver.applyBatch(Notes.AUTHORITY, operationList);
//数据库事务,数据库事务是由一组数据库操作序列组成,事务作为一个整体被执行
if (results == null || results.length == 0 || results[0] == null) {
Log.d(TAG, "delete notes failed, ids:" + ids.toString());
return false;
@ -114,7 +115,7 @@ public class DataUtils {
/**
* 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,
new String[] { "COUNT(*)" },
NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>?",
@ -145,7 +146,7 @@ public class DataUtils {
boolean exist = false;
if (cursor != null) {
if (cursor.getCount() > 0) {
if (cursor.getCount() > 0) {//用getcount函数判断cursor是否为空
exist = true;
}
cursor.close();
@ -187,6 +188,7 @@ public class DataUtils {
" AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER +
" AND " + NoteColumns.SNIPPET + "=?",
new String[] { name }, null);
//通过名字查询文件是否存在
boolean exist = false;
if(cursor != null) {
if(cursor.getCount() > 0) {
@ -250,7 +252,7 @@ public class DataUtils {
+ CallNote.PHONE_NUMBER + ",?)",
new String [] { String.valueOf(callDate), CallNote.CONTENT_ITEM_TYPE, phoneNumber },
null);
//通过数据库操作查询条件是callDate和phoneNumber匹配传入参数的值
if (cursor != null) {
if (cursor.moveToFirst()) {
try {

@ -15,7 +15,7 @@
*/
package net.micode.notes.tool;
//为jsonObject提供Key把这些定义全部写到一个类里方便查看管理
public class GTaskStringUtils {
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.ui.NotesPreferenceActivity;
//获取资源并且在程序中使用,比如颜色图片等
public class ResourceParser {
public static final int YELLOW = 0;

Loading…
Cancel
Save