Compare commits

..

No commits in common. 'ce28b7edc9b5c2725ae1dd836cb1fc7bb86c6b6f' and '006919e15e383c2a7d0640048015c8d1d522caeb' have entirely different histories.

@ -12,10 +12,6 @@
</deviceKey> </deviceKey>
</Target> </Target>
</targetSelectedWithDropDown> </targetSelectedWithDropDown>
<<<<<<< HEAD:.idea/deploymentTargetDropDown.xml
<timeTargetWasSelectedWithDropDown value="2023-04-07T06:44:46.634860500Z" /> <timeTargetWasSelectedWithDropDown value="2023-04-07T06:44:46.634860500Z" />
=======
<timeTargetWasSelectedWithDropDown value="2023-04-07T06:36:29.852905700Z" />
>>>>>>> master:src/.idea/deploymentTargetDropDown.xml
</component> </component>
</project> </project>

@ -1,293 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AndroidLayouts">
<shared>
<config />
</shared>
</component>
<component name="AutoImportSettings">
<option name="autoReloadType" value="NONE" />
</component>
<component name="ChangeListManager">
<list default="true" id="2531eea7-ec98-43ef-9f7f-09fe1004db56" name="变更" comment="庞浩的注释">
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/checksums/checksums.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/checksums/md5-checksums.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/checksums/sha1-checksums.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/dependencies-accessors/dependencies-accessors.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/dependencies-accessors/gc.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/executionHistory/executionHistory.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/fileChanges/last-build.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/fileHashes/fileHashes.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.4.2/gc.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/checksums/checksums.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/checksums/md5-checksums.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/checksums/sha1-checksums.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/dependencies-accessors/dependencies-accessors.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/dependencies-accessors/gc.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/executionHistory/executionHistory.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/executionHistory/executionHistory.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/fileChanges/last-build.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/fileHashes/fileHashes.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/fileHashes/fileHashes.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/fileHashes/resourceHashesCache.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/7.5/gc.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/buildOutputCleanup/buildOutputCleanup.lock" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/buildOutputCleanup/cache.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/buildOutputCleanup/outputFiles.bin" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/file-system.probe" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.gradle/vcs-1/gc.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/compiler.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/deploymentTargetDropDown.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/gradle.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/jarRepositories.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/misc.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/modules.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/modules/app/minote.app.androidTest.iml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/modules/app/minote.app.iml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/modules/app/minote.app.main.iml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/modules/app/minote.app.unitTest.iml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/.idea/vcs.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/build.gradle" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/gradle/wrapper/gradle-wrapper.jar" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/gradle/wrapper/gradle-wrapper.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/gradlew" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/gradlew.bat" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/import-summary.txt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/local.properties" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/minote.iml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/settings.gradle" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/.gitignore" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/compiler.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/deploymentTargetDropDown.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/gradle.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/jarRepositories.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/misc.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/modules.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/modules/app/minote.app.androidTest.iml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/modules/app/minote.app.iml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/modules/app/minote.app.main.iml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/modules/app/minote.app.unitTest.iml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/vcs.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/net/micode/notes/data/NotesProvider.java" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/net/micode/notes/data/NotesProvider.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/net/micode/notes/model/Note.java" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/net/micode/notes/model/Note.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/net/micode/notes/model/WorkingNote.java" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/net/micode/notes/model/WorkingNote.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/build.gradle" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.jar" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradle/wrapper/gradle-wrapper.properties" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradlew" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/gradlew.bat" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/import-summary.txt" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/local.properties" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/minote.iml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/settings.gradle" beforeDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="device_and_snapshot_combo_box_target[C:\Users\庞浩的电脑\.android\avd\Pixel_3_API_22.avd]" />
<component name="ExternalProjectsData">
<projectState path="$PROJECT_DIR$">
<ProjectState />
</projectState>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2O5GlHnjCn5qBz61G2RsTAQaajO" />
<component name="ProjectLevelVcsManager">
<ConfirmationsSetting value="2" id="Add" />
</component>
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;ASKED_ADD_EXTERNAL_FILES&quot;: &quot;true&quot;,
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.cidr.known.project.marker&quot;: &quot;true&quot;,
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;cidr.known.project.marker&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;D:/softwareengineering/Notes-master&quot;,
&quot;project.structure.last.edited&quot;: &quot;Modules&quot;,
&quot;project.structure.proportion&quot;: &quot;0.17&quot;,
&quot;project.structure.side.proportion&quot;: &quot;0.2&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.customizations&quot;
}
}</component>
<component name="RunManager" selected="Android App.app">
<configuration name="app" type="AndroidRunConfigurationType" factoryName="Android App">
<module name="minote.app.main" />
<option name="DEPLOY" value="true" />
<option name="DEPLOY_APK_FROM_BUNDLE" value="false" />
<option name="DEPLOY_AS_INSTANT" value="false" />
<option name="ARTIFACT_NAME" value="" />
<option name="PM_INSTALL_OPTIONS" value="" />
<option name="ALL_USERS" value="false" />
<option name="ALWAYS_INSTALL_WITH_PM" value="false" />
<option name="CLEAR_APP_STORAGE" value="false" />
<option name="DYNAMIC_FEATURES_DISABLED_LIST" value="" />
<option name="ACTIVITY_EXTRA_FLAGS" value="" />
<option name="MODE" value="default_activity" />
<option name="CLEAR_LOGCAT" value="false" />
<option name="SHOW_LOGCAT_AUTOMATICALLY" value="false" />
<option name="INSPECTION_WITHOUT_ACTIVITY_RESTART" value="false" />
<option name="TARGET_SELECTION_MODE" value="DEVICE_AND_SNAPSHOT_COMBO_BOX" />
<option name="SELECTED_CLOUD_MATRIX_CONFIGURATION_ID" value="-1" />
<option name="SELECTED_CLOUD_MATRIX_PROJECT_ID" value="" />
<option name="DEBUGGER_TYPE" value="Auto" />
<Auto>
<option name="USE_JAVA_AWARE_DEBUGGER" value="false" />
<option name="SHOW_STATIC_VARS" value="true" />
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
<option name="SHOW_OPTIMIZED_WARNING" value="true" />
</Auto>
<Hybrid>
<option name="USE_JAVA_AWARE_DEBUGGER" value="false" />
<option name="SHOW_STATIC_VARS" value="true" />
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
<option name="SHOW_OPTIMIZED_WARNING" value="true" />
</Hybrid>
<Java />
<Native>
<option name="USE_JAVA_AWARE_DEBUGGER" value="false" />
<option name="SHOW_STATIC_VARS" value="true" />
<option name="WORKING_DIR" value="" />
<option name="TARGET_LOGGING_CHANNELS" value="lldb process:gdb-remote packets" />
<option name="SHOW_OPTIMIZED_WARNING" value="true" />
</Native>
<Profilers>
<option name="ADVANCED_PROFILING_ENABLED" value="false" />
<option name="STARTUP_PROFILING_ENABLED" value="false" />
<option name="STARTUP_CPU_PROFILING_ENABLED" value="false" />
<option name="STARTUP_CPU_PROFILING_CONFIGURATION_NAME" value="Java/Kotlin Method Sample (legacy)" />
<option name="STARTUP_NATIVE_MEMORY_PROFILING_ENABLED" value="false" />
<option name="NATIVE_MEMORY_SAMPLE_RATE_BYTES" value="2048" />
</Profilers>
<option name="DEEP_LINK" value="" />
<option name="ACTIVITY_CLASS" value="" />
<option name="SEARCH_ACTIVITY_IN_GLOBAL_SCOPE" value="false" />
<option name="SKIP_ACTIVITY_VALIDATION" value="false" />
<method v="2">
<option name="Android.Gradle.BeforeRunTask" enabled="true" />
</method>
</configuration>
<configuration name="D:/softwareengineering/minote/app/build.gradle" type="GradleRunConfiguration" factoryName="Gradle" temporary="true">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$/app/build.gradle" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list />
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<DebugAllEnabled>false</DebugAllEnabled>
<method v="2" />
</configuration>
<recent_temporary>
<list>
<item itemvalue="Gradle.D:/softwareengineering/minote/app/build.gradle" />
</list>
</recent_temporary>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="应用程序级" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="默认任务">
<changelist id="2531eea7-ec98-43ef-9f7f-09fe1004db56" name="变更" comment="" />
<created>1680843179165</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1680843179165</updated>
</task>
<task id="LOCAL-00001" summary="更新">
<created>1680848243607</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1680848243608</updated>
</task>
<task id="LOCAL-00002" summary="注释">
<created>1680850445899</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1680850445899</updated>
</task>
<task id="LOCAL-00003" summary="注释">
<created>1680942675194</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1680942675194</updated>
</task>
<task id="LOCAL-00004" summary="庞浩的注释">
<created>1680942721752</created>
<option name="number" value="00004" />
<option name="presentableId" value="LOCAL-00004" />
<option name="project" value="LOCAL" />
<updated>1680942721752</updated>
</task>
<task id="LOCAL-00005" summary="庞浩的注释">
<created>1681292428634</created>
<option name="number" value="00005" />
<option name="presentableId" value="LOCAL-00005" />
<option name="project" value="LOCAL" />
<updated>1681292428635</updated>
</task>
<task id="LOCAL-00006" summary="庞浩的注释">
<created>1681312464473</created>
<option name="number" value="00006" />
<option name="presentableId" value="LOCAL-00006" />
<option name="project" value="LOCAL" />
<updated>1681312464473</updated>
</task>
<option name="localTasksCounter" value="7" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State>
<option name="FILTERS">
<map>
<entry key="branch">
<value>
<list>
<option value="master" />
</list>
</value>
</entry>
</map>
</option>
</State>
</value>
</entry>
</map>
</option>
</component>
<component name="VcsManagerConfiguration">
<option name="ADD_EXTERNAL_FILES_SILENTLY" value="true" />
<MESSAGE value="更新" />
<MESSAGE value="注释" />
<MESSAGE value="庞浩的注释" />
<option name="LAST_COMMIT_MESSAGE" value="庞浩的注释" />
</component>
</project>

@ -26,34 +26,25 @@ import android.util.Log;
import java.util.HashMap; import java.util.HashMap;
public class Contact { public class Contact {
private static HashMap<String, String> sContactCache;// 用于缓存已查询过的联系人信息 private static HashMap<String, String> sContactCache;
private static final String TAG = "Contact";// 用于日志输出的 TAG private static final String TAG = "Contact";
// 查询电话号码与联系人名字匹配的过滤条件
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'" + ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN " + " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id " + "(SELECT raw_contact_id "
+ " FROM phone_lookup" + " FROM phone_lookup"
+ " WHERE min_match = '+')"; + " WHERE min_match = '+')";
/*
*
* @param context
* @param phoneNumber
* @return
*/
public static String getContact(Context context, String phoneNumber) { public static String getContact(Context context, String phoneNumber) {
// 如果缓存为空,创建新的缓存对象
if(sContactCache == null) { if(sContactCache == null) {
sContactCache = new HashMap<String, String>(); sContactCache = new HashMap<String, String>();
} }
// 如果已经查询过该电话号码,直接返回缓存中的联系人名字
if(sContactCache.containsKey(phoneNumber)) { if(sContactCache.containsKey(phoneNumber)) {
return sContactCache.get(phoneNumber); return sContactCache.get(phoneNumber);
} }
// 构造查询条件
String selection = CALLER_ID_SELECTION.replace("+", String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(phoneNumber)); PhoneNumberUtils.toCallerIDMinMatch(phoneNumber));
Cursor cursor = context.getContentResolver().query( Cursor cursor = context.getContentResolver().query(
@ -63,20 +54,18 @@ public class Contact {
new String[] { phoneNumber }, new String[] { phoneNumber },
null); null);
// 如果能够查询到联系人信息
if (cursor != null && cursor.moveToFirst()) { if (cursor != null && cursor.moveToFirst()) {
try { try {
String name = cursor.getString(0); String name = cursor.getString(0);
// 将电话号码与联系人名字加入缓存中
sContactCache.put(phoneNumber, name); sContactCache.put(phoneNumber, name);
return name; return name;
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
Log.e(TAG, " Cursor get string error " + e.toString()); Log.e(TAG, " Cursor get string error " + e.toString());
return null; return null;
} finally { } finally {
cursor.close();// 关闭查询结果游标 cursor.close();
} }
} else {// 如果未能查询到联系人信息,输出日志并返回 null } else {
Log.d(TAG, "No contact matched with number:" + phoneNumber); Log.d(TAG, "No contact matched with number:" + phoneNumber);
return null; return null;
} }

@ -18,165 +18,155 @@ package net.micode.notes.data;
import android.net.Uri; import android.net.Uri;
public class Notes { public class Notes {
public static final String AUTHORITY = "micode_notes"; // 小米便签内容提供器的URI授权 public static final String AUTHORITY = "micode_notes";
public static final String TAG = "Notes"; // 用于调试和日志记录的标签 public static final String TAG = "Notes";
// 小米便签支持的三种类型 public static final int TYPE_NOTE = 0;
public static final int TYPE_NOTE = 0; // 笔记 public static final int TYPE_FOLDER = 1;
public static final int TYPE_FOLDER = 1;// 文件夹 public static final int TYPE_SYSTEM = 2;
public static final int TYPE_SYSTEM = 2;// 系统便签
/** /**
* Following IDs are system folders' identifiers * Following IDs are system folders' identifiers
* {@link Notes#ID_ROOT_FOLDER } is default folder * {@link Notes#ID_ROOT_FOLDER } is default folder
* {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder * {@link Notes#ID_TEMPARAY_FOLDER } is for notes belonging no folder
* {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records * {@link Notes#ID_CALL_RECORD_FOLDER} is to store call records
*/ */
// 小米便签内置的四个特殊文件夹 public static final int ID_ROOT_FOLDER = 0;
public static final int ID_ROOT_FOLDER = 0; // 根文件夹 public static final int ID_TEMPARAY_FOLDER = -1;
public static final int ID_TEMPARAY_FOLDER = -1; // 临时文件夹 public static final int ID_CALL_RECORD_FOLDER = -2;
public static final int ID_CALL_RECORD_FOLDER = -2;// 通话记录文件夹 public static final int ID_TRASH_FOLER = -3;
public static final int ID_TRASH_FOLER = -3; // 回收站文件夹
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";
public static final String INTENT_EXTRA_ALERT_DATE = "net.micode.notes.alert_date";//提醒时间的Intent extra key用于设置笔记的提醒时间。 public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";
public static final String INTENT_EXTRA_BACKGROUND_ID = "net.micode.notes.background_color_id";//背景颜色的Intent extra key用于设置笔记的背景颜色。 public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";
public static final String INTENT_EXTRA_WIDGET_ID = "net.micode.notes.widget_id";//小部件ID的Intent extra key用于设置小部件的ID。 public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";
public static final String INTENT_EXTRA_WIDGET_TYPE = "net.micode.notes.widget_type";//小部件类型的Intent extra key用于设置小部件的类型。 public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";
public static final String INTENT_EXTRA_FOLDER_ID = "net.micode.notes.folder_id";//文件夹ID的Intent extra key用于设置笔记所属的文件夹。 public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";
public static final String INTENT_EXTRA_CALL_DATE = "net.micode.notes.call_date";//通话时间的Intent extra key用于设置通话笔记的通话时间。
public static final int TYPE_WIDGET_INVALIDE = -1;
public static final int TYPE_WIDGET_INVALIDE = -1;//表示无效的小部件类型,其值为-1。 public static final int TYPE_WIDGET_2X = 0;
public static final int TYPE_WIDGET_2X = 0;//表示2x2大小的小部件其值为0。 public static final int TYPE_WIDGET_4X = 1;
public static final int TYPE_WIDGET_4X = 1;//表示4x4大小的小部件其值为1。
public static class DataConstants { public static class DataConstants {
public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;//指定普通的文本笔记类型 public static final String NOTE = TextNote.CONTENT_ITEM_TYPE;
public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;//指定通话记录笔记类型 public static final String CALL_NOTE = CallNote.CONTENT_ITEM_TYPE;
}//定义笔记的类型 }
/** /**
* Uri to query all notes and folders * Uri to query all notes and folders
*/ */
public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note"); public static final Uri CONTENT_NOTE_URI = Uri.parse("content://" + AUTHORITY + "/note");
/** /**
* Uri to query data * Uri to query data
*/ */
public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data"); public static final Uri CONTENT_DATA_URI = Uri.parse("content://" + AUTHORITY + "/data");
public interface NoteColumns { public interface NoteColumns {
/** /**
* The unique ID for a rowID * The unique ID for a row
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ID = "_id"; public static final String ID = "_id";
/** /**
* The parent's id for note or folder ID * The parent's id for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String PARENT_ID = "parent_id"; public static final String PARENT_ID = "parent_id";
/** /**
* Created data for note or folder * Created data for note or folder
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CREATED_DATE = "created_date"; public static final String CREATED_DATE = "created_date";
/** /**
* Latest modified date * Latest modified date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String MODIFIED_DATE = "modified_date"; public static final String MODIFIED_DATE = "modified_date";
/** /**
* Alert date * Alert date
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String ALERTED_DATE = "alert_date"; public static final String ALERTED_DATE = "alert_date";
/** /**
* Folder's name or text content of note * Folder's name or text content of note
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String SNIPPET = "snippet"; public static final String SNIPPET = "snippet";
/** /**
* Note's widget id ID * Note's widget id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_ID = "widget_id"; public static final String WIDGET_ID = "widget_id";
/** /**
* Note's widget type * Note's widget type
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String WIDGET_TYPE = "widget_type"; public static final String WIDGET_TYPE = "widget_type";
/** /**
* Note's background color's id ID * Note's background color's id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String BG_COLOR_ID = "bg_color_id"; public static final String BG_COLOR_ID = "bg_color_id";
/** /**
* For text note, it doesn't has attachment, for multi-media * For text note, it doesn't has attachment, for multi-media
* note, it has at least one attachment * note, it has at least one attachment
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String HAS_ATTACHMENT = "has_attachment"; public static final String HAS_ATTACHMENT = "has_attachment";
/** /**
* Folder's count of notes * Folder's count of notes
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTES_COUNT = "notes_count"; public static final String NOTES_COUNT = "notes_count";
/** /**
* The file type: folder or note * The file type: folder or note
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String TYPE = "type"; public static final String TYPE = "type";
/** /**
* The last sync id ID * The last sync id
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String SYNC_ID = "sync_id"; public static final String SYNC_ID = "sync_id";
/** /**
* Sign to indicate local modified or not * Sign to indicate local modified or not
* <P> Type: INTEGER </P> * <P> Type: INTEGER </P>
*/ */
public static final String LOCAL_MODIFIED = "local_modified"; public static final String LOCAL_MODIFIED = "local_modified";
/** /**
* Original parent id before moving into temporary folder ID * Original parent id before moving into temporary folder
* <P> Type : INTEGER </P> * <P> Type : INTEGER </P>
*/ */
public static final String ORIGIN_PARENT_ID = "origin_parent_id"; public static final String ORIGIN_PARENT_ID = "origin_parent_id";
/** /**
* The gtask idGoogle ID * The gtask id
* <P> Type : TEXT </P> * <P> Type : TEXT </P>
*/ */
public static final String GTASK_ID = "gtask_id"; public static final String GTASK_ID = "gtask_id";
/** /**
* The version code * The version code
* <P> Type : INTEGER (long) </P> * <P> Type : INTEGER (long) </P>
*/ */
public static final String VERSION = "version"; public static final String VERSION = "version";
} }
/**
* DataColumns
* NotesColumns
* DataColumnsNotesColumns
* NotesColumns
* DataColumns
* 使
*/
public interface DataColumns { public interface DataColumns {
/** /**
* The unique ID for a row * The unique ID for a row
@ -185,13 +175,13 @@ public class Notes {
public static final String ID = "_id"; public static final String ID = "_id";
/** /**
* The MIME type of the item represented by this row.MIME * The MIME type of the item represented by this row.
* <P> Type: Text </P> * <P> Type: Text </P>
*/ */
public static final String MIME_TYPE = "mime_type"; public static final String MIME_TYPE = "mime_type";
/** /**
* The reference id to note that this data belongs toID * The reference id to note that this data belongs to
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String NOTE_ID = "note_id"; public static final String NOTE_ID = "note_id";
@ -251,54 +241,39 @@ public class Notes {
public static final String DATA5 = "data5"; public static final String DATA5 = "data5";
} }
/**
* NotePadTextNote
* DataColumnsURI
* NotesColumnsTextNote
* MODEMODE_CHECK_LIST
* TextNote访URIURIContentProvidertext_note
*/
public static final class TextNote implements DataColumns { public static final class TextNote implements DataColumns {
/** /**
* Mode to indicate the text in check list mode or not * Mode to indicate the text in check list mode or not
* <P> Type: Integer 1:check list mode 0: normal mode </P> * <P> Type: Integer 1:check list mode 0: normal mode </P>
*/ */
public static final String MODE = DATA1;//MODE字段表示文本笔记的模式可以是正常模式或者是带有任务清单的模式类型为整数。它使用了接口中的DATA1字段来表示其存储值的列名。 public static final String MODE = DATA1;
public static final int MODE_CHECK_LIST = 1;//MODE_CHECK_LIST字段表示任务清单模式的值为1。 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_TYPE = "vnd.android.cursor.dir/text_note";
//CONTENT_TYPE字段表示此数据的MIME类型指示ContentProvider返回的数据类型。此处表示返回的是文本笔记列表。
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/text_note";
//CONTENT_ITEM_TYPE字段表示此数据的单个项目的MIME类型。
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/text_note");
//CONTENT_URI字段表示此数据的URI地址。
} }
/**
* NotesCallNoteDataColumns
* CallNoteCALL_DATEPHONE_NUMBER
* ContentProvider使MIMEURI
*/
public static final class CallNote implements DataColumns { public static final class CallNote implements DataColumns {
/** /**
* Call date for this record * Call date for this record
* <P> Type: INTEGER (long) </P> * <P> Type: INTEGER (long) </P>
*/ */
public static final String CALL_DATE = DATA1; public static final String CALL_DATE = DATA1;
//表示通话日期的列名数据类型为long存储在DATA1列中。
/** /**
* Phone number for this record * Phone number for this record
* <P> Type: TEXT </P> * <P> Type: TEXT </P>
*/ */
public static final String PHONE_NUMBER = DATA3; public static final String PHONE_NUMBER = DATA3;
//表示电话号码的列名数据类型为String存储在DATA3列中。
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note"; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/call_note";
//单条通话记录用于指定MIME类型的常量
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/call_note";
//同上,多条通话记录
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note"); public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/call_note");
//该类的内容URI用于访问通话记录。
} }
} }

@ -26,13 +26,7 @@ import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.DataConstants; import net.micode.notes.data.Notes.DataConstants;
import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.data.Notes.NoteColumns;
/**
* NotesDatabaseHelperSQLiteOpenHelper
* DB_NAMEDB_VERSION
* TABLENOTEDATA
* SQLiteOpenHelperAndroidSQLite
*
*/
public class NotesDatabaseHelper extends SQLiteOpenHelper { public class NotesDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "note.db"; private static final String DB_NAME = "note.db";
@ -44,64 +38,52 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
public static final String DATA = "data"; public static final String DATA = "data";
} }
private static final String TAG = "NotesDatabaseHelper";//这一行代码定义了一个名为TAG的字符串常量用于在调试时作为日志标签。 private static final String TAG = "NotesDatabaseHelper";
/**
* mInstanceNotesDatabaseHelperstatic
*
* NotesDatabaseHelper
*
*/
private static NotesDatabaseHelper mInstance; private static NotesDatabaseHelper mInstance;
/**
* CREATE_NOTE_TABLE_SQL CREATE_DATA_TABLE_SQL
* note data
*/
private static final String CREATE_NOTE_TABLE_SQL = private static final String CREATE_NOTE_TABLE_SQL =
"CREATE TABLE " + TABLE.NOTE + "(" + "CREATE TABLE " + TABLE.NOTE + "(" +
NoteColumns.ID + " INTEGER PRIMARY KEY," +//笔记 ID整数类型作为主键 NoteColumns.ID + " INTEGER PRIMARY KEY," +
NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +//父笔记 ID整数类型不为空默认为 0 NoteColumns.PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +//提醒时间,整数类型,不为空,默认为 0 NoteColumns.ALERTED_DATE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +//背景颜色 ID整数类型不为空默认为 0 NoteColumns.BG_COLOR_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +//创建时间,整数类型,不为空,默认为当前时间 NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +//是否有附件,整数类型,不为空,默认为 0 NoteColumns.HAS_ATTACHMENT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +//修改时间,整数类型,不为空,默认为当前时间 NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +//笔记数量,整数类型,不为空,默认为 0 NoteColumns.NOTES_COUNT + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +//笔记概要,文本类型,不为空,默认为空字符串 NoteColumns.SNIPPET + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +//笔记类型,整数类型,不为空,默认为 0 NoteColumns.TYPE + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +//小部件 ID整数类型不为空默认为 0 NoteColumns.WIDGET_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +//小部件类型,整数类型,不为空,默认为 -1 NoteColumns.WIDGET_TYPE + " INTEGER NOT NULL DEFAULT -1," +
NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +//同步 ID整数类型不为空默认为 0 NoteColumns.SYNC_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +//本地修改标识,整数类型,不为空,默认为 0 NoteColumns.LOCAL_MODIFIED + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +//原始父笔记 ID整数类型不为空默认为 0 NoteColumns.ORIGIN_PARENT_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +//Google 任务 ID文本类型不为空默认为空字符串 NoteColumns.GTASK_ID + " TEXT NOT NULL DEFAULT ''," +
NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +//版本号,整数类型,不为空,默认为 0 NoteColumns.VERSION + " INTEGER NOT NULL DEFAULT 0" +
")"; ")";
private static final String CREATE_DATA_TABLE_SQL = private static final String CREATE_DATA_TABLE_SQL =
"CREATE TABLE " + TABLE.DATA + "(" + "CREATE TABLE " + TABLE.DATA + "(" +
DataColumns.ID + " INTEGER PRIMARY KEY," +//数据 ID整数类型作为主键 DataColumns.ID + " INTEGER PRIMARY KEY," +
DataColumns.MIME_TYPE + " TEXT NOT NULL," +//MIME 类型,文本类型,不为空 DataColumns.MIME_TYPE + " TEXT NOT NULL," +
DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +//笔记 ID整数类型不为空默认为 0 DataColumns.NOTE_ID + " INTEGER NOT NULL DEFAULT 0," +
NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +//创建时间,整数类型,不为空,默认为当前时间 NoteColumns.CREATED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +//修改时间,整数类型,不为空,默认为当前时间 NoteColumns.MODIFIED_DATE + " INTEGER NOT NULL DEFAULT (strftime('%s','now') * 1000)," +
DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +//数据内容,文本类型,不为空,默认为空字符串 DataColumns.CONTENT + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA1 + " INTEGER," + DataColumns.DATA1 + " INTEGER," +
DataColumns.DATA2 + " INTEGER," + DataColumns.DATA2 + " INTEGER," +
DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA3 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," + DataColumns.DATA4 + " TEXT NOT NULL DEFAULT ''," +
DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" + DataColumns.DATA5 + " TEXT NOT NULL DEFAULT ''" +
")"; ")";
/**
* SQL"note_id_index"
* "TABLE.DATA"使"DataColumns.NOTE_ID"
* ID
*/
private static final String CREATE_DATA_NOTE_ID_INDEX_SQL = private static final String CREATE_DATA_NOTE_ID_INDEX_SQL =
"CREATE INDEX IF NOT EXISTS note_id_index ON " + "CREATE INDEX IF NOT EXISTS note_id_index ON " +
TABLE.DATA + "(" + DataColumns.NOTE_ID + ");"; TABLE.DATA + "(" + DataColumns.NOTE_ID + ");";
//以下是各种 SQLite 数据库的触发器,用于更新数据库
/** /**
* Increase folder's note count when move note to the folder * Increase folder's note count when move note to the folder
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_update "+ "CREATE TRIGGER increase_folder_count_on_update "+
@ -113,7 +95,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Decrease folder's note count when move note from folder * Decrease folder's note count when move note from folder
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_update " + "CREATE TRIGGER decrease_folder_count_on_update " +
@ -126,7 +108,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Increase folder's note count when insert new note to the folder * Increase folder's note count when insert new note to the folder
*/ */
private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER = private static final String NOTE_INCREASE_FOLDER_COUNT_ON_INSERT_TRIGGER =
"CREATE TRIGGER increase_folder_count_on_insert " + "CREATE TRIGGER increase_folder_count_on_insert " +
@ -138,7 +120,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Decrease folder's note count when delete note from the folder * Decrease folder's note count when delete note from the folder
*/ */
private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER = private static final String NOTE_DECREASE_FOLDER_COUNT_ON_DELETE_TRIGGER =
"CREATE TRIGGER decrease_folder_count_on_delete " + "CREATE TRIGGER decrease_folder_count_on_delete " +
@ -151,7 +133,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when insert data with type {@link DataConstants#NOTE}DataConstants * Update note's content when insert data with type {@link DataConstants#NOTE}
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_INSERT_TRIGGER =
"CREATE TRIGGER update_note_content_on_insert " + "CREATE TRIGGER update_note_content_on_insert " +
@ -164,7 +146,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has changedDataConstants * Update note's content when data with {@link DataConstants#NOTE} type has changed
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_UPDATE_TRIGGER =
"CREATE TRIGGER update_note_content_on_update " + "CREATE TRIGGER update_note_content_on_update " +
@ -177,7 +159,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Update note's content when data with {@link DataConstants#NOTE} type has deletedDataConstants * Update note's content when data with {@link DataConstants#NOTE} type has deleted
*/ */
private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER = private static final String DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER =
"CREATE TRIGGER update_note_content_on_delete " + "CREATE TRIGGER update_note_content_on_delete " +
@ -190,7 +172,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Delete datas belong to note which has been deleted * Delete datas belong to note which has been deleted
*/ */
private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER = private static final String NOTE_DELETE_DATA_ON_DELETE_TRIGGER =
"CREATE TRIGGER delete_data_on_delete " + "CREATE TRIGGER delete_data_on_delete " +
@ -201,7 +183,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Delete notes belong to folder which has been deleted * Delete notes belong to folder which has been deleted
*/ */
private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER = private static final String FOLDER_DELETE_NOTES_ON_DELETE_TRIGGER =
"CREATE TRIGGER folder_delete_notes_on_delete " + "CREATE TRIGGER folder_delete_notes_on_delete " +
@ -212,7 +194,7 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" END"; " END";
/** /**
* Move notes belong to folder which has been moved to trash folder * Move notes belong to folder which has been moved to trash folder
*/ */
private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER = private static final String FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER =
"CREATE TRIGGER folder_move_notes_on_trash " + "CREATE TRIGGER folder_move_notes_on_trash " +
@ -224,23 +206,10 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
" WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" + " WHERE " + NoteColumns.PARENT_ID + "=old." + NoteColumns.ID + ";" +
" END"; " END";
/**
* NotesDatabaseHelperSQLite
*
* Context context访
* String DB_NAME
* CursorFactory factorynull使
* int DB_VERSION
*/
public NotesDatabaseHelper(Context context) { public NotesDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION); super(context, DB_NAME, null, DB_VERSION);
} }
/**
*
* SQLCREATE_NOTE_TABLE_SQLreCreateNoteTableTriggers
* createSystemFolder使Log.d
*/
public void createNoteTable(SQLiteDatabase db) { public void createNoteTable(SQLiteDatabase db) {
db.execSQL(CREATE_NOTE_TABLE_SQL); db.execSQL(CREATE_NOTE_TABLE_SQL);
reCreateNoteTableTriggers(db); reCreateNoteTableTriggers(db);
@ -248,12 +217,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "note table has been created"); Log.d(TAG, "note table has been created");
} }
/**
*
* 使DROP TRIGGER使CREATE TRIGGER
* 使便
* @param db
*/
private void reCreateNoteTableTriggers(SQLiteDatabase db) { private void reCreateNoteTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS increase_folder_count_on_update");
db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update"); db.execSQL("DROP TRIGGER IF EXISTS decrease_folder_count_on_update");
@ -272,25 +235,18 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER); db.execSQL(FOLDER_MOVE_NOTES_ON_TRASH_TRIGGER);
} }
/**
*
* ContentValuesIDTYPE
* 使SQLiteDatabaseinsert
* IDNotes
*
*/
private void createSystemFolder(SQLiteDatabase db) { private void createSystemFolder(SQLiteDatabase db) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
/** /**
* call record folder for call notes * call record foler for call notes
*/ */
values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER); values.put(NoteColumns.ID, Notes.ID_CALL_RECORD_FOLDER);
values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM); values.put(NoteColumns.TYPE, Notes.TYPE_SYSTEM);
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
/** /**
* root folder which is default foldermo * root folder which is default folder
*/ */
values.clear(); values.clear();
values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER); values.put(NoteColumns.ID, Notes.ID_ROOT_FOLDER);
@ -314,14 +270,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.insert(TABLE.NOTE, null, values); db.insert(TABLE.NOTE, null, values);
} }
/**
*
* SQLiteDatabaseSQL
* CREATE_DATA_TABLE_SQLSQL
* recreatedatabletriggers
* CREATE_DATA_NOTE_ID_INDEX_SQLSQLNOTE ID
* NOTE IDNOTE
*/
public void createDataTable(SQLiteDatabase db) { public void createDataTable(SQLiteDatabase db) {
db.execSQL(CREATE_DATA_TABLE_SQL); db.execSQL(CREATE_DATA_TABLE_SQL);
reCreateDataTableTriggers(db); reCreateDataTableTriggers(db);
@ -329,13 +277,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
Log.d(TAG, "data table has been created"); Log.d(TAG, "data table has been created");
} }
/**
* Recreatedatabletriggersinsertupdatedelete
* 使
* update_note_content_on_insert_content_on_update_note_content_on_delete
* data_update_note_content_on_insert_trigger data_update_trigger data_update_note_content_on_delete_trigger
* snippet
*/
private void reCreateDataTableTriggers(SQLiteDatabase db) { private void reCreateDataTableTriggers(SQLiteDatabase db) {
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_insert");
db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update"); db.execSQL("DROP TRIGGER IF EXISTS update_note_content_on_update");
@ -346,12 +287,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER); db.execSQL(DATA_UPDATE_NOTE_CONTENT_ON_DELETE_TRIGGER);
} }
/**
* NotesDatabaseHelper
* ContextNotesDatabaseHelpernull
* nullNotesDatabaseHelper
* 线访
*/
static synchronized NotesDatabaseHelper getInstance(Context context) { static synchronized NotesDatabaseHelper getInstance(Context context) {
if (mInstance == null) { if (mInstance == null) {
mInstance = new NotesDatabaseHelper(context); mInstance = new NotesDatabaseHelper(context);
@ -359,18 +294,6 @@ public class NotesDatabaseHelper extends SQLiteOpenHelper {
return mInstance; return mInstance;
} }
/**
* NotesDatabaseHelperonCreateonUpgrade
* onCreate
* 使createNoteTablecreateDataTableNoteData
* onUpgrade
*
* 12Note使createNoteTablecreateDataTable
* 23使Notegtask_id
* 34
* reCreateNoteTableTriggersrecreateDatabletriggers
* IllegalStateException
*/
@Override @Override
public void onCreate(SQLiteDatabase db) { public void onCreate(SQLiteDatabase db) {
createNoteTable(db); createNoteTable(db);

@ -35,20 +35,20 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.NotesDatabaseHelper.TABLE; import net.micode.notes.data.NotesDatabaseHelper.TABLE;
public class NotesProvider extends ContentProvider {//定义NotesProvider类它继承自ContentProvider类 public class NotesProvider extends ContentProvider {
private static final UriMatcher mMatcher;//声明UriMatcher实例 private static final UriMatcher mMatcher;
private NotesDatabaseHelper mHelper;//声明NotesDatabaseHelper实例用于匹配Uri以确定请求的类型例如是否是请求特定的数据项或者是否是搜索建议请求。 private NotesDatabaseHelper mHelper;
private static final String TAG = "NotesProvider"; private static final String TAG = "NotesProvider";
private static final int URI_NOTE = 1;//代表笔记数据的URI private static final int URI_NOTE = 1;
private static final int URI_NOTE_ITEM = 2;//代表单个笔记数据的URI private static final int URI_NOTE_ITEM = 2;
private static final int URI_DATA = 3;//代表附加数据的URI private static final int URI_DATA = 3;
private static final int URI_DATA_ITEM = 4;//代表单个附加数据的URI private static final int URI_DATA_ITEM = 4;
private static final int URI_SEARCH = 5;//代表搜索请求的URI private static final int URI_SEARCH = 5;
private static final int URI_SEARCH_SUGGEST = 6;//代表搜索建议请求的URI private static final int URI_SEARCH_SUGGEST = 6;
static { static {
mMatcher = new UriMatcher(UriMatcher.NO_MATCH); mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
@ -65,7 +65,6 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
* x'0A' represents the '\n' character in sqlite. For title and content in the search result, * 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. * we will trim '\n' and white space in order to show more information.
*/ */
// 定义将在搜索结果中返回的列
private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + "," private static final String NOTES_SEARCH_PROJECTION = NoteColumns.ID + ","
+ NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + "," + NoteColumns.ID + " AS " + SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA + ","
+ "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + "," + "TRIM(REPLACE(" + NoteColumns.SNIPPET + ", x'0A','')) AS " + SearchManager.SUGGEST_COLUMN_TEXT_1 + ","
@ -73,15 +72,15 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
+ R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + "," + R.drawable.search_result + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1 + ","
+ "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + "," + "'" + Intent.ACTION_VIEW + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_ACTION + ","
+ "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA; + "'" + Notes.TextNote.CONTENT_TYPE + "' AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA;
// 定义将执行以检索搜索结果的搜索查询
private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION private static String NOTES_SNIPPET_SEARCH_QUERY = "SELECT " + NOTES_SEARCH_PROJECTION
+ " FROM " + TABLE.NOTE// 指定要搜索的表 + " FROM " + TABLE.NOTE
+ " WHERE " + NoteColumns.SNIPPET + " LIKE ?"// 指定搜索查询 + " WHERE " + NoteColumns.SNIPPET + " LIKE ?"
+ " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER// 排除在垃圾桶文件夹中的笔记 + " AND " + NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER
+ " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;// 排除非笔记条目 + " AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
@Override @Override
public boolean onCreate() {// 获取数据库帮助类的实例 public boolean onCreate() {
mHelper = NotesDatabaseHelper.getInstance(getContext()); mHelper = NotesDatabaseHelper.getInstance(getContext());
return true; return true;
} }
@ -89,30 +88,30 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
@Override @Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) { String sortOrder) {
Cursor c = null;// 获取可读的数据库实例 Cursor c = null;
SQLiteDatabase db = mHelper.getReadableDatabase(); SQLiteDatabase db = mHelper.getReadableDatabase();
String id = null; String id = null;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE:// 查询所有笔记 case URI_NOTE:
c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null, c = db.query(TABLE.NOTE, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_NOTE_ITEM:// 查询单个笔记 case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id c = db.query(TABLE.NOTE, projection, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_DATA:// 查询所有数据 case URI_DATA:
c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null, c = db.query(TABLE.DATA, projection, selection, selectionArgs, null, null,
sortOrder); sortOrder);
break; break;
case URI_DATA_ITEM: // 查询单个数据 case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); id = uri.getPathSegments().get(1);
c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id c = db.query(TABLE.DATA, projection, DataColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs, null, null, sortOrder); + parseSelection(selection), selectionArgs, null, null, sortOrder);
break; break;
case URI_SEARCH: case URI_SEARCH:
case URI_SEARCH_SUGGEST:// 搜索笔记 case URI_SEARCH_SUGGEST:
if (sortOrder != null || projection != null) { if (sortOrder != null || projection != null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"do not specify sortOrder, selection, selectionArgs, or projection" + "with this query"); "do not specify sortOrder, selection, selectionArgs, or projection" + "with this query");
@ -131,7 +130,7 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
return null; return null;
} }
try {// 搜索所有匹配的笔记 try {
searchString = String.format("%%%s%%", searchString); searchString = String.format("%%%s%%", searchString);
c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY, c = db.rawQuery(NOTES_SNIPPET_SEARCH_QUERY,
new String[] { searchString }); new String[] { searchString });
@ -142,44 +141,44 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (c != null) {// 设置通知URI以便在数据更改时通知观察者 if (c != null) {
c.setNotificationUri(getContext().getContentResolver(), uri); c.setNotificationUri(getContext().getContentResolver(), uri);
} }
return c; return c;
} }
@Override @Override
public Uri insert(Uri uri, ContentValues values) {// 获取可写的 SQLiteDatabase 对象 public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = mHelper.getWritableDatabase();// 初始化三个变量,用于存储 note、data 和插入的记录的 ID SQLiteDatabase db = mHelper.getWritableDatabase();
long dataId = 0, noteId = 0, insertedId = 0;// 根据传入的 Uri 进行匹配 long dataId = 0, noteId = 0, insertedId = 0;
switch (mMatcher.match(uri)) { switch (mMatcher.match(uri)) {
case URI_NOTE:// 向 TABLE.NOTE 表中插入记录,并获取插入的记录的 ID case URI_NOTE:
insertedId = noteId = db.insert(TABLE.NOTE, null, values); insertedId = noteId = db.insert(TABLE.NOTE, null, values);
break; break;
case URI_DATA: case URI_DATA:
if (values.containsKey(DataColumns.NOTE_ID)) {// 如果 ContentValues 包含 DataColumns.NOTE_ID 列 if (values.containsKey(DataColumns.NOTE_ID)) {
noteId = values.getAsLong(DataColumns.NOTE_ID);// 获取 DataColumns.NOTE_ID 列的值 noteId = values.getAsLong(DataColumns.NOTE_ID);
} else { } else {
Log.d(TAG, "Wrong data format without note id:" + values.toString()); Log.d(TAG, "Wrong data format without note id:" + values.toString());
}//打印日志 }
insertedId = dataId = db.insert(TABLE.DATA, null, values);// 向 TABLE.DATA 表中插入记录,并获取插入的记录的 ID insertedId = dataId = db.insert(TABLE.DATA, null, values);
break; break;
default: default:
throw new IllegalArgumentException("Unknown URI " + uri);// 抛出 IllegalArgumentException 异常 throw new IllegalArgumentException("Unknown URI " + uri);
} }
// Notify the note uri // Notify the note uri
if (noteId > 0) { // 如果 noteId 大于 0则通知 content resolver 对应的 Uri 对应的数据已经发生了变化 if (noteId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null); ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), null);
} }
// Notify the data uri // Notify the data uri
if (dataId > 0) {// 如果 dataId 大于 0则通知 content resolver 对应的 Uri 对应的数据已经发生了变化 if (dataId > 0) {
getContext().getContentResolver().notifyChange( getContext().getContentResolver().notifyChange(
ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null); ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), null);
} }
return ContentUris.withAppendedId(uri, insertedId); // 返回插入的记录的 Uri return ContentUris.withAppendedId(uri, insertedId);
} }
@Override @Override
@ -188,62 +187,60 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
String id = null; String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase(); SQLiteDatabase db = mHelper.getWritableDatabase();
boolean deleteData = false; boolean deleteData = false;
switch (mMatcher.match(uri)) {// 根据传入的 Uri 进行匹配 switch (mMatcher.match(uri)) {
case URI_NOTE:// 如果匹配到 URI_NOTE case URI_NOTE:
selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";// 组合 selection 条件,以确保删除的是用户笔记,而不是系统文件夹 selection = "(" + selection + ") AND " + NoteColumns.ID + ">0 ";
count = db.delete(TABLE.NOTE, selection, selectionArgs);// 删除 TABLE.NOTE 表中符合条件的记录,并返回删除的数量 count = db.delete(TABLE.NOTE, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: // 如果匹配到 URI_NOTE_ITEM case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);// 获取 Uri 中的 ID id = uri.getPathSegments().get(1);
/** /**
* ID that smaller than 0 is system folder which is not allowed to * ID that smaller than 0 is system folder which is not allowed to
* trash * trash
*/ */
long noteId = Long.valueOf(id); long noteId = Long.valueOf(id);
if (noteId <= 0) { // 如果 ID 小于等于 0则直接跳出 switch 语句 if (noteId <= 0) {
break; break;
} }
count = db.delete(TABLE.NOTE, count = db.delete(TABLE.NOTE,
NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);// 删除 TABLE.NOTE 表中符合条件的记录,并返回删除的数量 NoteColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
break; break;
case URI_DATA:// 如果匹配到 URI_DATA case URI_DATA:
count = db.delete(TABLE.DATA, selection, selectionArgs);// 删除 TABLE.DATA 表中符合条件的记录,并返回删除的数量 count = db.delete(TABLE.DATA, selection, selectionArgs);
deleteData = true; deleteData = true;
break; break;
case URI_DATA_ITEM:// 如果匹配到 URI_DATA_ITEM case URI_DATA_ITEM:
id = uri.getPathSegments().get(1); // 获取 Uri 中的 ID id = uri.getPathSegments().get(1);
count = db.delete(TABLE.DATA, count = db.delete(TABLE.DATA,
DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);// 删除 TABLE.DATA 表中符合条件的记录,并返回删除的数量 DataColumns.ID + "=" + id + parseSelection(selection), selectionArgs);
deleteData = true; deleteData = true;
break; break;
default:// 如果无法匹配到 Uri default:
throw new IllegalArgumentException("Unknown URI " + uri);// 抛出 IllegalArgumentException 异常 throw new IllegalArgumentException("Unknown URI " + uri);
} }
if (count > 0) {// 如果删除的数量大于 0 if (count > 0) {
if (deleteData) { if (deleteData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} // 如果删除的是 TABLE.DATA 表中的记录,则通知 content resolver 对应的 Uri 对应的笔记数据已经发生了变化 }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
} }
return count;// 返回删除的数量 return count;
} }
@Override @Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count = 0;// 受影响的行数 int count = 0;
String id = null;// 被更新的笔记或数据项的ID String id = null;
SQLiteDatabase db = mHelper.getWritableDatabase();// 获取可写数据库 SQLiteDatabase db = mHelper.getWritableDatabase();
boolean updateData = false;// 是否更新数据项 boolean updateData = false;
switch (mMatcher.match(uri)) {
switch (mMatcher.match(uri)) {// 使用 switch 语句处理不同类型的 URI
case URI_NOTE: case URI_NOTE:
increaseNoteVersion(-1, selection, selectionArgs);// 在更新前增加所有受影响的笔记的版本号 increaseNoteVersion(-1, selection, selectionArgs);
count = db.update(TABLE.NOTE, values, selection, selectionArgs);// 更新数据库中的行并获取受影响的行数 count = db.update(TABLE.NOTE, values, selection, selectionArgs);
break; break;
case URI_NOTE_ITEM: case URI_NOTE_ITEM:
id = uri.getPathSegments().get(1);// 在更新前增加笔记的版本号 id = uri.getPathSegments().get(1);
increaseNoteVersion(Long.valueOf(id), selection, selectionArgs); // 更新数据库中的行并获取受影响的行数 increaseNoteVersion(Long.valueOf(id), selection, selectionArgs);
count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id count = db.update(TABLE.NOTE, values, NoteColumns.ID + "=" + id
+ parseSelection(selection), selectionArgs); + parseSelection(selection), selectionArgs);
break; break;
@ -260,20 +257,20 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
default: default:
throw new IllegalArgumentException("Unknown URI " + uri); throw new IllegalArgumentException("Unknown URI " + uri);
} }
// 如果有行被更新,通知已注册的 ContentObserver
if (count > 0) { if (count > 0) {
if (updateData) { if (updateData) {
getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null); getContext().getContentResolver().notifyChange(Notes.CONTENT_NOTE_URI, null);
} }
getContext().getContentResolver().notifyChange(uri, null); getContext().getContentResolver().notifyChange(uri, null);
} }
return count; // 返回受影响的行数 return count;
} }
// 辅助方法,如果传递了 selection 参数,则将其添加到 SQL 查询中
private String parseSelection(String selection) { private String parseSelection(String selection) {
return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""); return (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : "");
} }
// 辅助方法,在更新笔记之前增加其版本号
private void increaseNoteVersion(long id, String selection, String[] selectionArgs) { private void increaseNoteVersion(long id, String selection, String[] selectionArgs) {
StringBuilder sql = new StringBuilder(120); StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE "); sql.append("UPDATE ");
@ -281,7 +278,7 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
sql.append(" SET "); sql.append(" SET ");
sql.append(NoteColumns.VERSION); sql.append(NoteColumns.VERSION);
sql.append("=" + NoteColumns.VERSION + "+1 "); sql.append("=" + NoteColumns.VERSION + "+1 ");
// 如果传递了 ID 或 selection 参数,则将其添加到 SQL 查询中
if (id > 0 || !TextUtils.isEmpty(selection)) { if (id > 0 || !TextUtils.isEmpty(selection)) {
sql.append(" WHERE "); sql.append(" WHERE ");
} }
@ -296,12 +293,12 @@ public class NotesProvider extends ContentProvider {//定义NotesProvider类
sql.append(selectString); sql.append(selectString);
} }
mHelper.getWritableDatabase().execSQL(sql.toString());// 执行 SQL 查询以更新笔记的版本号 mHelper.getWritableDatabase().execSQL(sql.toString());
} }
@Override @Override
public String getType(Uri uri) { public String getType(Uri uri) {
// TODO Auto-generated method stub这是一个待办事项,需要根据 ContentProvider需求添加适当的 MIME类型。 // TODO Auto-generated method stub
return null; return null;
} }

@ -0,0 +1,253 @@
/*
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.micode.notes.model;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.CallNote;
import net.micode.notes.data.Notes.DataColumns;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import java.util.ArrayList;
public class Note {
private ContentValues mNoteDiffValues;
private NoteData mNoteData;
private static final String TAG = "Note";
/**
* Create a new note id for adding a new note to databases
*/
public static synchronized long getNewNoteId(Context context, long folderId) {
// Create a new note in the database
ContentValues values = new ContentValues();
long createdTime = System.currentTimeMillis();
values.put(NoteColumns.CREATED_DATE, createdTime);
values.put(NoteColumns.MODIFIED_DATE, createdTime);
values.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
values.put(NoteColumns.LOCAL_MODIFIED, 1);
values.put(NoteColumns.PARENT_ID, folderId);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_NOTE_URI, values);
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);
}
return noteId;
}
public Note() {
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());
}
public void setTextData(String key, String value) {
mNoteData.setTextData(key, value);
}
public void setTextDataId(long id) {
mNoteData.setTextDataId(id);
}
public long getTextDataId() {
return mNoteData.mTextDataId;
}
public void setCallDataId(long id) {
mNoteData.setCallDataId(id);
}
public void setCallData(String key, String value) {
mNoteData.setCallData(key, value);
}
public boolean 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;
}
/**
* In theory, once data changed, the note should be updated on {@link NoteColumns#LOCAL_MODIFIED} and
* {@link NoteColumns#MODIFIED_DATE}. For data safety, though update note fails, we also update the
* note data info
*/
if (context.getContentResolver().update(
ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), mNoteDiffValues, null,
null) == 0) {
Log.e(TAG, "Update note error, should not happen");
// Do not return, fall through
}
mNoteDiffValues.clear();
if (mNoteData.isLocalModified()
&& (mNoteData.pushIntoContentResolver(context, noteId) == null)) {
return false;
}
return true;
}
private class NoteData {
private long mTextDataId;
private ContentValues mTextDataValues;
private long mCallDataId;
private ContentValues mCallDataValues;
private static final String TAG = "NoteData";
public NoteData() {
mTextDataValues = new ContentValues();
mCallDataValues = new ContentValues();
mTextDataId = 0;
mCallDataId = 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;
}
void setCallDataId(long id) {
if (id <= 0) {
throw new IllegalArgumentException("Call data id should larger than 0");
}
mCallDataId = id;
}
void setCallData(String key, String value) {
mCallDataValues.put(key, value);
mNoteDiffValues.put(NoteColumns.LOCAL_MODIFIED, 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());
}
Uri pushIntoContentResolver(Context context, long noteId) {
/**
* Check for safety
*/
if (noteId <= 0) {
throw new IllegalArgumentException("Wrong note id:" + noteId);
}
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = null;
if(mTextDataValues.size() > 0) {
mTextDataValues.put(DataColumns.NOTE_ID, noteId);
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)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new text data fail with noteId" + noteId);
mTextDataValues.clear();
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mTextDataId));
builder.withValues(mTextDataValues);
operationList.add(builder.build());
}
mTextDataValues.clear();
}
if(mCallDataValues.size() > 0) {
mCallDataValues.put(DataColumns.NOTE_ID, noteId);
if (mCallDataId == 0) {
mCallDataValues.put(DataColumns.MIME_TYPE, CallNote.CONTENT_ITEM_TYPE);
Uri uri = context.getContentResolver().insert(Notes.CONTENT_DATA_URI,
mCallDataValues);
try {
setCallDataId(Long.valueOf(uri.getPathSegments().get(1)));
} catch (NumberFormatException e) {
Log.e(TAG, "Insert new call data fail with noteId" + noteId);
mCallDataValues.clear();
return null;
}
} else {
builder = ContentProviderOperation.newUpdate(ContentUris.withAppendedId(
Notes.CONTENT_DATA_URI, mCallDataId));
builder.withValues(mCallDataValues);
operationList.add(builder.build());
}
mCallDataValues.clear();
}
if (operationList.size() > 0) {
try {
ContentProviderResult[] results = context.getContentResolver().applyBatch(
Notes.AUTHORITY, operationList);
return (results == null || results.length == 0 || results[0] == null) ? null
: ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId);
} catch (RemoteException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
} catch (OperationApplicationException e) {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
return null;
}
}
return null;
}
}
}

@ -33,39 +33,39 @@ import net.micode.notes.tool.ResourceParser.NoteBgResources;
public class WorkingNote { public class WorkingNote {
// Note for the working note(工作笔记类) // Note for the working note
private Note mNote;// 笔记 private Note mNote;
// Note Id/笔记ID // Note Id
private long mNoteId; private long mNoteId;
// Note content笔记内容 // Note content
private String mContent; private String mContent;
// Note mode笔记模式 // Note mode
private int mMode; private int mMode;
private long mAlertDate;// 提醒日期 private long mAlertDate;
private long mModifiedDate;// 修改日期 private long mModifiedDate;
private int mBgColorId;// 背景颜色ID private int mBgColorId;
private int mWidgetId;// 小部件ID private int mWidgetId;
private int mWidgetType;// 小部件类型 private int mWidgetType;
private long mFolderId;// 文件夹ID private long mFolderId;
private Context mContext;// 上下文 private Context mContext;
private static final String TAG = "WorkingNote";// 标签 private static final String TAG = "WorkingNote";
private boolean mIsDeleted;// 是否已删除 private boolean mIsDeleted;
private NoteSettingChangedListener mNoteSettingStatusListener;// 笔记设置改变监听器 private NoteSettingChangedListener mNoteSettingStatusListener;
public static final String[] DATA_PROJECTION = new String[] {// 查询数据时需要返回的列名数组 public static final String[] DATA_PROJECTION = new String[] {
DataColumns.ID,// ID列 DataColumns.ID,
DataColumns.CONTENT, // 内容列 DataColumns.CONTENT,
DataColumns.MIME_TYPE, // MIME类型列 DataColumns.MIME_TYPE,
DataColumns.DATA1, DataColumns.DATA1,
DataColumns.DATA2, DataColumns.DATA2,
DataColumns.DATA3, DataColumns.DATA3,

@ -47,28 +47,23 @@ public class BackupUtils {
} }
return sInstance; return sInstance;
} }
/* `TAG` String tag
`sInstance`
`getInstance()` `Context` `BackupUtils`
使线
*/
/** /**
* Following states are signs to represents backup or restore * Following states are signs to represents backup or restore
* status * status
*/ */
// Currently, the sdcard is not mounted // Currently, the sdcard is not mounted
public static final int STATE_SD_CARD_UNMOUONTED = 0; public static final int STATE_SD_CARD_UNMOUONTED = 0;
// The backup file not exist(备份文件不存在) // The backup file not exist
public static final int STATE_BACKUP_FILE_NOT_EXIST = 1; public static final int STATE_BACKUP_FILE_NOT_EXIST = 1;
// The data is not well formated, may be changed by other programs(数据格式不正确可能被其他程序更改) // The data is not well formated, may be changed by other programs
public static final int STATE_DATA_DESTROIED = 2; public static final int STATE_DATA_DESTROIED = 2;
// Some run-time exception which causes restore or backup fails(导致备份或还原失败的默写运行异常) // Some run-time exception which causes restore or backup fails
public static final int STATE_SYSTEM_ERROR = 3; public static final int STATE_SYSTEM_ERROR = 3;
// Backup or restore success(备份或还原成功) // Backup or restore success
public static final int STATE_SUCCESS = 4; public static final int STATE_SUCCESS = 4;
private TextExport mTextExport;//实例化对象 private TextExport mTextExport;
private BackupUtils(Context context) { private BackupUtils(Context context) {
mTextExport = new TextExport(context); mTextExport = new TextExport(context);
@ -80,15 +75,15 @@ public class BackupUtils {
public int exportToText() { public int exportToText() {
return mTextExport.exportToText(); return mTextExport.exportToText();
}//这是一个 public 方法,用于将数据导出为文本,并返回一个整数值。 }
public String getExportedTextFileName() { public String getExportedTextFileName() {
return mTextExport.mFileName; return mTextExport.mFileName;
}//这是一个 public 方法,用于获取导出的文本文件名。 }
public String getExportedTextFileDir() { public String getExportedTextFileDir() {
return mTextExport.mFileDirectory; return mTextExport.mFileDirectory;
}//这是一个 public 方法,用于获取导出的文本文件所在的目录。 }
private static class TextExport { private static class TextExport {
private static final String[] NOTE_PROJECTION = { private static final String[] NOTE_PROJECTION = {
@ -96,8 +91,7 @@ public class BackupUtils {
NoteColumns.MODIFIED_DATE, NoteColumns.MODIFIED_DATE,
NoteColumns.SNIPPET, NoteColumns.SNIPPET,
NoteColumns.TYPE NoteColumns.TYPE
};//这是一个私有的静态内部类,用于完成数据导出的操作。 };
private static final int NOTE_COLUMN_ID = 0; private static final int NOTE_COLUMN_ID = 0;
@ -121,37 +115,32 @@ public class BackupUtils {
private static final int DATA_COLUMN_CALL_DATE = 2; private static final int DATA_COLUMN_CALL_DATE = 2;
private static final int DATA_COLUMN_PHONE_NUMBER = 4; private static final int DATA_COLUMN_PHONE_NUMBER = 4;
// 定义了多个常量,用于操作笔记和数据的列索引
private final String [] TEXT_FORMAT; private final String [] TEXT_FORMAT;
private static final int FORMAT_FOLDER_NAME = 0; private static final int FORMAT_FOLDER_NAME = 0;
private static final int FORMAT_NOTE_DATE = 1; private static final int FORMAT_NOTE_DATE = 1;
private static final int FORMAT_NOTE_CONTENT = 2; private static final int FORMAT_NOTE_CONTENT = 2;
// 定义了一个字符串数组 TEXT_FORMAT其中存储了导出笔记时的文件格式
private Context mContext; private Context mContext;
private String mFileName; private String mFileName;
private String mFileDirectory; private String mFileDirectory;
// 定义了 Context mContext、String mFileName、String mFileDirectory 三个变量
// mContext 存储了当前上下文mFileName 存储了文件名mFileDirectory 存储了文件夹路径
public TextExport(Context context) { public TextExport(Context context) {
TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note); TEXT_FORMAT = context.getResources().getStringArray(R.array.format_for_exported_note);
mContext = context; mContext = context;
mFileName = ""; mFileName = "";
mFileDirectory = "";// 构造函数,初始化了 TEXT_FORMAT、mContext、mFileName 和 mFileDirectory mFileDirectory = "";
} }
private String getFormat(int id) { private String getFormat(int id) {
return TEXT_FORMAT[id]; return TEXT_FORMAT[id];
}// getFormat 方法返回 TEXT_FORMAT 数组中指定 id 的字符串 }
/** /**
* Export the folder identified by folder id to text * Export the folder identified by folder id to text
* (exportFolderToText )
*/ */
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,
NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] { NOTE_PROJECTION, NoteColumns.PARENT_ID + "=?", new String[] {
folderId folderId
@ -160,11 +149,11 @@ public class BackupUtils {
if (notesCursor != null) { if (notesCursor != null) {
if (notesCursor.moveToFirst()) { if (notesCursor.moveToFirst()) {
do { do {
// Print note's last modified date // 输出笔记的最后修改日期 // Print note's last modified date
ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format( ps.println(String.format(getFormat(FORMAT_NOTE_DATE), DateFormat.format(
mContext.getString(R.string.format_datetime_mdhm), mContext.getString(R.string.format_datetime_mdhm),
notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE)))); notesCursor.getLong(NOTE_COLUMN_MODIFIED_DATE))));
// Query data belong to this note // 查询属于该笔记的数据 // Query data belong to this note
String noteId = notesCursor.getString(NOTE_COLUMN_ID); String noteId = notesCursor.getString(NOTE_COLUMN_ID);
exportNoteToText(noteId, ps); exportNoteToText(noteId, ps);
} while (notesCursor.moveToNext()); } while (notesCursor.moveToNext());
@ -180,14 +169,14 @@ public class BackupUtils {
Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI, Cursor dataCursor = mContext.getContentResolver().query(Notes.CONTENT_DATA_URI,
DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] { DATA_PROJECTION, DataColumns.NOTE_ID + "=?", new String[] {
noteId noteId
}, null);// exportNoteToText 方法用于将指定笔记的数据导出到文本中 }, null);
if (dataCursor != null) { if (dataCursor != null) {
if (dataCursor.moveToFirst()) { if (dataCursor.moveToFirst()) {
do { do {
String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE); String mimeType = dataCursor.getString(DATA_COLUMN_MIME_TYPE);
if (DataConstants.CALL_NOTE.equals(mimeType)) { if (DataConstants.CALL_NOTE.equals(mimeType)) {
// Print phone number // 输出电话号码 // Print phone number
String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER); String phoneNumber = dataCursor.getString(DATA_COLUMN_PHONE_NUMBER);
long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE); long callDate = dataCursor.getLong(DATA_COLUMN_CALL_DATE);
String location = dataCursor.getString(DATA_COLUMN_CONTENT); String location = dataCursor.getString(DATA_COLUMN_CONTENT);
@ -196,11 +185,11 @@ public class BackupUtils {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
phoneNumber)); phoneNumber));
} }
// Print call date// 输出通话日期 // Print call date
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), DateFormat
.format(mContext.getString(R.string.format_datetime_mdhm), .format(mContext.getString(R.string.format_datetime_mdhm),
callDate))); callDate)));
// Print call attachment location // 输出通话附件位置 // Print call attachment location
if (!TextUtils.isEmpty(location)) { if (!TextUtils.isEmpty(location)) {
ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT), ps.println(String.format(getFormat(FORMAT_NOTE_CONTENT),
location)); location));
@ -216,7 +205,7 @@ public class BackupUtils {
} }
dataCursor.close(); dataCursor.close();
} }
// print a line separator between note// 在导出每个笔记后输出一个分隔符 // print a line separator between note
try { try {
ps.write(new byte[] { ps.write(new byte[] {
Character.LINE_SEPARATOR, Character.LETTER_NUMBER Character.LINE_SEPARATOR, Character.LETTER_NUMBER
@ -233,20 +222,14 @@ public class BackupUtils {
if (!externalStorageAvailable()) { if (!externalStorageAvailable()) {
Log.d(TAG, "Media was not mounted"); Log.d(TAG, "Media was not mounted");
return STATE_SD_CARD_UNMOUONTED; return STATE_SD_CARD_UNMOUONTED;
}/*PrintStream使JavabyteCharacter.LINE_SEPARATORCharacter.LETTER_NUMBER }
Character.LINE_SEPARATORWindows"\r\n"Unix/Linux"\n"
Character.LETTER_NUMBER
bytePrintStream便IOExceptionLogcat*/
PrintStream ps = getExportToTextPrintStream(); PrintStream ps = getExportToTextPrintStream();
if (ps == null) { if (ps == null) {
Log.e(TAG, "get print stream error"); Log.e(TAG, "get print stream error");
return STATE_SYSTEM_ERROR; return STATE_SYSTEM_ERROR;
}//这段代码中的 getExportToTextPrintStream() 是一个自定义方法,它返回一个 PrintStream 对象,该对象用于将笔记数据导出到文本文件中 }
// 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,
@ -272,11 +255,7 @@ public class BackupUtils {
} while (folderCursor.moveToNext()); } while (folderCursor.moveToNext());
} }
folderCursor.close(); folderCursor.close();
}/* }
ContentResolver query() Call Record Cursor folderCursor
folderCursor ID ps Call Record 使*/
// Export notes in root's folder // Export notes in root's folder
Cursor noteCursor = mContext.getContentResolver().query( Cursor noteCursor = mContext.getContentResolver().query(
@ -301,13 +280,7 @@ public class BackupUtils {
ps.close(); ps.close();
return STATE_SUCCESS; return STATE_SUCCESS;
}/* }
ContentResolver query() Cursor noteCursor
noteCursor ps exportNoteToText() ps
ps STATE_SUCCESS noteCursor */
/** /**
* Get a print stream pointed to the file {@generateExportedTextFile} * Get a print stream pointed to the file {@generateExportedTextFile}
@ -334,15 +307,7 @@ public class BackupUtils {
} }
return ps; return ps;
} }
}/* PrintStream }
generateFileMountedOnSDcard() File file
file nullLogcat "create file to exported failed" null
file FileOutputStream fos PrintStream PrintStream ps
ps PrintStream FileNotFoundException NullPointerException null*/
/** /**
* Generate the text file to store imported data * Generate the text file to store imported data
@ -374,14 +339,6 @@ public class BackupUtils {
return null; return null;
} }
}/* }
filePathResId StringBuilder sb
File filedir mkdir()
使 fileNameFormatResId sb File file
file filedir file SecurityException IOException null*/

@ -36,7 +36,7 @@ import java.util.HashSet;
public class DataUtils { public class DataUtils {
public static final String TAG = "DataUtils";//定义了一个Java常量变量名为TAG 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");
@ -70,13 +70,7 @@ public class DataUtils {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} }
return false; return false;
}/*ContentResolverLongHashSet }
idstrueids0true
ids0idsNotes.ID_ROOT_FOLDERContentProviderOperation使ContentProviderOperation.newDelete()operationList
使ContentResolver.applyBatch()truefalseRemoteExceptionOperationApplicationExceptionfalse*/
public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) { public static void moveNoteToFoler(ContentResolver resolver, long id, long srcFolderId, long desFolderId) {
ContentValues values = new ContentValues(); ContentValues values = new ContentValues();
@ -84,11 +78,7 @@ public class DataUtils {
values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId); values.put(NoteColumns.ORIGIN_PARENT_ID, srcFolderId);
values.put(NoteColumns.LOCAL_MODIFIED, 1); values.put(NoteColumns.LOCAL_MODIFIED, 1);
resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null); resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
}/*ContentResolverlongidlongsrcFolderIdlongdesFolderId }
ContentValuesNoteColumns.PARENT_IDdesFolderIdNoteColumns.ORIGIN_PARENT_IDsrcFolderIdNoteColumns.LOCAL_MODIFIED1
ContentResolver.update()URIURIContentUris.withAppendedId()Notes.CONTENT_NOTE_URIidContentValuesnull*/
public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids, public static boolean batchMoveToFolder(ContentResolver resolver, HashSet<Long> ids,
long folderId) { long folderId) {
@ -119,13 +109,7 @@ public class DataUtils {
Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage())); Log.e(TAG, String.format("%s: %s", e.toString(), e.getMessage()));
} }
return false; return false;
}/*ContentResolverLongHashSetidsLongfolderId }
idstrue
idsidsContentProviderOperation使ContentProviderOperation.newUpdate()NoteColumns.PARENT_IDfolderIdNoteColumns.LOCAL_MODIFIED1operationList
使ContentResolver.applyBatch()truefalseRemoteExceptionOperationApplicationExceptionfalse*/
/** /**
* Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}} * Get the all folder count except system folders {@link Notes#TYPE_SYSTEM}}
@ -150,13 +134,7 @@ public class DataUtils {
} }
} }
return count; return count;
}/*ContentResolver }
Cursor使ContentResolver.query()Notes.TYPE_FOLDERCOUNT(*)
CursorCursornull使getInt(0)IndexOutOfBoundsExceptionCursor
*/
public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) { public static boolean visibleInNoteDatabase(ContentResolver resolver, long noteId, int type) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
@ -173,11 +151,7 @@ public class DataUtils {
cursor.close(); cursor.close();
} }
return exist; return exist;
}/*ContentResolverlongnoteIdinttype }
Cursor使ContentResolver.query()type
existtrueCursorexist*/
public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) { public static boolean existInNoteDatabase(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, noteId),
@ -191,11 +165,7 @@ public class DataUtils {
cursor.close(); cursor.close();
} }
return exist; return exist;
}/*ContentResolverlongnoteId }
Cursor使ContentResolver.query()IDnoteId
existtrueCursorexist*/
public static boolean existInDataDatabase(ContentResolver resolver, long dataId) { public static boolean existInDataDatabase(ContentResolver resolver, long dataId) {
Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId), Cursor cursor = resolver.query(ContentUris.withAppendedId(Notes.CONTENT_DATA_URI, dataId),
@ -209,11 +179,7 @@ public class DataUtils {
cursor.close(); cursor.close();
} }
return exist; return exist;
}/*ContentResolverlongdataId }
Cursor使ContentResolver.query()IDdataId
existtrueCursorexist*/
public static boolean checkVisibleFolderName(ContentResolver resolver, String name) { public static boolean checkVisibleFolderName(ContentResolver resolver, String name) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, null,
@ -229,11 +195,7 @@ public class DataUtils {
cursor.close(); cursor.close();
} }
return exist; return exist;
}/*ContentResolverStringname }
Cursor使ContentResolver.query()Notes.TYPE_FOLDERNoteColumns.PARENT_ID <> Notes.ID_TRASH_FOLERNoteColumns.SNIPPET
existtrueCursorexist*/
public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) { public static HashSet<AppWidgetAttribute> getFolderNoteWidget(ContentResolver resolver, long folderId) {
Cursor c = resolver.query(Notes.CONTENT_NOTE_URI, Cursor c = resolver.query(Notes.CONTENT_NOTE_URI,
@ -260,13 +222,7 @@ public class DataUtils {
c.close(); c.close();
} }
return set; return set;
}/*ContentResolverlongfolderIdID }
Cursor使ContentResolver.query()IDfolderIdID
HashSetHashSet<AppWidgetAttribute>IDHashSetnull
CursorHashSetID*/
public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) { public static String getCallNumberByNoteId(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
@ -285,13 +241,7 @@ public class DataUtils {
} }
} }
return ""; return "";
}/*ContentResolverlongnoteIdID }
Cursor使ContentResolver.query()IDnoteIdMIMECallNote.CONTENT_ITEM_TYPE
Cursor*/
public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) { public static long getNoteIdByPhoneNumberAndCallDate(ContentResolver resolver, String phoneNumber, long callDate) {
Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI, Cursor cursor = resolver.query(Notes.CONTENT_DATA_URI,
@ -312,13 +262,7 @@ public class DataUtils {
cursor.close(); cursor.close();
} }
return 0; return 0;
}/*ContentResolverStringphoneNumberlongcallDateID }
Cursor使ContentResolver.query()callDateMIMECallNote.CONTENT_ITEM_TYPEphoneNumberID
ID0
CursorID0*/
public static String getSnippetById(ContentResolver resolver, long noteId) { public static String getSnippetById(ContentResolver resolver, long noteId) {
Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI, Cursor cursor = resolver.query(Notes.CONTENT_NOTE_URI,
@ -336,11 +280,7 @@ public class DataUtils {
return snippet; return snippet;
} }
throw new IllegalArgumentException("Note is not found with id: " + noteId); throw new IllegalArgumentException("Note is not found with id: " + noteId);
}/*ContentResolverlongnoteIdIDsnippet }
Cursor使ContentResolver.query()IDnoteId
snippetCursorsnippetIllegalArgumentExceptionNote is not found with id: noteId*/
public static String getFormattedSnippet(String snippet) { public static String getFormattedSnippet(String snippet) {
if (snippet != null) { if (snippet != null) {
@ -352,8 +292,4 @@ public class DataUtils {
} }
return snippet; return snippet;
} }
}/*Stringsnippetsnippet便 }
snippet使String.trim()snippet使String.indexOf()snippet使String.substring()snippetsnippetsnippet
snippet*/

@ -18,95 +18,96 @@ package net.micode.notes.tool;
public class GTaskStringUtils { public class GTaskStringUtils {
public final static String GTASK_JSON_ACTION_ID = "action_id";// 行动 ID public final static String GTASK_JSON_ACTION_ID = "action_id";
public final static String GTASK_JSON_ACTION_LIST = "action_list";// 行动清单 public final static String GTASK_JSON_ACTION_LIST = "action_list";
public final static String GTASK_JSON_ACTION_TYPE = "action_type";// 行动类型 public final static String GTASK_JSON_ACTION_TYPE = "action_type";
public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";// 创建行动 public final static String GTASK_JSON_ACTION_TYPE_CREATE = "create";
public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";// 获取全部行动 public final static String GTASK_JSON_ACTION_TYPE_GETALL = "get_all";
public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";// 移动行动 public final static String GTASK_JSON_ACTION_TYPE_MOVE = "move";
public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update"; // 更新行动 public final static String GTASK_JSON_ACTION_TYPE_UPDATE = "update";
public final static String GTASK_JSON_CREATOR_ID = "creator_id";// 创建者 ID public final static String GTASK_JSON_CREATOR_ID = "creator_id";
public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";// 子实体 public final static String GTASK_JSON_CHILD_ENTITY = "child_entity";
public final static String GTASK_JSON_CLIENT_VERSION = "client_version";// 客户端版本 public final static String GTASK_JSON_CLIENT_VERSION = "client_version";
public final static String GTASK_JSON_COMPLETED = "completed"; // 完成状态 public final static String GTASK_JSON_COMPLETED = "completed";
public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";// 当前清单 ID public final static String GTASK_JSON_CURRENT_LIST_ID = "current_list_id";
public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id"; // 默认清单 ID public final static String GTASK_JSON_DEFAULT_LIST_ID = "default_list_id";
public final static String GTASK_JSON_DELETED = "deleted";// 删除状态 public final static String GTASK_JSON_DELETED = "deleted";
public final static String GTASK_JSON_DEST_LIST = "dest_list";// 目标清单 public final static String GTASK_JSON_DEST_LIST = "dest_list";
public final static String GTASK_JSON_DEST_PARENT = "dest_parent";// 目标父元素 public final static String GTASK_JSON_DEST_PARENT = "dest_parent";
public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type"; // 目标父元素类型 public final static String GTASK_JSON_DEST_PARENT_TYPE = "dest_parent_type";
public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";// 实体增量 public final static String GTASK_JSON_ENTITY_DELTA = "entity_delta";
public final static String GTASK_JSON_ENTITY_TYPE = "entity_type"; // 实体类型 public final static String GTASK_JSON_ENTITY_TYPE = "entity_type";
public final static String GTASK_JSON_GET_DELETED = "get_deleted"; // 获取删除状态 public final static String GTASK_JSON_GET_DELETED = "get_deleted";
public final static String GTASK_JSON_ID = "id";// ID public final static String GTASK_JSON_ID = "id";
public final static String GTASK_JSON_INDEX = "index";// 索引 public final static String GTASK_JSON_INDEX = "index";
public final static String GTASK_JSON_LAST_MODIFIED = "last_modified"; // 最后修改时间 public final static String GTASK_JSON_LAST_MODIFIED = "last_modified";
public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";// 最新同步点 public final static String GTASK_JSON_LATEST_SYNC_POINT = "latest_sync_point";
public final static String GTASK_JSON_LIST_ID = "list_id"; // 清单 ID public final static String GTASK_JSON_LIST_ID = "list_id";
public final static String GTASK_JSON_LISTS = "lists";// 清单列表 public final static String GTASK_JSON_LISTS = "lists";
public final static String GTASK_JSON_NAME = "name";// 名称
public final static String GTASK_JSON_NEW_ID = "new_id";// 新 ID public final static String GTASK_JSON_NAME = "name";
public final static String GTASK_JSON_NOTES = "notes";// 备注 public final static String GTASK_JSON_NEW_ID = "new_id";
public final static String GTASK_JSON_PARENT_ID = "parent_id";// 父 ID public final static String GTASK_JSON_NOTES = "notes";
public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";// 上一个同级 ID public final static String GTASK_JSON_PARENT_ID = "parent_id";
public final static String GTASK_JSON_RESULTS = "results";// 结果 public final static String GTASK_JSON_PRIOR_SIBLING_ID = "prior_sibling_id";
public final static String GTASK_JSON_SOURCE_LIST = "source_list";// 源清单 public final static String GTASK_JSON_RESULTS = "results";
public final static String GTASK_JSON_TASKS = "tasks";// 任务列表 public final static String GTASK_JSON_SOURCE_LIST = "source_list";
public final static String GTASK_JSON_TYPE = "type";// 类型 public final static String GTASK_JSON_TASKS = "tasks";
public final static String GTASK_JSON_TYPE_GROUP = "GROUP";// 分组类型 public final static String GTASK_JSON_TYPE = "type";
public final static String GTASK_JSON_TYPE_TASK = "TASK";// 任务类型 public final static String GTASK_JSON_TYPE_GROUP = "GROUP";
public final static String GTASK_JSON_USER = "user";// 用户 public final static String GTASK_JSON_TYPE_TASK = "TASK";
public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]"; // MIUI 笔记前缀 public final static String GTASK_JSON_USER = "user";
public final static String FOLDER_DEFAULT = "Default";// 默认文件夹 public final static String MIUI_FOLDER_PREFFIX = "[MIUI_Notes]";
public final static String FOLDER_CALL_NOTE = "Call_Note"; // 通话笔记文件夹 public final static String FOLDER_DEFAULT = "Default";
public final static String FOLDER_META = "METADATA";// 元数据文件夹 public final static String FOLDER_CALL_NOTE = "Call_Note";
public final static String META_HEAD_GTASK_ID = "meta_gid";// GTASK ID 元数据头 public final static String FOLDER_META = "METADATA";
public final static String META_HEAD_NOTE = "meta_note";// 笔记元数据头 public final static String META_HEAD_GTASK_ID = "meta_gid";
public final static String META_HEAD_DATA = "meta_data";// 数据元数据头 public final static String META_HEAD_NOTE = "meta_note";
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";// 元数据笔记名称 public final static String META_HEAD_DATA = "meta_data";
public final static String META_NOTE_NAME = "[META INFO] DON'T UPDATE AND DELETE";
} }

@ -0,0 +1,181 @@
/*
* 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.preference.PreferenceManager;
import net.micode.notes.R;
import net.micode.notes.ui.NotesPreferenceActivity;
public class ResourceParser {
public static final int YELLOW = 0;
public static final int BLUE = 1;
public static final int WHITE = 2;
public static final int GREEN = 3;
public static final int RED = 4;
public static final int BG_DEFAULT_COLOR = YELLOW;
public static final int TEXT_SMALL = 0;
public static final int TEXT_MEDIUM = 1;
public static final int TEXT_LARGE = 2;
public static final int TEXT_SUPER = 3;
public static final int BG_DEFAULT_FONT_SIZE = TEXT_MEDIUM;
public static class NoteBgResources {
private final static int [] BG_EDIT_RESOURCES = new int [] {
R.drawable.edit_yellow,
R.drawable.edit_blue,
R.drawable.edit_white,
R.drawable.edit_green,
R.drawable.edit_red
};
private final static int [] BG_EDIT_TITLE_RESOURCES = new int [] {
R.drawable.edit_title_yellow,
R.drawable.edit_title_blue,
R.drawable.edit_title_white,
R.drawable.edit_title_green,
R.drawable.edit_title_red
};
public static int getNoteBgResource(int id) {
return BG_EDIT_RESOURCES[id];
}
public static int getNoteTitleBgResource(int id) {
return BG_EDIT_TITLE_RESOURCES[id];
}
}
public static int getDefaultBgId(Context context) {
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
NotesPreferenceActivity.PREFERENCE_SET_BG_COLOR_KEY, false)) {
return (int) (Math.random() * NoteBgResources.BG_EDIT_RESOURCES.length);
} else {
return BG_DEFAULT_COLOR;
}
}
public static class NoteItemBgResources {
private final static int [] BG_FIRST_RESOURCES = new int [] {
R.drawable.list_yellow_up,
R.drawable.list_blue_up,
R.drawable.list_white_up,
R.drawable.list_green_up,
R.drawable.list_red_up
};
private final static int [] BG_NORMAL_RESOURCES = new int [] {
R.drawable.list_yellow_middle,
R.drawable.list_blue_middle,
R.drawable.list_white_middle,
R.drawable.list_green_middle,
R.drawable.list_red_middle
};
private final static int [] BG_LAST_RESOURCES = new int [] {
R.drawable.list_yellow_down,
R.drawable.list_blue_down,
R.drawable.list_white_down,
R.drawable.list_green_down,
R.drawable.list_red_down,
};
private final static int [] BG_SINGLE_RESOURCES = new int [] {
R.drawable.list_yellow_single,
R.drawable.list_blue_single,
R.drawable.list_white_single,
R.drawable.list_green_single,
R.drawable.list_red_single
};
public static int getNoteBgFirstRes(int id) {
return BG_FIRST_RESOURCES[id];
}
public static int getNoteBgLastRes(int id) {
return BG_LAST_RESOURCES[id];
}
public static int getNoteBgSingleRes(int id) {
return BG_SINGLE_RESOURCES[id];
}
public static int getNoteBgNormalRes(int id) {
return BG_NORMAL_RESOURCES[id];
}
public static int getFolderBgRes() {
return R.drawable.list_folder;
}
}
public static class WidgetBgResources {
private final static int [] BG_2X_RESOURCES = new int [] {
R.drawable.widget_2x_yellow,
R.drawable.widget_2x_blue,
R.drawable.widget_2x_white,
R.drawable.widget_2x_green,
R.drawable.widget_2x_red,
};
public static int getWidget2xBgResource(int id) {
return BG_2X_RESOURCES[id];
}
private final static int [] BG_4X_RESOURCES = new int [] {
R.drawable.widget_4x_yellow,
R.drawable.widget_4x_blue,
R.drawable.widget_4x_white,
R.drawable.widget_4x_green,
R.drawable.widget_4x_red
};
public static int getWidget4xBgResource(int id) {
return BG_4X_RESOURCES[id];
}
}
public static class TextAppearanceResources {
private final static int [] TEXTAPPEARANCE_RESOURCES = new int [] {
R.style.TextAppearanceNormal,
R.style.TextAppearanceMedium,
R.style.TextAppearanceLarge,
R.style.TextAppearanceSuper
};
public static int getTexAppearanceResource(int id) {
/**
* HACKME: Fix bug of store the resource id in shared preference.
* The id may larger than the length of resources, in this case,
* return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
*/
if (id >= TEXTAPPEARANCE_RESOURCES.length) {
return BG_DEFAULT_FONT_SIZE;
}
return TEXTAPPEARANCE_RESOURCES[id];
}
public static int getResourcesSize() {
return TEXTAPPEARANCE_RESOURCES.length;
}
}
}

@ -48,28 +48,26 @@ import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.gtask.remote.GTaskSyncService;
public class NotesPreferenceActivity extends PreferenceActivity {// 定义了一个常量字符串 PREFERENCE_NAME表示 SharedPreferences 的名称 public class NotesPreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "notes_preferences";// 定义了一个常量字符串 PREFERENCE_SYNC_ACCOUNT_NAME表示同步账户名称的键名 public static final String PREFERENCE_NAME = "notes_preferences";
public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";// 定义了一个常量字符串 PREFERENCE_LAST_SYNC_TIME表示上一次同步时间的键名 public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";
public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";// 定义了一个常量字符串 PREFERENCE_SET_BG_COLOR_KEY表示是否随机设置背景颜色的键名 public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";
public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";// 定义了一个常量字符串 PREFERENCE_SYNC_ACCOUNT_KEY表示同步账户的键名 public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";
private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";// 定义了一个常量字符串 PREFERENCE_SYNC_ACCOUNT_KEY表示同步账户的键名 private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";
private static final String AUTHORITIES_FILTER_KEY = "authorities";// 定义了一个常量字符串 AUTHORITIES_FILTER_KEY表示过滤器的 authorities 键名 private static final String AUTHORITIES_FILTER_KEY = "authorities";
private PreferenceCategory mAccountCategory;// 声明了一个 PreferenceCategory 类型的成员变量 mAccountCategory表示账户分类 private PreferenceCategory mAccountCategory;
private GTaskReceiver mReceiver;
private GTaskReceiver mReceiver;// 声明了一个 GTaskReceiver 类型的成员变量 mReceiver表示 GTask 接收器 private Account[] mOriAccounts;
private boolean mHasAddedAccount;
private Account[] mOriAccounts;// 声明了一个 Account 数组类型的成员变量 mOriAccounts表示原始账户
private boolean mHasAddedAccount;// 声明了一个 boolean 类型的成员变量 mHasAddedAccount表示是否已添加了账户
@Override @Override
protected void onCreate(Bundle icicle) { protected void onCreate(Bundle icicle) {
@ -78,22 +76,21 @@ public class NotesPreferenceActivity extends PreferenceActivity {// 定义了一
/* using the app icon for navigation */ /* using the app icon for navigation */
getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true);
addPreferencesFromResource(R.xml.preferences);// 加载 preferences.xml 文件中的 Preference addPreferencesFromResource(R.xml.preferences);
mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);// 从 preferences.xml 中找到同步账户分类,赋值给 mAccountCategory mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
mReceiver = new GTaskReceiver(); mReceiver = new GTaskReceiver();
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME); filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
registerReceiver(mReceiver, filter);// 注册 GTaskReceiver 广播接收器,监听 Gtask 同步服务的消息 registerReceiver(mReceiver, filter);
mOriAccounts = null; mOriAccounts = null;
View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null); View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
getListView().addHeaderView(header, null, true);//将原始账户数组 mOriAccounts 设置为 null。 getListView().addHeaderView(header, null, true);
} }
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume();// onStart 方法,表示 Activity 启动时调用的方 super.onResume();
// need to set sync account automatically if user has added a new // need to set sync account automatically if user has added a new
// account // account
@ -117,15 +114,7 @@ public class NotesPreferenceActivity extends PreferenceActivity {// 定义了一
} }
refreshUI(); refreshUI();
}/*1. onCreate() Activity }
2. 便Activity
3. preferences.xml Preference
4. preferences.xml mAccountCategory
5. GTaskReceiver 广 GTask
6. mOriAccounts null
7. LayoutInflater R.layout.settings_header
8. ListView
广*/
@Override @Override
protected void onDestroy() { protected void onDestroy() {
@ -133,67 +122,64 @@ public class NotesPreferenceActivity extends PreferenceActivity {// 定义了一
unregisterReceiver(mReceiver); unregisterReceiver(mReceiver);
} }
super.onDestroy(); super.onDestroy();
}/* Android Activity onDestroy() }
1. mReceiver null null广
2. onDestroy() Activity
Activity 广 Android 广广 Activity Activity广*/
private void loadAccountPreference() { private void loadAccountPreference() {
mAccountCategory.removeAll();// 清空同步账户分类中的所有设置项 mAccountCategory.removeAll();
Preference accountPref = new Preference(this);// 创建一个新的 Preference 对象 accountPref Preference accountPref = new Preference(this);
final String defaultAccount = getSyncAccountName(this);// 获取当前默认的同步账户名称 final String defaultAccount = getSyncAccountName(this);
accountPref.setTitle(getString(R.string.preferences_account_title));// 设置 accountPref 的标题和摘要 accountPref.setTitle(getString(R.string.preferences_account_title));
accountPref.setSummary(getString(R.string.preferences_account_summary)); // 设置 accountPref 的点击事件监听器 accountPref.setSummary(getString(R.string.preferences_account_summary));
accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {// 判断是否正在进行同步任务 public boolean onPreferenceClick(Preference preference) {
if (!GTaskSyncService.isSyncing()) { if (!GTaskSyncService.isSyncing()) {
if (TextUtils.isEmpty(defaultAccount)) { if (TextUtils.isEmpty(defaultAccount)) {
// the first time to set account // the first time to set account
showSelectAccountAlertDialog();//如果当前同步账户为空,则弹出选择账户对话框 showSelectAccountAlertDialog();
} else { } else {
// if the account has already been set, we need to promp // if the account has already been set, we need to promp
// user about the risk // user about the risk
showChangeAccountConfirmAlertDialog(); showChangeAccountConfirmAlertDialog();
}// 如果已经设置了同步账户,则需要提示用户风险 }
} else { } else {
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT) R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
.show();// 如果正在进行同步任务,则提示用户无法更改账户 .show();
} }
return true;// 返回 true表示点击事件已被处理 return true;
} }
}); });
mAccountCategory.addPreference(accountPref);// 将 accountPref 添加到同步账户分类中 mAccountCategory.addPreference(accountPref);
} }
private void loadSyncButton() { private void loadSyncButton() {
Button syncButton = (Button) findViewById(R.id.preference_sync_button);// 获取同步按钮和上次同步时间的视图对 Button syncButton = (Button) findViewById(R.id.preference_sync_button);
TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);// 设置同步按钮的状态和点击事件监听器 TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
// set button state // set button state
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
syncButton.setText(getString(R.string.preferences_button_sync_cancel)); // 如果正在同步任务中,则将按钮文本设置为“取消同步”,并添加取消同步的点击事件监听器 syncButton.setText(getString(R.string.preferences_button_sync_cancel));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
GTaskSyncService.cancelSync(NotesPreferenceActivity.this); GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
} }
}); });
} else { } else {
syncButton.setText(getString(R.string.preferences_button_sync_immediately));// 如果没有正在同步任务,则将按钮文本设置为“立即同步”,并添加开始同步的点击事件监听器 syncButton.setText(getString(R.string.preferences_button_sync_immediately));
syncButton.setOnClickListener(new View.OnClickListener() { syncButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
GTaskSyncService.startSync(NotesPreferenceActivity.this); GTaskSyncService.startSync(NotesPreferenceActivity.this);
} }
}); });
}// 根据当前是否设置了同步账户来设置同步按钮的可用状态 }
syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));// 设置上次同步时间的显示状态和文本内容 syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));
// set last sync time // set last sync time
if (GTaskSyncService.isSyncing()) { if (GTaskSyncService.isSyncing()) {
lastSyncTimeView.setText(GTaskSyncService.getProgressString()); lastSyncTimeView.setText(GTaskSyncService.getProgressString());
lastSyncTimeView.setVisibility(View.VISIBLE); // 如果正在同步任务中,则显示当前同步进度,并将上次同步时间视图设置为可见状态 lastSyncTimeView.setVisibility(View.VISIBLE);
} else { } else {
long lastSyncTime = getLastSyncTime(this); long lastSyncTime = getLastSyncTime(this);
if (lastSyncTime != 0) { if (lastSyncTime != 0) {
@ -205,192 +191,184 @@ public class NotesPreferenceActivity extends PreferenceActivity {// 定义了一
lastSyncTimeView.setVisibility(View.GONE); lastSyncTimeView.setVisibility(View.GONE);
} }
} }
}// 如果没有正在同步任务则获取上次同步时间并根据上次同步时间是否为0来设置上次同步时间视图的可见状态和文本内容 }
private void refreshUI() { private void refreshUI() {
loadAccountPreference(); loadAccountPreference();
loadSyncButton(); loadSyncButton();
}/*loadAccountPreference() 方法用于加载和显示当前同步账户的信息,而 loadSyncButton() 方法则用于设置同步按钮的状态和点击事件监听器,并显示上次同步时间的信息。*/ }
private void showSelectAccountAlertDialog() { private void showSelectAccountAlertDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);// 创建 AlertDialog.Builder 对象 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);/// 创建自定义标题视图 TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));// 设置标题文本 titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));// 设置副标题文本 subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));
dialogBuilder.setCustomTitle(titleView);// 将自定义标题视图设置到对话框中 dialogBuilder.setCustomTitle(titleView);
dialogBuilder.setPositiveButton(null, null); // 不设置确定按钮和点击事件监听器 dialogBuilder.setPositiveButton(null, null);
Account[] accounts = getGoogleAccounts(); Account[] accounts = getGoogleAccounts();
String defAccount = getSyncAccountName(this);// 获取所有谷歌账户的列表和当前同步账户的名称 String defAccount = getSyncAccountName(this);
mOriAccounts = accounts; mOriAccounts = accounts;
mHasAddedAccount = false;// 保存原始账户列表并将“已添加账户”标志设为 false mHasAddedAccount = false;
if (accounts.length > 0) {// 如果找到了至少一个谷歌账户,则创建单选项列表 if (accounts.length > 0) {
CharSequence[] items = new CharSequence[accounts.length];// 创建单选项列表的选项文本数组 CharSequence[] items = new CharSequence[accounts.length];
final CharSequence[] itemMapping = items;// 创建选项文本数组的映射数组 final CharSequence[] itemMapping = items;
int checkedItem = -1; // 初始化默认选中项的索引为 -1 int checkedItem = -1;
int index = 0; int index = 0;
for (Account account : accounts) {// 遍历所有谷歌账户,为每个账户设置一个选项 for (Account account : accounts) {
if (TextUtils.equals(account.name, defAccount)) { if (TextUtils.equals(account.name, defAccount)) {
checkedItem = index; checkedItem = index;
}// 如果该账户的名称与当前同步账户的名称相同,则将其作为默认选中项
items[index++] = account.name;// 将该账户的名称添加到选项文本数组中
} }
dialogBuilder.setSingleChoiceItems(items, checkedItem, // 将单选项列表设置到对话框中,并为每个选项设置点击事件监听器 items[index++] = account.name;
}
dialogBuilder.setSingleChoiceItems(items, checkedItem,
new DialogInterface.OnClickListener() { new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
setSyncAccount(itemMapping[which].toString()); // 将用户选择的账户名称设置为同步账户 setSyncAccount(itemMapping[which].toString());
dialog.dismiss();// 关闭对话框 dialog.dismiss();
refreshUI();// 刷新 UI 界面上的账户和同步按钮状态 refreshUI();
} }
}); });
} }
View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);//从布局文件中加载一个视图对象并将其赋值给 addAccountView 变量 View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
dialogBuilder.setView(addAccountView);//将 addAccountView 设置为对话框的自定义视图 dialogBuilder.setView(addAccountView);
final AlertDialog dialog = dialogBuilder.show();//创建一个 AlertDialog 对象,并将其显示出来 final AlertDialog dialog = dialogBuilder.show();
addAccountView.setOnClickListener(new View.OnClickListener() {//添加一个点击事件监听器 addAccountView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) { public void onClick(View v) {
mHasAddedAccount = true;//用户是否已经添加了一个账户 mHasAddedAccount = true;
Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS"); Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] { intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
"gmail-ls" "gmail-ls"
});//创建了一个 Intent 对象,用于启动一个系统设置界面,以便让用户添加新的帐户 });
startActivityForResult(intent, -1);//启动一个新的界面,等待用户添加新的账户 startActivityForResult(intent, -1);
dialog.dismiss();//关闭对话框 dialog.dismiss();
} }
}); });
} }
private void showChangeAccountConfirmAlertDialog() { private void showChangeAccountConfirmAlertDialog() {
// 创建一个 AlertDialog.Builder 对象
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this); AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// 从布局文件 R.layout.account_dialog_title 中加载一个视图 titleView
View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null); View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
// 从 titleView 中找到一个 TextView 对象 titleTextView并设置其文本
TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title); TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
titleTextView.setText(getString(R.string.preferences_dialog_change_account_title, titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
getSyncAccountName(this))); getSyncAccountName(this)));
// 从 titleView 中找到一个 TextView 对象 subtitleTextView并设置其文本
TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle); TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg)); subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
// 将 titleView 设置为对话框的自定义标题
dialogBuilder.setCustomTitle(titleView); dialogBuilder.setCustomTitle(titleView);
// 创建一个 CharSequence 类型的数组 menuItemArray包含三个字符串作为选项菜单的标签文字
CharSequence[] menuItemArray = new CharSequence[] { CharSequence[] menuItemArray = new CharSequence[] {
getString(R.string.preferences_menu_change_account), getString(R.string.preferences_menu_change_account),
getString(R.string.preferences_menu_remove_account), getString(R.string.preferences_menu_remove_account),
getString(R.string.preferences_menu_cancel) getString(R.string.preferences_menu_cancel)
}; };
dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() { // 创建一个 DialogInterface.OnClickListener 对象,用于处理选项菜单的点击事件 dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {// 判断点击了哪个菜单项 public void onClick(DialogInterface dialog, int which) {
if (which == 0) { if (which == 0) {
showSelectAccountAlertDialog();// 如果点击了第一个菜单项,调用 showSelectAccountAlertDialog() 方法显示“选择帐户”对话框 showSelectAccountAlertDialog();
} else if (which == 1) { } else if (which == 1) {
removeSyncAccount(); removeSyncAccount();
refreshUI();// 如果点击了第二个菜单项,先调用 removeSyncAccount() 方法删除同步帐户,再调用 refreshUI() 方法刷新界面 refreshUI();
} }
} }
}); });
dialogBuilder.show();// 显示对话框 dialogBuilder.show();
} }
private Account[] getGoogleAccounts() { private Account[] getGoogleAccounts() {
// 获取 AccountManager 对象
AccountManager accountManager = AccountManager.get(this); AccountManager accountManager = AccountManager.get(this);
// 调用 getAccountsByType() 方法,传入参数 "com.google",以获取所有类型为 "com.google" 的帐户
return accountManager.getAccountsByType("com.google"); return accountManager.getAccountsByType("com.google");
} }
private void setSyncAccount(String account) { private void setSyncAccount(String account) {
if (!getSyncAccountName(this).equals(account)) {// 判断传入的 account 是否与当前同步帐户相同 if (!getSyncAccountName(this).equals(account)) {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();// 获取 SharedPreferences 对象 SharedPreferences.Editor editor = settings.edit();
if (account != null) { if (account != null) {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account); // 如果传入的 account 不为 null则将其存储到 SharedPreferences 中 editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
} else { } else {
editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");// 如果传入的 account 为 null则将空字符串存储到 SharedPreferences 中 editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
editor.commit();// 提交修改 editor.commit();
// clean up last sync time // clean up last sync time
setLastSyncTime(this, 0);// 清除上一次同步的时间 setLastSyncTime(this, 0);
// clean up local gtask related info // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues(); // 创建一个 ContentValues 对象,用于更新所有的 note ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, "");// 清空 GTasks ID 和 sync ID values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0);// 清空 GTasks ID 和 sync ID values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); // 更新所有的 note getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start(); }).start();
Toast.makeText(NotesPreferenceActivity.this, Toast.makeText(NotesPreferenceActivity.this,
getString(R.string.preferences_toast_success_set_accout, account), getString(R.string.preferences_toast_success_set_accout, account),
Toast.LENGTH_SHORT).show();// 显示一个 Toast提示同步帐户设置成功 Toast.LENGTH_SHORT).show();
} }
} }
private void removeSyncAccount() { private void removeSyncAccount() {
SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); // 获取 SharedPreferences 对象 SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();// 获取 SharedPreferences 对象 SharedPreferences.Editor editor = settings.edit();
if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) { if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME); editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
}// 如果 SharedPreferences 包含同步帐户名称,则从 SharedPreferences 中删除该名称 }
if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) { if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
editor.remove(PREFERENCE_LAST_SYNC_TIME); // 如果 SharedPreferences 包含上一次同步的时间,则从 SharedPreferences 中删除该时间 editor.remove(PREFERENCE_LAST_SYNC_TIME);
} }
editor.commit(); // 提交修改 editor.commit();
// clean up local gtask related info // clean up local gtask related info
new Thread(new Runnable() { new Thread(new Runnable() {
public void run() { public void run() {
ContentValues values = new ContentValues();// 创建一个 ContentValues 对象,用于更新所有的 note ContentValues values = new ContentValues();
values.put(NoteColumns.GTASK_ID, ""); values.put(NoteColumns.GTASK_ID, "");
values.put(NoteColumns.SYNC_ID, 0); // 清空 GTasks ID 和 sync ID values.put(NoteColumns.SYNC_ID, 0);
getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null); getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
} }
}).start();// 更新所有的 note }).start();
} }
public static String getSyncAccountName(Context context) { public static String getSyncAccountName(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,// 获取 SharedPreferences 对象 SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");// 从 SharedPreferences 中获取同步帐户名称 return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
} }
public static void setLastSyncTime(Context context, long time) { public static void setLastSyncTime(Context context, long time) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE); Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit(); // 获取 SharedPreferences 对象 SharedPreferences.Editor editor = settings.edit();
editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);// 将最后一次同步的时间保存到 SharedPreferences 中 editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
editor.commit();// 提交修改 editor.commit();
} }
public static long getLastSyncTime(Context context) { public static long getLastSyncTime(Context context) {
SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);// 获取 SharedPreferences 对象 Context.MODE_PRIVATE);
return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);// 从 SharedPreferences 中获取最后一次同步的时间 return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
} }
private class GTaskReceiver extends BroadcastReceiver { private class GTaskReceiver extends BroadcastReceiver {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
refreshUI();// 刷新用户界面 refreshUI();
if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) { if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview); TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
syncStatus.setText(intent syncStatus.setText(intent
.getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));// 如果正在同步,则更新同步状态 .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
} }
} }
@ -402,9 +380,9 @@ public class NotesPreferenceActivity extends PreferenceActivity {// 定义了一
Intent intent = new Intent(this, NotesListActivity.class); Intent intent = new Intent(this, NotesListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent); startActivity(intent);
return true; // 创建一个 Intent 对象,跳转到 NotesListActivity并清除之前的所有 Activity return true;
default: default:
return false;// 如果选择的菜单项不是返回主页,则返回 false return false;
} }
} }
} }

@ -37,15 +37,13 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
NoteColumns.ID, NoteColumns.ID,
NoteColumns.BG_COLOR_ID, NoteColumns.BG_COLOR_ID,
NoteColumns.SNIPPET NoteColumns.SNIPPET
};/* NoteWidgetProvider AppWidgetProvider };
PROJECTION ID ID */ public static final int COLUMN_ID = 0;
public static final int COLUMN_BG_COLOR_ID = 1;
public static final int COLUMN_SNIPPET = 2;
public static final int COLUMN_ID = 0;// 笔记 ID 列在 PROJECTION 数组中的索引 private static final String TAG = "NoteWidgetProvider";
public static final int COLUMN_BG_COLOR_ID = 1;// 笔记背景颜色 ID 列在 PROJECTION 数组中的索引
public static final int COLUMN_SNIPPET = 2;// 笔记摘录内容列在 PROJECTION 数组中的索引
private static final String TAG = "NoteWidgetProvider";// 日志输出标识符
@Override @Override
public void onDeleted(Context context, int[] appWidgetIds) { public void onDeleted(Context context, int[] appWidgetIds) {
@ -57,28 +55,19 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
NoteColumns.WIDGET_ID + "=?", NoteColumns.WIDGET_ID + "=?",
new String[] { String.valueOf(appWidgetIds[i])}); new String[] { String.valueOf(appWidgetIds[i])});
} }
}/* NoteWidgetProvider onDeleted() AppWidgetProvider }
ContentValues values NoteColumns.WIDGET_ID AppWidgetManager.INVALID_APPWIDGET_ID
appWidgetIds NoteColumns.WIDGET_ID AppWidgetManager.INVALID_APPWIDGET_ID便
使 getContentResolver() ContentResolver update() NoteColumns.WIDGET_ID + "=?" NoteColumns.WIDGET_ID ID values NoteColumns.WIDGET_ID AppWidgetManager.INVALID_APPWIDGET_ID*/
private Cursor getNoteWidgetInfo(Context context, int widgetId) {// 使用 getContentResolver() 方法获取 ContentResolver 对象,通过该对象进行对笔记数据库的查询操作 private Cursor getNoteWidgetInfo(Context context, int widgetId) {
return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, // 使用 query() 方法查询笔记数据库,返回一个 Cursor 对象 return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
return context.getContentResolver().query(// 查询的 URI笔记数据库中笔记的内容保存在该 URI 下
PROJECTION,
Notes.CONTENT_NOTE_URI,
PROJECTION, PROJECTION,
NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",// 查询的列,即笔记 ID、笔记背景颜色 ID 和笔记摘录内容 NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },//查询的条件,即笔记关联的小部件 ID 以及笔记的父 ID 不为回收站的笔记 new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
null);// 排序方式,这里为 null 表示不排序 null);
} }
protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
update(context, appWidgetManager, appWidgetIds, false); update(context, appWidgetManager, appWidgetIds, false);
}/*这是 NoteWidgetProvider 抽象类中的一个受保护的方法 update(),它接受一个 Context 对象、一个 AppWidgetManager 对象和一个整型数组 appWidgetIds 作为参数,并在方法中调用了另一个同名方法。*/ }
private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
boolean privacyMode) { boolean privacyMode) {
@ -133,21 +122,11 @@ public abstract class NoteWidgetProvider extends AppWidgetProvider {
appWidgetManager.updateAppWidget(appWidgetIds[i], rv); appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
} }
} }
}/* `NoteWidgetProvider` `update()` `Context` `AppWidgetManager` `appWidgetIds` `privacyMode` }
`appWidgetIds` ID `AppWidgetManager.INVALID_APPWIDGET_ID`
- ID
- `NoteEditActivity` ID
- `getNoteWidgetInfo()` ID
- ID `RemoteViews` ID `PendingIntent`
- `AppWidgetManager` `updateAppWidget()`
`privacyMode` `true` "隐私模式" `NotesListActivity` `NoteEditActivity`*/
protected abstract int getBgResourceId(int bgId);//用于获取小部件的背景资源 ID。 protected abstract int getBgResourceId(int bgId);
protected abstract int getLayoutId();//用于获取小部件的布局资源 ID。 protected abstract int getLayoutId();
protected abstract int getWidgetType();//用于获取小部件的类型。 protected abstract int getWidgetType();
} }

@ -24,24 +24,24 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_2x extends NoteWidgetProvider {//创建一个继承自 NoteWidgetProvider 的子类 NoteWidgetProvider_2x public class NoteWidgetProvider_2x extends NoteWidgetProvider {
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
}/*重写父类的 onUpdate() 方法,并在其中调用父类的 update() 方法,以更新小部件的显示内容和点击事件。*/ }
@Override @Override
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_2x; return R.layout.widget_2x;
}/*重写父类的 getLayoutId() 方法,返回用于小部件的布局资源 ID。这里返回 R.layout.widget_2x表示使用 widget_2x.xml 文件作为布局资源。*/ }
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId);
}/*重写父类的 getBgResourceId() 方法,返回用于小部件的背景资源 ID。这里调用了 ResourceParser.WidgetBgResources.getWidget2xBgResource(bgId) 方法,该方法根据传入的背景 ID 返回相应的背景资源 ID。*/ }
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_2X; return Notes.TYPE_WIDGET_2X;
}/*重写父类的 getWidgetType() 方法,返回小部件的类型。这里返回 Notes.TYPE_WIDGET_2X表示这是一个 2x 大小的小部件。*/ }
} }

@ -24,22 +24,23 @@ import net.micode.notes.data.Notes;
import net.micode.notes.tool.ResourceParser; import net.micode.notes.tool.ResourceParser;
public class NoteWidgetProvider_4x extends NoteWidgetProvider {//创建一个继承自 NoteWidgetProvider 的子类 NoteWidgetProvider_4x。 public class NoteWidgetProvider_4x extends NoteWidgetProvider {
@Override @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.update(context, appWidgetManager, appWidgetIds); super.update(context, appWidgetManager, appWidgetIds);
}/*重写父类的 onUpdate() 方法,并在其中调用父类的 update() 方法,以更新小部件的显示内容和点击事件。*/ }
protected int getLayoutId() { protected int getLayoutId() {
return R.layout.widget_4x; return R.layout.widget_4x;
}/*重写父类的 getLayoutId() 方法,返回用于小部件的布局资源 ID。这里返回 R.layout.widget_4x表示使用 widget_4x.xml 文件作为布局资源。*/ }
@Override @Override
protected int getBgResourceId(int bgId) { protected int getBgResourceId(int bgId) {
return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId); return ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId);
}/*重写父类的 getBgResourceId() 方法,返回用于小部件的背景资源 ID。这里调用了 ResourceParser.WidgetBgResources.getWidget4xBgResource(bgId) 方法,该方法根据传入的背景 ID 返回相应的背景资源 ID。*/ }
@Override @Override
protected int getWidgetType() { protected int getWidgetType() {
return Notes.TYPE_WIDGET_4X; return Notes.TYPE_WIDGET_4X;
} }
}/*重写父类的 getWidgetType() 方法,返回小部件的类型。这里返回 Notes.TYPE_WIDGET_4X表示这是一个 4x 大小的小部件。*/ }

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.5 KiB

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Before

Width:  |  Height:  |  Size: 3.1 KiB

After

Width:  |  Height:  |  Size: 3.1 KiB

Before

Width:  |  Height:  |  Size: 6.7 KiB

After

Width:  |  Height:  |  Size: 6.7 KiB

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Before

Width:  |  Height:  |  Size: 3.2 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save