Compare commits

..

2 Commits

Author SHA1 Message Date
p42zuhvry f45b53820b v1
1 year ago
wsy cbdfd2ab2a v1
1 year ago

Binary file not shown.

Before

Width:  |  Height:  |  Size: 520 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

@ -31,44 +31,33 @@ import net.micode.notes.ui.NotesPreferenceActivity;
public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// 定义一个静态常量用于标识通知的ID
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) {
// 发布进度
publishProgress(new String[] {
message
});
@ -92,87 +81,59 @@ public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {
// pendingIntent);
// mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
// }
// 显示通知
private void showNotification(int tickerId, String content) {
// 创建一个PendingIntent用于在通知被点击时启动相应的Activity
PendingIntent pendingIntent;
if (tickerId != R.string.ticker_success) {
// 如果tickerId不等于R.string.ticker_success则创建一个PendingIntent用于启动NotesPreferenceActivity
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesPreferenceActivity.class), PendingIntent.FLAG_IMMUTABLE);
} else {
// 如果tickerId等于R.string.ticker_success则创建一个PendingIntent用于启动NotesListActivity
pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
NotesListActivity.class), PendingIntent.FLAG_IMMUTABLE);
}
// 创建一个Notification.Builder对象用于构建通知
Notification.Builder builder = new Notification.Builder(mContext)
.setAutoCancel(true) // 点击通知后自动消失
.setContentTitle(mContext.getString(R.string.app_name)) // 设置通知的标题
// 设置通知内容
.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);}
mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);
}
@Override
// 重写doInBackground方法用于在后台执行同步操作
protected Integer doInBackground(Void... unused) {
// 发布进度,显示同步账户名称
publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
.getSyncAccountName(mContext)));
// 调用mTaskManager的sync方法执行同步操作并返回结果
return mTaskManager.sync(mContext, this);
}
@Override
// 重写父类方法,当进度更新时调用
protected void onProgressUpdate(String... progress) {
// 显示通知通知内容为正在同步进度为progress[0]
showNotification(R.string.ticker_syncing, progress[0]);
// 如果上下文是GTaskSyncService的实例
if (mContext instanceof GTaskSyncService) {
// 发送广播广播内容为progress[0]
((GTaskSyncService) mContext).sendBroadcast(progress[0]);
}
}
@Override
protected void onPostExecute(Integer result) {
// 如果同步成功
if (result == GTaskManager.STATE_SUCCESS) {
// 显示成功通知
showNotification(R.string.ticker_success, mContext.getString(
R.string.success_sync_account, mTaskManager.getSyncAccount()));
// 设置最后同步时间
NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());
// 如果网络错误
} else if (result == GTaskManager.STATE_NETWORK_ERROR) {
// 显示网络错误通知
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
// 如果内部错误
} else if (result == GTaskManager.STATE_INTERNAL_ERROR) {
// 显示内部错误通知
showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
// 如果同步取消
} else if (result == GTaskManager.STATE_SYNC_CANCELLED) {
// 显示同步取消通知
showNotification(R.string.ticker_cancel, mContext
.getString(R.string.error_sync_cancelled));
}
// 如果有完成监听器
if (mOnCompleteListener != null) {
// 在新线程中执行完成监听器的完成方法
new Thread(new Runnable() {
public void run() {
// 调用mOnCompleteListener的onComplete方法
mOnCompleteListener.onComplete();
}
}).start();

@ -62,76 +62,50 @@ import java.util.zip.InflaterInputStream;
public class GTaskClient {
// 定义TAG常量用于日志输出
private static final String TAG = GTaskClient.class.getSimpleName();
// 定义GTask的URL
private static final String GTASK_URL = "https://mail.google.com/tasks/";
// 定义GTask的GET URL
private static final String GTASK_GET_URL = "https://mail.google.com/tasks/ig";
// 定义GTask的POST URL
private static final String GTASK_POST_URL = "https://mail.google.com/tasks/r/ig";
// 定义GTaskClient的实例
private static GTaskClient mInstance = null;
// 定义DefaultHttpClient实例
private DefaultHttpClient mHttpClient;
// 定义GET URL
private String mGetUrl;
private String mPostUrl;
// 客户端版本
private long mClientVersion;
// 是否已登录
private boolean mLoggedin;
// 最后一次登录时间
private long mLastLoginTime;
// 动作ID
private int mActionId;
// 账户信息
private Account mAccount;
// 更新数组
private JSONArray mUpdateArray;
// 构造函数
private GTaskClient() {
// 初始化HTTP客户端
mHttpClient = null;
// 获取URL
mGetUrl = GTASK_GET_URL;
// 提交URL
mPostUrl = GTASK_POST_URL;
// 客户端版本
mClientVersion = -1;
// 是否已登录
mLoggedin = false;
// 最后一次登录时间
mLastLoginTime = 0;
// 动作ID
mActionId = 1;
// 账户信息
mAccount = null;
// 更新数组
mUpdateArray = null;
}
// 获取GTaskClient实例
public static synchronized GTaskClient getInstance() {
// 如果实例为空则创建一个新的GTaskClient实例
if (mInstance == null) {
mInstance = new GTaskClient();
}
// 返回单例实例
return mInstance;
}
@ -139,123 +113,79 @@ public class GTaskClient {
// we suppose that the cookie would expire after 5 minutes
// then we need to re-login
final long interval = 1000 * 60 * 5;
// 如果上次登录时间加上5分钟小于当前时间则表示cookie已过期需要重新登录
if (mLastLoginTime + interval < System.currentTimeMillis()) {
mLoggedin = false;
}
// need to re-login after account switch
// 如果已经登录并且同步账户的名称与NotesPreferenceActivity中的同步账户名称不相等则将mLoggedin设置为false
if (mLoggedin
// 判断条件如果当前同步账户的名称与NotesPreferenceActivity中的同步账户名称不相等
&& !TextUtils.equals(getSyncAccount().name, NotesPreferenceActivity
.getSyncAccountName(activity))) {
// 设置登录状态为未登录
mLoggedin = false;
}
// 判断是否已经登录
if (mLoggedin) {
// 如果已经登录,打印日志信息
Log.d(TAG, "already logged in");
// 返回true
return true;
}
// 获取当前时间
mLastLoginTime = System.currentTimeMillis();
// 登录Google账号
String authToken = loginGoogleAccount(activity, false);
// 如果登录失败
if (authToken == null) {
// 打印错误日志
Log.e(TAG, "login google account failed");
// 返回false
return false;
}
// login with custom domain if necessary
if (!(mAccount.name.toLowerCase().endsWith("gmail.com") || mAccount.name.toLowerCase()
.endsWith("googlemail.com"))) {
// 如果mAccount.name不是以"gmail.com"或"googlemail.com"结尾,则执行以下代码
StringBuilder url = new StringBuilder(GTASK_URL).append("a/");
// 创建一个StringBuilder对象并将GTASK_URL和"a/"拼接起来
int index = mAccount.name.indexOf('@') + 1;
// 获取mAccount.name中'@'符号的索引并加1
String suffix = mAccount.name.substring(index);
// 获取mAccount.name中'@'符号后面的字符串
url.append(suffix + "/");
// 将suffix和"/"拼接起来并添加到url中
mGetUrl = url.toString() + "ig";
// 将url和"ig"拼接起来并赋值给mGetUrl
mPostUrl = url.toString() + "r/ig";
// 将url和"r/ig"拼接起来并赋值给mPostUrl
if (tryToLoginGtask(activity, authToken)) {
// 如果tryToLoginGtask方法返回true则执行以下代码
mLoggedin = true;
// 将mLoggedin设置为true
}
}
// try to login with google official url
// 如果没有登录
if (!mLoggedin) {
// 设置获取URL
mGetUrl = GTASK_GET_URL;
// 设置提交URL
mPostUrl = GTASK_POST_URL;
// 尝试登录
if (!tryToLoginGtask(activity, authToken)) {
// 如果登录失败返回false
return false;
}
}
// 设置登录状态为已登录
// 返回true
mLoggedin = true;
return true;
}
private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
// 定义一个字符串变量authToken
String authToken;
// 获取AccountManager实例
AccountManager accountManager = AccountManager.get(activity);
// 获取所有类型为com.google的账户
Account[] accounts = accountManager.getAccountsByType("com.google");
// 如果没有可用的google账户
if (accounts.length == 0) {
// 打印错误日志
Log.e(TAG, "there is no available google account");
// 返回null
return null;
}
// 获取同步账户名称
String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
// 初始化账户为null
Account account = null;
// 遍历账户列表
for (Account a : accounts) {
// 如果账户名称与同步账户名称相同
if (a.name.equals(accountName)) {
// 将账户赋值给account
account = a;
// 跳出循环
break;
}
}
// 如果account不为null
if (account != null) {
// 将account赋值给mAccount
mAccount = account;
} else {
// 如果account为null则打印错误日志
Log.e(TAG, "unable to get an account with the same name in the settings");
// 返回null
return null;
}
@ -263,309 +193,207 @@ public class GTaskClient {
AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account,
"goanna_mobile", null, activity, null, null);
try {
// 获取认证令牌的结果
Bundle authTokenBundle = accountManagerFuture.getResult();
// 从结果中获取认证令牌
authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
// 如果需要无效化令牌则无效化令牌并重新登录Google账户
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
private boolean tryToLoginGtask(Activity activity, String authToken) {
// 如果登录失败
if (!loginGtask(authToken)) {
// maybe the auth token is out of date, now let's invalidate the
// token and try again
// 登录Google账号
authToken = loginGoogleAccount(activity, true);
// 如果登录失败
if (authToken == null) {
// 打印错误日志
Log.e(TAG, "login google account failed");
return false;
}
// 判断是否登录gtask失败
if (!loginGtask(authToken)) {
// 打印错误日志
Log.e(TAG, "login gtask failed");
// 返回false
return false;
}
}
// 返回true
return true;
}
// 登录Gtask
private boolean loginGtask(String authToken) {
// 设置连接超时时间
int timeoutConnection = 10000;
// 设置Socket超时时间
int timeoutSocket = 15000;
// 创建HttpParams对象
HttpParams httpParameters = new BasicHttpParams();
// 设置连接超时时间
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// 设置Socket超时时间
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// 创建DefaultHttpClient对象
mHttpClient = new DefaultHttpClient(httpParameters);
// 创建BasicCookieStore对象
BasicCookieStore localBasicCookieStore = new BasicCookieStore();
// 设置CookieStore
mHttpClient.setCookieStore(localBasicCookieStore);
// 设置是否使用Expect: 100-continue
HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
// login gtask
try {
// 构造登录URL
String loginUrl = mGetUrl + "?auth=" + authToken;
// 创建HttpGet对象
HttpGet httpGet = new HttpGet(loginUrl);
// 执行请求
HttpResponse response = null;
response = mHttpClient.execute(httpGet);
// get the cookie now
// 获取CookieStore中的所有Cookie
List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
// 定义一个布尔变量用于判断是否有认证Cookie
boolean hasAuthCookie = false;
// 遍历所有Cookie
for (Cookie cookie : cookies) {
// 如果Cookie的名称包含"GTL"则说明有认证Cookie
if (cookie.getName().contains("GTL")) {
hasAuthCookie = true;
}
}
// 如果没有认证Cookie则输出警告日志
if (!hasAuthCookie) {
Log.w(TAG, "it seems that there is no auth cookie");
}
// get the client version
// 获取响应内容
String resString = getResponseContent(response.getEntity());
// 定义js开始字符串
String jsBegin = "_setup(";
// 定义js结束字符串
String jsEnd = ")}</script>";
// 获取js开始字符串在响应内容中的位置
int begin = resString.indexOf(jsBegin);
// 获取js结束字符串在响应内容中的位置
int end = resString.lastIndexOf(jsEnd);
// 定义js字符串
String jsString = null;
// 如果开始字符串和结束字符串都存在,并且开始字符串的位置在结束字符串之前
if (begin != -1 && end != -1 && begin < end) {
// 获取js字符串
jsString = resString.substring(begin + jsBegin.length(), end);
}
// 将jsString转换为JSONObject对象
JSONObject js = new JSONObject(jsString);
// 获取JSONObject对象中的v字段的值并将其赋值给mClientVersion变量
mClientVersion = js.getLong("v");
// 捕获JSONException异常并打印异常信息
} 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;
}
// 返回true表示成功获取到mClientVersion的值
return true;
}
private int getActionId() {
// 获取动作ID
return mActionId++;
}
private HttpPost createHttpPost() {
// 创建HttpPost对象
HttpPost httpPost = new HttpPost(mPostUrl);
// 设置请求头Content-Type为application/x-www-form-urlencoded;charset=utf-8
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 设置请求头AT为1
httpPost.setHeader("AT", "1");
// 返回HttpPost对象
return httpPost;
}
private String getResponseContent(HttpEntity entity) throws IOException {
// 获取响应内容的编码
String contentEncoding = null;
if (entity.getContentEncoding() != null) {
// 获取响应内容的编码
contentEncoding = entity.getContentEncoding().getValue();
// 打印编码
Log.d(TAG, "encoding: " + contentEncoding);
}
InputStream input = entity.getContent();
// 如果contentEncoding不为空且等于gzip则将input设置为GZIPInputStream
if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
input = new GZIPInputStream(entity.getContent());
// 如果contentEncoding不为空且等于deflate则将input设置为InflaterInputStream
} else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
// 创建一个Inflater对象true表示使用ZLIB压缩算法
Inflater inflater = new Inflater(true);
// 创建一个InflaterInputStream对象将entity.getContent()作为输入流inflater作为解压缩算法
input = new InflaterInputStream(entity.getContent(), inflater);
}
try {
// 创建一个InputStreamReader对象用于将输入流转换为字符流
InputStreamReader isr = new InputStreamReader(input);
// 创建一个BufferedReader对象用于读取字符流
BufferedReader br = new BufferedReader(isr);
// 创建一个StringBuilder对象用于存储读取的字符流
StringBuilder sb = new StringBuilder();
while (true) {
// 读取一行数据
String buff = br.readLine();
// 如果读取到的数据为空,则返回已经读取到的数据
if (buff == null) {
return sb.toString();
}
// 将读取到的数据添加到StringBuilder中
sb = sb.append(buff);
}
} finally {
// 关闭输入流
input.close();
}
}
// 发送post请求
private JSONObject postRequest(JSONObject js) throws NetworkFailureException {
// 如果没有登录,抛出异常
if (!mLoggedin) {
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
// 创建HttpPost对象
HttpPost httpPost = createHttpPost();
try {
// 创建一个LinkedList对象用于存储BasicNameValuePair对象
LinkedList<BasicNameValuePair> list = new LinkedList<BasicNameValuePair>();
// 将一个BasicNameValuePair对象添加到LinkedList中该对象包含一个键值对键为"r"值为js.toString()的字符串表示
list.add(new BasicNameValuePair("r", js.toString()));
// 创建一个UrlEncodedFormEntity对象将list参数转换为UTF-8编码的表单数据
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
// 将UrlEncodedFormEntity对象设置为httpPost的实体
httpPost.setEntity(entity);
// execute the post
// 执行httpPost请求
HttpResponse response = mHttpClient.execute(httpPost);
// 获取响应内容
String jsString = getResponseContent(response.getEntity());
// 返回一个JSONObject对象
return new JSONObject(jsString);
} catch (ClientProtocolException e) {
// 捕获ClientProtocolException异常
Log.e(TAG, e.toString());
// 打印异常信息
e.printStackTrace();
// 抛出NetworkFailureException异常
throw new NetworkFailureException("postRequest failed");
} catch (IOException e) {
// 捕获IOException异常
Log.e(TAG, e.toString());
// 打印异常信息
e.printStackTrace();
// 抛出NetworkFailureException异常
throw new NetworkFailureException("postRequest failed");
} catch (JSONException e) {
// 捕获JSONException异常
Log.e(TAG, e.toString());
// 打印异常信息
e.printStackTrace();
// 抛出ActionFailureException异常
throw new ActionFailureException("unable to convert response content to jsonobject");
} catch (Exception e) {
// 捕获其他异常
Log.e(TAG, e.toString());
// 打印异常信息
e.printStackTrace();
// 抛出ActionFailureException异常
throw new ActionFailureException("error occurs when posting request");
}
}
public void createTask(Task task) throws NetworkFailureException {
// 提交更新
commitUpdate();
try {
// 创建一个JSONObject对象
JSONObject jsPost = new JSONObject();
// 创建一个JSONArray对象
JSONArray actionList = new JSONArray();
// action_list
// 将task的createAction方法返回的值放入actionList中
actionList.put(task.getCreateAction(getActionId()));
// 将actionList放入jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 将mClientVersion放入jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// post
JSONObject jsResponse = postRequest(jsPost);
// 获取返回的JSON对象中的results数组中的第一个元素
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 将返回的JSON对象中的new_id赋值给task的gid
task.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
// 打印错误日志
Log.e(TAG, e.toString());
e.printStackTrace();
// 抛出异常
throw new ActionFailureException("create task: handing jsonobject failed");
}
}
// 创建任务列表
public void createTaskList(TaskList tasklist) throws NetworkFailureException {
// 提交更新
commitUpdate();
try {
// 创建一个JSONObject对象
JSONObject jsPost = new JSONObject();
// 创建一个JSONArray对象
JSONArray actionList = new JSONArray();
// action_list
// 将tasklist中获取的创建动作添加到actionList中
actionList.put(tasklist.getCreateAction(getActionId()));
// 将actionList添加到jsPost中键为GTASK_JSON_ACTION_LIST
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client version
@ -573,110 +401,77 @@ public class GTaskClient {
// post
JSONObject jsResponse = postRequest(jsPost);
// 从jsResponse中获取GTaskStringUtils.GTASK_JSON_RESULTS数组中的第一个元素并将其转换为JSONObject类型
JSONObject jsResult = (JSONObject) jsResponse.getJSONArray(
GTaskStringUtils.GTASK_JSON_RESULTS).get(0);
// 将JSONObject中的GTaskStringUtils.GTAS键对应的值设置到tasklist的gid属性中
tasklist.setGid(jsResult.getString(GTaskStringUtils.GTASK_JSON_NEW_ID));
} catch (JSONException e) {
// 捕获JSONException异常
Log.e(TAG, e.toString());
// 打印异常信息
e.printStackTrace();
// 抛出自定义异常ActionFailureException并传入异常信息
throw new ActionFailureException("create tasklist: handing jsonobject failed");
}
}
public void commitUpdate() throws NetworkFailureException {
// 如果mUpdateArray不为空则执行以下操作
if (mUpdateArray != null) {
try {
// 创建一个JSONObject对象
JSONObject jsPost = new JSONObject();
// action_list
// 将mUpdateArray放入jsPost中键为GTASK_JSON_ACTION_LIST
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, mUpdateArray);
// client_version
// 将客户端版本号添加到jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送post请求
postRequest(jsPost);
// 将mUpdateArray置为null
mUpdateArray = null;
// 捕获JSONException异常
} catch (JSONException e) {
// 打印异常信息
Log.e(TAG, e.toString());
e.printStackTrace();
// 抛出ActionFailureException异常异常信息为"commit update: handing jsonobject failed"
throw new ActionFailureException("commit update: handing jsonobject failed");
}
}
}
public void addUpdateNode(Node node) throws NetworkFailureException {
// 检查传入的节点是否为空
if (node != null) {
// too many update items may result in an error
// set max to 10 items
// 如果mUpdateArray不为空且长度大于10则执行commitUpdate()方法
if (mUpdateArray != null && mUpdateArray.length() > 10) {
commitUpdate();
}
// 如果mUpdateArray为空则创建一个新的JSONArray对象
if (mUpdateArray == null)
mUpdateArray = new JSONArray();
// 将node的更新动作添加到mUpdateArray中
mUpdateArray.put(node.getUpdateAction(getActionId()));
}
}
// 将任务task从preParent移动到curParent
public void moveTask(Task task, TaskList preParent, TaskList curParent)
throws NetworkFailureException {
// 提交更新
commitUpdate();
try {
// 创建一个JSONObject对象
JSONObject jsPost = new JSONObject();
// 创建一个JSONArray对象
JSONArray actionList = new JSONArray();
// 创建一个JSONObject对象
JSONObject action = new JSONObject();
// action_list
// 将GTASK_JSON_ACTION_TYPE键的值设置为GTASK_JSON_ACTION_TYPE_MOVE
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_MOVE);
// 将GTASK_JSON_ACTION_ID键的值设置为getActionId()方法的返回值
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
// 将GTASK_JSON_ID键的值设置为task对象的getGid()方法的返回值
action.put(GTaskStringUtils.GTASK_JSON_ID, task.getGid());
// 如果preParent和curParent相等且task对象的getPriorSibling()方法返回值不为null
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中
action.put(GTaskStringUtils.GTASK_JSON_PRIOR_SIBLING_ID, task.getPriorSibling());
}
// 将任务的前一个父节点的GID放入action中
action.put(GTaskStringUtils.GTASK_JSON_SOURCE_LIST, preParent.getGid());
// 将任务的新父节点的GID放入action中
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());
}
// 将action添加到actionList中
actionList.put(action);
// 将actionList添加到jsPost中键为GTASK_JSON_ACTION_LIST
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
@ -684,169 +479,107 @@ public class GTaskClient {
postRequest(jsPost);
// 捕获JSON异常
} catch (JSONException e) {
// 打印错误日志
Log.e(TAG, e.toString());
e.printStackTrace();
// 抛出ActionFailureException异常异常信息为"move task: handing jsonobject failed"
// 抛出ActionFailureException异常异常信息为"move task: handing jsonobject failed"
throw new ActionFailureException("move task: handing jsonobject failed");
}
}
// 删除节点
public void deleteNode(Node node) throws NetworkFailureException {
// 提交更新
commitUpdate();
try {
// 创建一个JSONObject对象
JSONObject jsPost = new JSONObject();
// 创建一个JSONArray对象
JSONArray actionList = new JSONArray();
// action_list
// 设置节点为已删除状态
node.setDeleted(true);
// 将节点的更新操作添加到action_list中
actionList.put(node.getUpdateAction(getActionId()));
// 将action_list添加到jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 将客户端版本号添加到jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送post请求
postRequest(jsPost);
// 将mUpdateArray置为null
mUpdateArray = null;
} catch (JSONException e) {
// 捕获JSONException异常
Log.e(TAG, e.toString());
e.printStackTrace();
// 抛出ActionFailureException异常
throw new ActionFailureException("delete node: handing jsonobject failed");
}
}
public JSONArray getTaskLists() throws NetworkFailureException {
// 检查用户是否已经登录
if (!mLoggedin) {
// 如果没有登录,则抛出异常
Log.e(TAG, "please login first");
throw new ActionFailureException("not logged in");
}
try {
// 创建一个HttpGet对象用于发送GET请求
HttpGet httpGet = new HttpGet(mGetUrl);
// 声明一个HttpResponse对象用于接收服务器返回的响应
HttpResponse response = null;
// 使用HttpClient执行HttpGet请求并将响应赋值给response对象
response = mHttpClient.execute(httpGet);
// get the task list
String resString = getResponseContent(response.getEntity());
// 获取响应内容
String jsBegin = "_setup(";
// 定义js字符串开始标志
String jsEnd = ")}</script>";
// 定义js字符串结束标志
int begin = resString.indexOf(jsBegin);
// 获取js字符串开始位置
int end = resString.lastIndexOf(jsEnd);
// 获取js字符串结束位置
String jsString = null;
// 定义js字符串
if (begin != -1 && end != -1 && begin < end) {
// 如果开始位置、结束位置都存在且开始位置在结束位置之前
jsString = resString.substring(begin + jsBegin.length(), end);
// 获取js字符串
}
// 将jsString转换为JSONObject对象
JSONObject js = new JSONObject(jsString);
// 返回JSONObject对象中键为"t"的JSONObject对象中键为GTASK_JSON_LISTS的JSONArray对象
return js.getJSONObject("t").getJSONArray(GTaskStringUtils.GTASK_JSON_LISTS);
// 捕获ClientProtocolException异常
} catch (ClientProtocolException e) {
// 打印异常信息
Log.e(TAG, e.toString());
e.printStackTrace();
// 抛出网络失败异常
throw new NetworkFailureException("gettasklists: httpget failed");
// 捕获IO异常
} catch (IOException e) {
// 打印错误日志
Log.e(TAG, e.toString());
// 打印堆栈信息
e.printStackTrace();
catch (JSONException e) {
// 捕获JSONException异常
throw new NetworkFailureException("gettasklists: httpget failed");
} catch (JSONException e) {
Log.e(TAG, e.toString());
// 打印异常信息
e.printStackTrace();
// 抛出自定义异常ActionFailureException并传入异常信息
throw new ActionFailureException("get task lists: handing jasonobject failed") throw new NetworkFailureException("gettasklists: httpget failed");
} ;
throw new ActionFailureException("get task lists: handing jasonobject failed");
}
}
// 根据listGid获取任务列表
public JSONArray getTaskList(String listGid) throws NetworkFailureException {
// 提交更新
commitUpdate();
try {
// 创建一个JSONObject对象
JSONObject jsPost = new JSONObject();
// 创建一个JSONArray对象
JSONArray actionList = new JSONArray();
// 创建一个JSONObject对象
JSONObject action = new JSONObject();
// action_list
// 设置action类型为获取所有任务
action.put(GTaskStringUtils.GTASK_JSON_ACTION_TYPE,
GTaskStringUtils.GTASK_JSON_ACTION_TYPE_GETALL);
// 设置action的id
action.put(GTaskStringUtils.GTASK_JSON_ACTION_ID, getActionId());
// 设置任务的list id
action.put(GTaskStringUtils.GTASK_JSON_LIST_ID, listGid);
// 设置是否获取已删除的任务
action.put(GTaskStringUtils.GTASK_JSON_GET_DELETED, false);
// 将action添加到actionList中
actionList.put(action);
// 将actionList添加到jsPost中
jsPost.put(GTaskStringUtils.GTASK_JSON_ACTION_LIST, actionList);
// client_version
// 设置客户端版本
jsPost.put(GTaskStringUtils.GTASK_JSON_CLIENT_VERSION, mClientVersion);
// 发送post请求获取响应
JSONObject jsResponse = postRequest(jsPost);
// 返回响应中的任务数组
return jsResponse.getJSONArray(GTaskStringUtils.GTASK_JSON_TASKS);
// 捕获JSONException异常
} catch (JSONException e) {
// 打印错误日志
Log.e(TAG, e.toString());
// 打印异常堆栈信息
e.printStackTrace();
// 抛出自定义异常ActionFailureException并传入错误信息
throw new ActionFailureException("get task list: handing jsonobject failed");
}
}
// 获取同步账户
public Account getSyncAccount() {
// 返回mAccount
return mAccount;
}
// 重置更新数组
public void resetUpdateArray() {
// 将更新数组置为空
mUpdateArray = null;
}
}

@ -0,0 +1,490 @@
/*
* 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.tool;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.text.TextUtils;
import android.text.format.DateFormat;
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.DataConstants;
import net.micode.notes.data.Notes.NoteColumns;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class BackupUtils {
// 定义一个常量,用于打印日志
private static final String TAG = "BackupUtils";
// Singleton stuff
// 定义一个静态变量用于保存BackupUtils的实例
private static BackupUtils sInstance;
// 获取BackupUtils实例
public static synchronized BackupUtils getInstance(Context context) {
// 如果sInstance为空则创建一个新的BackupUtils实例
if (sInstance == null) {
sInstance = new BackupUtils(context);
}
// 返回sInstance实例
return sInstance;
}
/**
* Following states are signs to represents backup or restore
* status
*/
// Currently, the sdcard is not mounted
// 定义一个常量表示SD卡未挂载的状态
public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist
// 定义一个常量,表示备份文件不存在
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs
// 定义一个常量,表示数据被销毁的状态
public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails
// 定义一个常量,表示系统错误状态
public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success
// 定义一个常量,表示成功状态
public static final int STATE_SUCCESS = 4;
// 声明一个TextExport类型的变量mTextExport
private TextExport mTextExport;
// 定义一个BackupUtils类构造函数接收一个Context参数
private BackupUtils(Context context) {
// 创建一个TextExport对象传入Context参数
mTextExport = new TextExport(context);
}
// 检查外部存储是否可用
private static boolean externalStorageAvailable() {
// 返回外部存储的状态是否为MEDIA_MOUNTED
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 导出为文本文件
public int exportToText() {
// 调用mTextExport对象的exportToText方法
return mTextExport.exportToText();
}
// 获取导出的文本文件名
public String getExportedTextFileName() {
// 返回mTextExport对象的mFileName属性
return mTextExport.mFileName;
}
// 获取导出的文本文件目录
public String getExportedTextFileDir() {
// 返回mTextExport对象的mFileDirectory属性
return mTextExport.mFileDirectory;
}
// 定义一个静态内部类TextExport
private static class TextExport {
// 定义一个常量数组NOTE_PROJECTION包含NoteColumns中的ID、MODIFIED_DATE、SNIPPET、TYPE四个字段
private static final String[] NOTE_PROJECTION = {
// 获取NoteColumns中的ID、MODIFIED_DATE、SNIPPET字段
// NoteColumns.ID 表示Note表的ID列
NoteColumns.ID,
// 添加注释
NoteColumns.MODIFIED_DATE, // 修改日期
// 定义NoteColumns类中的SNIPPET常量
NoteColumns.SNIPPET,
// 定义一个常量表示NoteColumns中的TYPE列
NoteColumns.TYPE
};
// 定义一个常量表示笔记的ID列
private static final int NOTE_COLUMN_ID = 0;
// 定义一个常量,表示笔记的修改日期列
private static final int NOTE_COLUMN_MODIFIED_DATE = 1;
// 定义一个常量,表示笔记的摘要列
private static final int NOTE_COLUMN_SNIPPET = 2;
// 定义一个常量数组,用于存储数据投影
private static final String[] DATA_PROJECTION = {
// 数据列
DataColumns.CONTENT,
// 数据列的MIME类型
DataColumns.MIME_TYPE,
// 数据列1
DataColumns.DATA1,
DataColumns.DATA2,
DataColumns.DATA3,
DataColumns.DATA4,
};
// 定义一个常量,表示数据列的内容
private static final int DATA_COLUMN_CONTENT = 0;
// 定义一个常量表示数据列的MIME类型
private static final int DATA_COLUMN_MIME_TYPE = 1;
// 定义一个常量,表示数据列的调用日期
private static final int DATA_COLUMN_CALL_DATE = 2;
// 定义一个常量,表示数据列中的电话号码列的索引
private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 声明一个字符串数组,用于存储文本格式
private final String [] TEXT_FORMAT;
// 定义一个常量,表示文件夹名称的格式
private static final int FORMAT_FOLDER_NAME = 0;
// 定义常量,表示日期格式
private static final int FORMAT_NOTE_DATE = 1;
// 定义常量,表示格式化笔记内容的格式
private static final int FORMAT_NOTE_CONTENT = 2;
// 定义一个Context类型的成员变量
private Context mContext;
// 声明一个字符串类型的私有变量mFileName
private String mFileName;
// 文件目录
private String mFileDirectory;
// 构造函数用于创建TextExport对象
public TextExport(Context context) {
// 获取导出笔记的格式数组
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
// 保存上下文
mContext = context;
// 初始化文件名为空字符串
mFileName = "";
// 初始化文件目录为空字符串
mFileDirectory = "";
}
// 根据id获取格式
private String getFormat(int id) {
// 返回TEXT_FORMAT数组中索引为id的元素
return TEXT_FORMAT[id];
}
/**
// 导出由folder id标识的文件夹到文本
* Export the folder identified by folder id to text
*/
// 将文件夹导出到文本文件
private void exportFolderToText(String folderId, PrintStream ps) {
// Query notes belong to this folder
// 获取指定文件夹下的所有笔记
Cursor notesCursor = mContext.getContentResolver().query(Notes.CONTENT_NOTE_URI,
// 定义一个常量用于查询Note表中的数据
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
// 定义一个变量folderId用于存储文件夹的ID
folderId
// 定义一个无符号长整型变量
}, null);
// 判断notesCursor是否为空
if (notesCursor != null) {
// 如果notesCursor指向的数据表中有数据
if (notesCursor.moveToFirst()) {
do {
// Print note's last modified date
// 打印日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
// 获取字符串资源,格式为"yyyy-MM-dd HH:mm"
mContext.getString(R.string.format_datetime_mdhm),
// 获取notesCursor中NOTE_COLUMN_MODIFIED_DATE列的值并将其转换为long类型
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 从notesCursor中获取NOTE_COLUMN_ID列的值并将其赋值给noteId变量
String noteId = notesCursor.getString(NOTE_COLUMN_ID);
// 导出笔记到文本
exportNoteToText(noteId, ps);
// 使用while循环遍历notesCursor中的数据
} while (notesCursor.moveToNext());
}
// 关闭游标
notesCursor.close();
}
}
/**
* Export note identified by id to a print stream
*/
// 将笔记导出到文本文件
private void exportNoteToText(String noteId, PrintStream ps) {
// 获取Notes表中的数据
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
// 查询数据指定投影为DATA_PROJECTION条件为DataColumns.NOTE_ID等于noteId不指定排序
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId
}, null);
// 如果dataCursor不为空
if (dataCursor != null) {
// 如果dataCursor可以移动到第一行
if (dataCursor.moveToFirst()) {
// do 关键字用于开始一个循环,循环体内的代码会一直执行,直到遇到 break 关键字
do {
// 获取数据的光标
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
// 判断mimeType是否等于DataConstants.CALL_NOTE
if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number
// 从dataCursor中获取电话号码
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
// 获取dataCursor中DATA_COLUMN_CALL_DATE列的值并将其赋值给callDate变量
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
// 获取数据光标中指定列的字符串值
String location = dataCursor.getString(DATA_COLUMN_CONTENT);
// 判断phoneNumber是否为空
if (!TextUtils.isEmpty(phoneNumber)) {
// 打印格式化后的字符串
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber));
}
// Print call date
// 打印格式化后的字符串
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
// 格式化日期
.format(mContext.getString(R.string.format_datetime_mdhm),
callDate)));
// Print call attachment location
// 判断location是否为空
if (!TextUtils.isEmpty(location)) {
// 使用String.format方法将location格式化为指定格式并打印输出
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location));
}
} else if (DataConstants.NOTE.equals(mimeType)) {
// 获取数据内容
String content = dataCursor.getString(DATA_COLUMN_CONTENT);
// 如果内容不为空
if (!TextUtils.isEmpty(content)) {
// 打印格式化后的内容
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
content));
}
}
// 如果dataCursor可以移动到下一个位置则继续循环
} while (dataCursor.moveToNext());
}
dataCursor.close();
}
// print a line separator between note
try {
// 向ps写入一个换行符和一个字母数字字符
ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER
});
} catch (IOException e) {
// 捕获IOException异常并打印错误日志
Log.e(TAG, e.toString());
}
}
/**
* Note will be exported as text which is user readable
*/
public int exportToText() {
// 检查外部存储是否可用
if (!externalStorageAvailable()) {
// 如果外部存储不可用,则输出日志信息
Log.d(TAG, "Media was not mounted");
// 返回SD卡未挂载状态
return STATE_SD_CARD_UNMOUONTED;
}
// 获取导出到文本的PrintStream
PrintStream ps = getExportToTextPrintStream();
// 如果获取失败
if (ps == null) {
// 打印错误日志
Log.e(TAG, "get print stream error");
// 返回系统错误状态
return STATE_SYSTEM_ERROR;
}
// First export folder and its notes
// 查询数据库,获取文件夹和通话记录文件夹的信息
Cursor folderCursor = mContext.getContentResolver().query(
// 定义一个常量表示笔记的URI
Notes.CONTENT_NOTE_URI,
// 声明一个名为NOTE_PROJECTION的常量
NOTE_PROJECTION,
"(" + NoteColumns.TYPE + "=" + Notes.TYPE_FOLDER + " AND "
+ NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + ") OR "
+ NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER, null, null);
// 如果folderCursor不为空
if (folderCursor != null) {
// 如果游标指向的数据集不为空
if (folderCursor.moveToFirst()) {
do {
// Print folder's name
// 声明一个字符串变量folderName用于存储文件夹名称
String folderName = "";
// 如果文件夹游标中的ID等于Notes中的ID_CALL_RECORD_FOLDER则将文件夹名称设置为上下文中的call_record_folder_name字符串
if(folderCursor.getLong(NOTE_COLUMN_ID) == Notes.ID_CALL_RECORD_FOLDER) {
folderName = mContext.getString(R.string.call_record_folder_name);
// 如果文件夹名称为空,则从游标中获取文件夹名称
} else {
folderName = folderCursor.getString(NOTE_COLUMN_SNIPPET);
}
// 判断folderName是否为空
if (!TextUtils.isEmpty(folderName)) {
// 使用String.format方法将folderName格式化为指定格式并输出到ps流中
ps.println(String.format(getFormat(FORMAT_FOLDER_NAME), folderName));
}
// 获取文件夹ID
String folderId = folderCursor.getString(NOTE_COLUMN_ID);
// 将文件夹导出到文本
exportFolderToText(folderId, ps);
// 移动到下一个文件夹
} while (folderCursor.moveToNext());
}
// 关闭文件夹游标
folderCursor.close();
}
// Export notes in root's folder
// 获取一个游标查询Notes表中type为Notes.TYPE_NOTE且parent_id为0的数据 Cursor noteCursor = mContext.getContentResolver().query(
Cursor noteCursor = mContext.getContentResolver().query(
// 定义一个Notes类其中包含一个CONTENT_NOTE_URI常量用于表示Notes表的URI
Notes.CONTENT_NOTE_URI,
// 定义一个常量,用于表示投影
NOTE_PROJECTION,
// 拼接查询条件查询类型为Notes.TYPE_NOTE且父ID为NoteColumns.PARENT_ID的记录
NoteColumns.TYPE + "=" + +Notes.TYPE_NOTE + " AND " + NoteColumns.PARENT_ID
+ "=0", null, null);
// 如果noteCursor不为空
if (noteCursor != null) {
// 如果游标移动到第一行
if (noteCursor.moveToFirst()) {
do {
// 打印笔记的修改日期
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm),
noteCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note
// 获取当前游标中的noteId
String noteId = noteCursor.getString(NOTE_COLUMN_ID);
// 将noteId导出到文本中
exportNoteToText(noteId, ps);
// 如果游标还有下一个元素,则继续循环
} while (noteCursor.moveToNext());
}
// 关闭游标
noteCursor.close();
}
// 关闭ps
ps.close();
// 返回成功状态
return STATE_SUCCESS;
}
/**
* Get a print stream pointed to the file {@generateExportedTextFile}
*/
private PrintStream getExportToTextPrintStream() {
// 生成一个挂载在SD卡上的文件
File file = generateFileMountedOnSDcard(mContext, R.string.file_path,
R.string.file_name_txt_format);
// 如果文件生成失败则返回null
if (file == null) {
Log.e(TAG, "create file to exported failed");
return null;
}
// 获取文件名
mFileName = file.getName();
// 获取文件路径
mFileDirectory = mContext.getString(R.string.file_path);
PrintStream ps = null;
try {
// 创建文件输出流
FileOutputStream fos = new FileOutputStream(file);
// 创建PrintStream对象
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
// 文件未找到异常,打印异常信息
e.printStackTrace();
return null;
} catch (NullPointerException e) {
// 空指针异常,打印异常信息
e.printStackTrace();
return null;
}
// 返回PrintStream对象
return ps;
}
}
/**
* Generate the text file to store imported data
*/
// 生成一个挂载在SD卡上的文件
private static File generateFileMountedOnSDcard(Context context, int filePathResId, int fileNameFormatResId) {
// 创建一个StringBuilder对象
StringBuilder sb = new StringBuilder();
// 将SD卡的根目录添加到StringBuilder中
sb.append(Environment.getExternalStorageDirectory());
// 将文件路径字符串添加到StringBuilder中
sb.append(context.getString(filePathResId));
// 创建一个File对象表示文件路径
File filedir = new File(sb.toString());
// 将文件名格式字符串添加到StringBuilder中
sb.append(context.getString(
fileNameFormatResId,
// 使用当前时间格式化文件名
DateFormat.format(context.getString(R.string.format_date_ymd),
System.currentTimeMillis())));
// 创建一个File对象表示文件名
File file = new File(sb.toString());
try {
// 如果文件路径不存在,则创建文件夹
if (!filedir.exists()) {
filedir.mkdir();
}
// 如果文件不存在,则创建文件
if (!file.exists()) {
file.createNewFile();
}
// 返回文件对象
return file;
} catch (SecurityException e) {
// 捕获SecurityException异常并打印异常信息
e.printStackTrace();
} catch (IOException e) {
// 捕获IOException异常并打印异常信息
e.printStackTrace();
}
// 返回null
return null;
}
}

@ -0,0 +1,90 @@
/*
* 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.data;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import java.util.HashMap;
public class Contact {
// 定义一个静态的HashMap用于缓存联系人信息
private static HashMap<String, String> sContactCache;
// 定义一个常量,用于打印日志
private static final String TAG = "Contact";
// 定义一个常量用于查询联系人信息的SQL语句
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE min_match = '+')";
// 根据传入的上下文和电话号码获取联系人信息
public static String getContact(Context context, String phoneNumber) {
// 如果联系人缓存为空则创建一个新的HashMap
if(sContactCache == null) {
sContactCache = new HashMap<String, String>();
}
// 如果sContactCache中包含phoneNumber键
if(sContactCache.containsKey(phoneNumber)) {
// 返回sContactCache中phoneNumber键对应的值
return sContactCache.get(phoneNumber);
}
// 将电话号码转换为Caller ID的最小匹配格式并替换掉"+"号
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
// 通过ContentResolver查询Data表获取电话号码对应的联系人姓名
Cursor cursor = context.getContentResolver().query(
Data.CONTENT_URI,
new String [] { Phone.DISPLAY_NAME },
selection,
new String[] { phoneNumber },
null);
if (cursor != null && cursor.moveToFirst()) {
try {
// 获取联系人姓名
String name = cursor.getString(0);
// 将联系人姓名存入缓存
sContactCache.put(phoneNumber, name);
// 返回联系人姓名
return name;
} catch (IndexOutOfBoundsException e) {
// 捕获索引越界异常
Log.e(TAG, " Cursor get string error " + e.toString());
// 返回null
return null;
} finally {
// 关闭游标
cursor.close();
}
} else {
// 没有匹配的联系人
Log.d(TAG, "No contact matched with number:" + phoneNumber);
// 返回null
return null;
}
}
}

@ -0,0 +1,152 @@
// 定义一个常量表示原始父级ID
public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/**
* The gtask id
* <P> Type : TEXT </P>
*/
// 定义一个常量用于存储任务ID
public static final String GTASK_ID = "gtask_id";
/**
* The version code
* <P> Type : INTEGER (long) </P>
*/
// 定义一个常量,表示版本号
public static final String VERSION = "version";
}
// 定义一个接口DataColumns
public interface DataColumns {
/**
* The unique ID for a row
* <P> Type: INTEGER (long) </P>
*/
// 定义一个常量表示ID
public static final String ID = "_id";
/**
* The MIME type of the item represented by this row.
* <P> Type: Text </P>
*/
// 定义一个常量表示MIME类型
public static final String MIME_TYPE = "mime_type";
/**
* The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P>
*/
// 定义一个常量表示笔记的ID
public static final String NOTE_ID = "note_id";
/**
* Created data for note or folder
* <P> Type: INTEGER (long) </P>
*/
// 声明一个常量,表示创建日期
public static final String CREATED_DATE = "created_date";
/**
* Latest modified date
* <P> Type: INTEGER (long) </P>
*/
// 声明一个常量,表示修改日期
public static final String MODIFIED_DATE = "modified_date";
/**
* Data's content
* <P> Type: TEXT </P>
*/
// 定义一个常量CONTENT值为"content"
public static final String CONTENT = "content";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
// 定义一个常量DATA1值为"data1"
// 定义一个常量DATA1值为"data1"
public static final String DATA1 = "data1";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* integer data type
* <P> Type: INTEGER </P>
*/
// 定义一个常量DATA2值为"data2"
public static final String DATA2 = "data2";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
// 定义一个常量DATA3值为"data3"
public static final String DATA3 = "data3";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
// 定义一个常量DATA4值为"data4"
public static final String DATA4 = "data4";
/**
* Generic data column, the meaning is {@link #MIMETYPE} specific, used for
* TEXT data type
* <P> Type: TEXT </P>
*/
// 定义一个常量DATA5值为"data5"
public static final String DATA5 = "data5";
}
// 实现DataColumns接口的TextNote类
public static final class TextNote implements DataColumns {
/**
* Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P>
*/
public static final String MODE = DATA1;
// 定义一个常量,表示检查列表的模式
public static final int MODE_CHECK_LIST = 1;
// 定义一个常量,表示内容类型为文本笔记
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/text_note";
// 定义一个常量,表示内容项类型为文本笔记
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
// 定义一个常量表示内容URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
}
// 定义一个名为CallNote的公共静态内部类实现DataColumns接口
public static final class CallNote implements DataColumns {
/**
* Call date for this record
* <P> Type: INTEGER (long) </P>
*/
// 定义一个常量,表示调用日期
public static final String CALL_DATE = DATA1;
/**
* Phone number for this record
* <P> Type: TEXT </P>
*/
// 定义一个常量,表示电话号码
public static final String PHONE_NUMBER = DATA3;
// 定义一个常量,表示内容类型
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
// 定义一个常量,表示内容项类型
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
// 定义一个常量表示内容URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
}
}

@ -0,0 +1,437 @@
/*
* 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.data;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import net.micode.notes.R;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE;
public class NotesProvider extends ContentProvider {
// 定义一个UriMatcher对象用于匹配Uri
private static final UriMatcher mMatcher;
// 定义一个NotesDatabaseHelper对象用于操作数据库
private NotesDatabaseHelper mHelper;
// 定义一个常量用于标识NotesProvider
private static final String TAG = "NotesProvider";
// 定义一个常量用于标识URI_NOTE
private static final int URI_NOTE = 1;
// 定义一个常量用于标识URI_NOTE_ITEM
private static final int URI_NOTE_ITEM = 2;
// 定义一个常量用于标识URI_DATA
private static final int URI_DATA = 3;
// 定义一个常量用于标识URI_DATA_ITEM
private static final int URI_DATA_ITEM = 4;
// 定义一个常量用于标识URI_SEARCH
private static final int URI_SEARCH = 5;
// 定义一个常量用于标识URI_SEARCH_SUGGEST
private static final int URI_SEARCH_SUGGEST = 6;
// 静态代码块用于初始化UriMatcher对象
static {
// 创建UriMatcher对象NO_MATCH表示没有匹配的URI
mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 添加URI匹配规则匹配Notes.AUTHORITY下的note匹配成功返回URI_NOTE
mMatcher.addURI(Notes.AUTHORITY, "note", URI_NOTE);
// 添加URI匹配规则匹配Notes.AUTHORITY下的note/#匹配成功返回URI_NOTE_ITEM
mMatcher.addURI(Notes.AUTHORITY, "note/#", URI_NOTE_ITEM);
// 添加URI匹配规则匹配Notes.AUTHORITY下的data匹配成功返回URI_DATA
mMatcher.addURI(Notes.AUTHORITY, "data", URI_DATA);
// 添加URI匹配规则匹配Notes.AUTHORITY下的data/#匹配成功返回URI_DATA_ITEM
mMatcher.addURI(Notes.AUTHORITY, "data/#", URI_DATA_ITEM);
// 添加URI匹配规则匹配Notes.AUTHORITY下的search匹配成功返回URI_SEARCH
mMatcher.addURI(Notes.AUTHORITY, "search", URI_SEARCH);
// 添加URI匹配规则匹配Notes.AUTHORITY下的search/*匹配成功返回URI_SEARCH_SUGGEST
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, URI_SEARCH_SUGGEST);
// 添加URI匹配规则匹配Notes.AUTHORITY下的search/*/*匹配成功返回URI_SEARCH_SUGGEST
mMatcher.addURI(Notes.AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", URI_SEARCH_SUGGEST);
}
/**
* x'0A' represents the '\n' character in sqlite. For title and content in the search result,
* we will trim '\n' and white space in order to show more information.
*/
// 定义一个常量,用于搜索笔记的投影
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
// 将笔记的ID作为搜索建议的额外数据
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
// 将笔记的摘要作为搜索建议的文本1
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
// 将笔记的摘要作为搜索建议的文本2
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_2 + ","
// 将搜索结果的图标设置为drawable/search_result
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
// 将搜索建议的意图动作设置为Intent.ACTION_VIEW
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
// 将搜索建议的意图数据设置为Notes.TextNote.CONTENT_TYPE
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 定义一个静态字符串变量,用于查询笔记片段
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
// 查询笔记片段
+ " FROM " + TABLE.NOTE
// 从笔记表中查询
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
// 笔记片段匹配查询条件
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
// 笔记的父ID不等于垃圾桶文件夹
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override
// 重写onCreate方法
public boolean onCreate() {
// 获取NotesDatabaseHelper的实例
mHelper = NotesDatabaseHelper.getInstance(getContext());
// 返回true
return true;
}
@Override
// 重写query方法用于查询数据
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
// 声明一个Cursor对象
Cursor c = null;
// 获取可读的数据库
SQLiteDatabase db = mHelper.getReadableDatabase();
// 声明一个id变量
String id = null;
// 根据传入的uri执行不同的数据库查询操作
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 查询note表
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_NOTE_ITEM:
// 查询note表中指定id的记录
id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
case URI_DATA:
// 查询data表
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder);
break;
case URI_DATA_ITEM:
// 查询data表中指定id的记录
id = uri.getPathSegments().get(1);
// 查询数据库中指定表的数据返回一个Cursor对象
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder);
break;
// 搜索URI
case URI_SEARCH:
// 搜索建议URI
case URI_SEARCH_SUGGEST:
// 查询搜索结果
// 如果sortOrder不为空或者projection不为空则抛出异常
if (sortOrder != null || projection != null) {
// 抛出IllegalArgumentException异常异常信息为"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"
throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
}
// 获取搜索字符串
String searchString = null;
// 如果匹配到URI_SEARCH_SUGGEST
if (mMatcher.match(uri) == URI_SEARCH_SUGGEST) {
// 如果URI的路径段大于1
if (uri.getPathSegments().size() > 1) {
// 获取路径段的第二个元素作为搜索字符串
searchString = uri.getPathSegments().get(1);
}
} else {
// 获取uri中的查询参数pattern
searchString = uri.getQueryParameter("pattern");
}
// 如果查询参数为空则返回null
if (TextUtils.isEmpty(searchString)) {
return null;
}
try {
// 将搜索字符串格式化为包含通配符的字符串
searchString = String.format("%%%s%%", searchString);
// 执行查询语句,返回结果集
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString });
} catch (IllegalStateException ex) {
// 捕获异常并打印错误日志
Log.e(TAG, "got exception: " + ex.toString());
}
break;
default:
// 抛出异常表示未知的URI
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 如果结果集不为空则设置通知URI
if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri);
}
// 返回结果集
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// 获取可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
// 定义变量用于存储插入的数据ID
long dataId = 0, noteId = 0, insertedId = 0;
// 根据传入的URI进行匹配
switch (mMatcher.match(uri)) {
// 如果匹配到URI_NOTE
case URI_NOTE:
// 在NOTE表中插入数据并获取插入的数据ID
insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break;
// 如果匹配到URI_DATA
case URI_DATA:
// 如果values中包含NOTE_ID
if (values.containsKey(DataColumns.NOTE_ID)) {
// 获取NOTE_ID
noteId = values.getAsLong(DataColumns.NOTE_ID);
} else {
// 否则,打印错误日志
Log.d(TAG, "Wrong data format without note id:" + values.toString());
}
// 在DATA表中插入数据并获取插入的数据ID
insertedId = dataId = db.insert(TABLE.DATA, null, values);
break;
// 如果没有匹配到任何URI
default:
// 抛出异常
throw new IllegalArgumentException("Unknown URI " + uri);
}
// Notify the note uri
if (noteId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
}
// Notify the data uri
if (dataId > 0) {
getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
}
return ContentUris.withAppendedId(uri, insertedId);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// 初始化删除的记录数
int count = 0;
// 初始化ID
String id = null;
// 获取可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
// 初始化删除数据标志
boolean deleteData = false;
// 根据URI匹配不同的删除操作
switch (mMatcher.match(uri)) {
// 删除笔记
case URI_NOTE:
// 添加删除条件
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
// 执行删除操作
count = db.delete(TABLE.NOTE, selection, selectionArgs);
break;
// 删除笔记项
case URI_NOTE_ITEM:
// 获取笔记项的ID
id = uri.getPathSegments().get(1);
/**
* ID that smaller than 0 is system folder which is not allowed to
* trash
*/
// 将id转换为long类型
long noteId = Long.valueOf(id);
// 如果noteId小于等于0则跳出循环
if (noteId <= 0) {
break;
}
// 删除指定id的note
// 删除指定ID的笔记
count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break;
// 处理URI_DATA
case URI_DATA:
// 删除数据
count = db.delete(TABLE.DATA, selection, selectionArgs);
// 标记删除数据
deleteData = true;
break;
// 删除数据项
case URI_DATA_ITEM:
// 获取数据项的id
id = uri.getPathSegments().get(1);
// 删除数据项
count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
// 标记删除数据
deleteData = true;
break;
// 未知URI
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 如果删除了数据
if (count > 0) {
// 如果删除了数据,通知内容解析器
if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
// 通知内容解析器
getContext().getContentResolver().notifyChange(uri, null);
}
// 返回删除的条数
return count;
}
// 重写update方法用于更新数据库中的数据
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
// 定义一个计数器,用于记录更新的数据条数
int count = 0;
// 定义一个字符串用于存储要更新的数据的id
String id = null;
// 获取可写的数据库
SQLiteDatabase db = mHelper.getWritableDatabase();
// 定义一个布尔值,用于判断是否更新了数据
boolean updateData = false;
// 根据传入的uri进行匹配根据匹配结果执行不同的操作
switch (mMatcher.match(uri)) {
case URI_NOTE:
// 增加note的版本号
increaseNoteVersion(-1, selection, selectionArgs);
// 更新note表
count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break;
case URI_NOTE_ITEM:
// 获取uri中的id
id = uri.getPathSegments().get(1);
// 增加note的版本号
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
// 更新note表
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
break;
case URI_DATA:
// 更新data表
count = db.update(TABLE.DATA, values, selection, selectionArgs);
// 标记更新data
updateData = true;
break;
case URI_DATA_ITEM:
// 获取uri中的id
id = uri.getPathSegments().get(1);
// 更新data表
count = db.update(TABLE.DATA, values, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs);
// 标记更新data
updateData = true;
break;
default:
// 抛出异常未知uri
throw new IllegalArgumentException("Unknown URI " + uri);
}
// 如果count大于0
if (count > 0) {
// 如果updateData为true
if (updateData) {
// 通知ContentResolver更新Notes.CONTENT_NOTE_URI
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
}
// 通知ContentResolver更新uri
getContext().getContentResolver().notifyChange(uri, null);
}
// 返回count
return count;
}
// 解析selection字符串
private String parseSelection(String selection) {
// 如果selection不为空
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
}
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
// 创建一个StringBuilder对象用于拼接SQL语句
StringBuilder sql = new StringBuilder(120);
// 拼接UPDATE语句
sql.append("UPDATE ");
// 拼接表名
sql.append(TABLE.NOTE);
// 拼接SET语句
sql.append(" SET ");
// 拼接版本号字段
sql.append(NoteColumns.VERSION);
// 拼接版本号增加1的语句
sql.append("=" + NoteColumns.VERSION + "+1 ");
// 如果id大于0或者selection不为空则拼接WHERE语句
if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE ");
}
// 如果id大于0则拼接id等于指定值的语句
if (id > 0) {
sql.append(NoteColumns.ID + "=" + String.valueOf(id));
}
// 判断selection是否为空
if (!TextUtils.isEmpty(selection)) {
// 如果id大于0则调用parseSelection方法解析selection否则直接赋值给selectString
String selectString = id > 0 ? parseSelection(selection) : selection;
// 遍历selectionArgs数组将每个元素替换selectString中的第一个问号
for (String args : selectionArgs) {
selectString = selectString.replaceFirst("\\?", args);
}
// 将selectString追加到sql中
sql.append(selectString);
}
// 获取可写的数据库
mHelper.getWritableDatabase().execSQL(sql.toString());
}
@Override
public String getType(Uri uri) {
// 获取Uri的类型
// TODO Auto-generated method stub
Loading…
Cancel
Save