Ray Zhang 11 سال پیش
والد
کامیت
1fd6ff995f
45فایلهای تغییر یافته به همراه3995 افزوده شده و 1821 حذف شده
  1. 17 2
      RedAnt Photo/AndroidManifest.xml
  2. 0 94
      RedAnt Photo/bin/AndroidManifest.xml
  3. BIN
      RedAnt Photo/bin/RedAnt Photo.apk
  4. BIN
      RedAnt Photo/bin/classes.dex
  5. BIN
      RedAnt Photo/bin/dexedLibs/android-support-v4-ad2b487553186efad76950e11c38631e.jar
  6. BIN
      RedAnt Photo/bin/dexedLibs/core-2.3.0-e81eef8eadd8056a1cd4c87d01190c6d.jar
  7. BIN
      RedAnt Photo/bin/dexedLibs/httpmime-4.1.1-f01cef40ac68c8b60029e5681e91d959.jar
  8. 0 3
      RedAnt Photo/bin/jarlist.cache
  9. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/apertureblack128.png
  10. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/barcode_scanner128.png
  11. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/camera_256.png
  12. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/database_upload128.png
  13. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/ic_launcher.png
  14. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/ic_shipping.png
  15. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/no_pic.png
  16. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/picture_frame.png
  17. BIN
      RedAnt Photo/bin/res/crunch/drawable-hdpi/qr_code256.png
  18. BIN
      RedAnt Photo/bin/res/crunch/drawable-mdpi/ic_launcher.png
  19. BIN
      RedAnt Photo/bin/res/crunch/drawable-xhdpi/ic_launcher.png
  20. BIN
      RedAnt Photo/bin/res/crunch/drawable-xxhdpi/ic_launcher.png
  21. BIN
      RedAnt Photo/bin/resources.ap_
  22. BIN
      RedAnt Photo/res/drawable-hdpi/picture_frame.png
  23. 0 201
      RedAnt Photo/res/layout-ldpi/capture.xml
  24. 4 2
      RedAnt Photo/res/layout/activity_locker.xml
  25. 6 4
      RedAnt Photo/res/layout/activity_login.xml
  26. 6 7
      RedAnt Photo/res/layout/activity_main1.xml
  27. 54 0
      RedAnt Photo/res/layout/activity_photo_preview.xml
  28. 33 0
      RedAnt Photo/res/layout/activity_search.xml
  29. 8 1
      RedAnt Photo/res/layout/capture.xml
  30. 50 0
      RedAnt Photo/res/layout/search_lvitem_edit.xml
  31. 10 4
      RedAnt Photo/res/menu/main.xml
  32. 5 2
      RedAnt Photo/res/values/strings.xml
  33. 12 1
      RedAnt Photo/src/com/usai/redant/photo/BootReceiver.java
  34. 836 659
      RedAnt Photo/src/com/usai/redant/photo/CaptureActivity.java
  35. 586 114
      RedAnt Photo/src/com/usai/redant/photo/LockerActivity.java
  36. 182 115
      RedAnt Photo/src/com/usai/redant/photo/LoginActivity.java
  37. 563 341
      RedAnt Photo/src/com/usai/redant/photo/MainActivity.java
  38. 191 0
      RedAnt Photo/src/com/usai/redant/photo/PhotoPreviewActivity.java
  39. 35 0
      RedAnt Photo/src/com/usai/redant/photo/RedAntApplication.java
  40. 335 0
      RedAnt Photo/src/com/usai/redant/photo/UploadQueueActivity.java
  41. 247 2
      RedAnt Photo/src/com/usai/redant/photo/UploadService.java
  42. 133 0
      RedAnt Photo/src/com/usai/util/Crypto.java
  43. 627 258
      RedAnt Photo/src/com/usai/util/Network.java
  44. 40 1
      RedAnt Photo/src/com/usai/util/dbUtil.java
  45. 15 10
      RedAnt Photo/src/com/usai/util/dbgUtil.java

+ 17 - 2
RedAnt Photo/AndroidManifest.xml

@@ -18,6 +18,7 @@
     <uses-permission android:name="android.permission.INTERNET" />
 
     <application
+        android:name="com.usai.redant.photo.RedAntApplication"
         android:allowBackup="true"
         android:icon="@drawable/ic_shipping"
         android:label="@string/app_name"
@@ -26,6 +27,7 @@
             android:name="com.usai.redant.photo.MainActivity"
             android:configChanges="orientation|keyboardHidden"
             android:label="@string/app_name"
+            
             android:screenOrientation="landscape"
             android:stateNotNeeded="true"
             android:theme="@style/CaptureTheme" >
@@ -41,9 +43,9 @@
         <activity
             android:name="com.usai.redant.photo.CaptureActivity"
             android:clearTaskOnLaunch="true"
-            android:configChanges="orientation|keyboardHidden"
             android:label="Scan"
             android:stateNotNeeded="true"
+            android:screenOrientation="landscape"
             android:theme="@style/CaptureTheme"
             android:windowSoftInputMode="stateAlwaysHidden" >
 
@@ -58,7 +60,7 @@
         <activity
             android:name="com.usai.redant.photo.LoginActivity"
             android:label="@string/app_name"
-            android:screenOrientation="landscape"
+            android:screenOrientation="sensorLandscape"
             android:windowSoftInputMode="stateHidden|adjustResize" >
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
@@ -66,10 +68,23 @@
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
+        <activity
+            android:name="com.usai.redant.photo.UploadQueueActivity"
+            android:label="Upload queue"
+
+            android:theme="@style/CaptureTheme"
+            android:screenOrientation="landscape">
+            
+        </activity>
         <activity
             android:name="com.usai.redant.photo.PreferencesActivityvity"
             android:label="@string/preferences_name"
             android:stateNotNeeded="true" >
+        </activity>
+                <activity
+            android:name="com.usai.redant.photo.PhotoPreviewActivity"
+            android:label="@string/preferences_name"
+             >
         </activity>
         <activity
             android:name="com.usai.redant.photo.LockerActivity"

+ 0 - 94
RedAnt Photo/bin/AndroidManifest.xml

@@ -1,94 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-    package="com.usai.redant.photo"
-    android:versionCode="1"
-    android:versionName="1.0" >
-
-    <uses-sdk
-        android:minSdkVersion="14"
-        android:targetSdkVersion="18" />
-
-    <uses-permission android:name="android.permission.CAMERA" />
-    <uses-permission android:name="android.permission.VIBRATE" />
-    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
-    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
-    <uses-permission android:name="android.permission.INTERNET" />
-
-    <application
-        android:allowBackup="true"
-        android:icon="@drawable/ic_shipping"
-        android:label="@string/app_name"
-        android:theme="@style/AppTheme" >
-        <activity
-            android:name="com.usai.redant.photo.MainActivity"
-            android:configChanges="orientation|keyboardHidden"
-            android:label="@string/app_name"
-            android:screenOrientation="landscape"
-            android:stateNotNeeded="true"
-            android:theme="@style/CaptureTheme" >
-
-            <!--
-                 <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-            -->
-        </activity>
-        <activity
-            android:name="com.usai.redant.photo.CaptureActivity"
-            android:clearTaskOnLaunch="true"
-            android:configChanges="orientation|keyboardHidden"
-            android:label="Scan"
-            android:stateNotNeeded="true"
-            android:theme="@style/CaptureTheme"
-            android:windowSoftInputMode="stateAlwaysHidden" >
-
-            <!--
-                 <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-            -->
-        </activity>
-        <activity
-            android:name="com.usai.redant.photo.LoginActivity"
-            android:label="@string/app_name"
-            android:screenOrientation="landscape"
-            android:windowSoftInputMode="stateHidden|adjustResize" >
-            <intent-filter>
-                <action android:name="android.intent.action.MAIN" />
-
-                <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>
-        </activity>
-        <activity
-            android:name="com.usai.redant.photo.PreferencesActivityvity"
-            android:label="@string/preferences_name"
-            android:stateNotNeeded="true" >
-        </activity>
-        <activity
-            android:name="com.usai.redant.photo.LockerActivity"
-            android:label="@string/title_activity_locker"
-            android:screenOrientation="landscape"
-            android:windowSoftInputMode="adjustResize|stateVisible" >
-        </activity>
-
-        <receiver android:name="com.usai.redant.photo.BootReceiver" >
-            <intent-filter android:priority="2147483647" >
-                <action android:name="android.intent.action.BOOT_COMPLETED" />
-                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
-            </intent-filter>
-        </receiver>
-
-        <service
-            android:name="com.usai.redant.photo.UploadService"
-            android:label="usai upload service" >
-        </service>
-    </application>
-
-</manifest>

BIN
RedAnt Photo/bin/RedAnt Photo.apk


BIN
RedAnt Photo/bin/classes.dex


BIN
RedAnt Photo/bin/dexedLibs/android-support-v4-244ae62fbeb5c51ea12edd1e7158e520.jar → RedAnt Photo/bin/dexedLibs/android-support-v4-ad2b487553186efad76950e11c38631e.jar


BIN
RedAnt Photo/bin/dexedLibs/core-2.3.0-84c93f4ef03886c0c217796c3e60cab1.jar → RedAnt Photo/bin/dexedLibs/core-2.3.0-e81eef8eadd8056a1cd4c87d01190c6d.jar


BIN
RedAnt Photo/bin/dexedLibs/httpmime-4.1.1-dbad932ae6bcfab1636e85a4463b0b5c.jar → RedAnt Photo/bin/dexedLibs/httpmime-4.1.1-f01cef40ac68c8b60029e5681e91d959.jar


+ 0 - 3
RedAnt Photo/bin/jarlist.cache

@@ -1,3 +0,0 @@
-# cache for current jar dependency. DO NOT EDIT.
-# format is <lastModified> <length> <SHA-1> <path>
-# Encoding is UTF-8

BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/apertureblack128.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/barcode_scanner128.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/camera_256.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/database_upload128.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/ic_launcher.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/ic_shipping.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/no_pic.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/picture_frame.png


BIN
RedAnt Photo/bin/res/crunch/drawable-hdpi/qr_code256.png


BIN
RedAnt Photo/bin/res/crunch/drawable-mdpi/ic_launcher.png


BIN
RedAnt Photo/bin/res/crunch/drawable-xhdpi/ic_launcher.png


BIN
RedAnt Photo/bin/res/crunch/drawable-xxhdpi/ic_launcher.png


BIN
RedAnt Photo/bin/resources.ap_


BIN
RedAnt Photo/res/drawable-hdpi/picture_frame.png


+ 0 - 201
RedAnt Photo/res/layout-ldpi/capture.xml

@@ -1,201 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright (C) 2008 ZXing authors
-
- 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.
- -->
-<merge xmlns:android="http://schemas.android.com/apk/res/android">
-
-  <SurfaceView android:id="@+id/preview_view"
-               android:layout_width="fill_parent"
-               android:layout_height="fill_parent"/>
-
-  <com.usai.redant.photo.ViewfinderView
-      android:id="@+id/viewfinder_view"
-      android:layout_width="fill_parent"
-      android:layout_height="fill_parent"/>
-
-  <!-- <LinearLayout android:id="@+id/result_view"
-                android:orientation="vertical"
-                android:layout_width="fill_parent"
-                android:layout_height="fill_parent"
-                android:background="@color/result_view"
-                android:visibility="gone"
-                android:baselineAligned="false">
-
-    <LinearLayout
-        android:orientation="horizontal"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:layout_weight="1"
-        android:gravity="top"
-        android:padding="@dimen/standard_padding">
-
-      <LinearLayout
-          android:orientation="vertical"
-          android:layout_width="wrap_content"
-          android:layout_height="fill_parent"
-          android:gravity="right">
-
-        <ImageView android:id="@+id/barcode_image_view"
-                   android:layout_width="150dip"
-                   android:layout_height="wrap_content"
-                   android:maxWidth="150dip"
-                   android:maxHeight="150dip"
-                   android:layout_marginBottom="@dimen/half_padding"
-                   android:adjustViewBounds="true"
-                   android:scaleType="centerInside"/>
-
-        <LinearLayout
-          android:orientation="horizontal"
-          android:layout_width="wrap_content"
-          android:layout_height="wrap_content">
-
-          <TextView android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:text="@string/msg_default_format"
-                    android:textColor="@color/result_minor_text"
-                    android:textStyle="bold"
-                    android:paddingRight="@dimen/half_padding"/>
-
-          <TextView android:id="@+id/format_text_view"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:textColor="@color/result_minor_text"/>
-
-        </LinearLayout>
-
-        <LinearLayout
-          android:orientation="horizontal"
-          android:layout_width="wrap_content"
-          android:layout_height="wrap_content">
-
-          <TextView android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:text="@string/msg_default_type"
-                    android:textColor="@color/result_minor_text"
-                    android:textStyle="bold"
-                    android:paddingRight="@dimen/half_padding"/>
-
-          <TextView android:id="@+id/type_text_view"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:textColor="@color/result_minor_text"/>
-
-        </LinearLayout>
-
-        <LinearLayout
-          android:orientation="horizontal"
-          android:layout_width="wrap_content"
-          android:layout_height="wrap_content">
-
-          <TextView android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:text="@string/msg_default_time"
-                    android:textColor="@color/result_minor_text"
-                    android:textStyle="bold"
-                    android:paddingRight="@dimen/half_padding"/>
-
-          <TextView android:id="@+id/time_text_view"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:textColor="@color/result_minor_text"/>
-
-        </LinearLayout>
-
-        <LinearLayout
-          android:orientation="horizontal"
-          android:layout_width="wrap_content"
-          android:layout_height="wrap_content">
-
-          <TextView android:id="@+id/meta_text_view_label"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:text="@string/msg_default_meta"
-                    android:textColor="@color/result_minor_text"
-                    android:textStyle="bold"
-                    android:paddingRight="@dimen/half_padding"/>
-
-          <TextView android:id="@+id/meta_text_view"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:textColor="@color/result_minor_text"/>
-
-        </LinearLayout>
-
-      </LinearLayout>
-
-      <ScrollView
-          android:layout_width="fill_parent"
-          android:layout_height="wrap_content">
-
-        <LinearLayout
-          android:orientation="vertical"
-          android:layout_width="wrap_content"
-          android:layout_height="wrap_content">
-
-          <TextView android:id="@+id/contents_text_view"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:textColor="@color/result_text"
-                    android:textColorLink="@color/result_text"
-                    android:textSize="22sp"
-                    android:paddingLeft="12dip"
-                    android:autoLink="web"/>
-
-          <TextView android:id="@+id/contents_supplement_text_view"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:textColor="@color/result_text"
-                    android:textColorLink="@color/result_text"
-                    android:paddingLeft="12dip"
-                    android:autoLink="web"
-                    android:clickable="true"/>
-
-        </LinearLayout>
-
-      </ScrollView>
-
-    </LinearLayout>
-
-    <LinearLayout android:id="@+id/result_button_view"
-                  android:orientation="horizontal"
-                  android:layout_width="fill_parent"
-                  android:layout_height="wrap_content"
-                  android:gravity="center">
-
-      <Button style="@style/ResultButton"
-              android:visibility="gone"/>
-
-      <Button style="@style/ResultButton"
-              android:visibility="gone"/>
-
-      <Button style="@style/ResultButton"
-              android:visibility="gone"/>
-
-      <Button style="@style/ResultButton"
-              android:visibility="gone"/>
-
-    </LinearLayout>
-
-  </LinearLayout> -->
-
-  <TextView android:id="@+id/status_view"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:layout_gravity="bottom|center_horizontal"
-            android:background="@color/transparent"
-            android:text="@string/msg_default_status"
-            android:textColor="@color/status_text"/>
-
-</merge>

+ 4 - 2
RedAnt Photo/res/layout/activity_locker.xml

@@ -40,10 +40,11 @@
             style="@style/LoginFormContainer"
             android:orientation="vertical" >
 
-            <EditText
+            <AutoCompleteTextView
                 android:id="@+id/name"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
+                android:imeOptions="flagNoExtractUi"
                 android:hint="@string/prompt_Name"
                 android:inputType="textAutoComplete"
                 android:maxLines="1"
@@ -52,11 +53,12 @@
             <EditText
                 android:id="@+id/password"
                 android:layout_width="match_parent"
+                android:imeOptions="flagNoExtractUi"
                 android:layout_height="wrap_content"
                 android:hint="@string/prompt_password"
                 android:imeActionId="@+id/locker"
                 android:imeActionLabel="@string/action_sign_in_short"
-                android:imeOptions="actionUnspecified"
+
                 android:inputType="textPassword"
                 android:maxLines="1"
                 android:singleLine="true" />

+ 6 - 4
RedAnt Photo/res/layout/activity_login.xml

@@ -40,7 +40,7 @@
             style="@style/LoginFormContainer"
             android:orientation="vertical" >
 
-            <EditText
+            <AutoCompleteTextView
                 android:id="@+id/name"
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
@@ -48,7 +48,8 @@
                 android:inputType="textAutoComplete"
                 android:maxLines="1"
                 android:singleLine="true"
-                android:text="admin" />
+                android:imeOptions="flagNoExtractUi"
+                android:text="" />
 
             <EditText
                 android:id="@+id/password"
@@ -57,11 +58,12 @@
                 android:hint="@string/prompt_password"
                 android:imeActionId="@+id/login"
                 android:imeActionLabel="@string/action_sign_in_short"
-                android:imeOptions="actionUnspecified"
+
                 android:inputType="textPassword"
                 android:maxLines="1"
+                android:imeOptions="flagNoExtractUi"
                 android:singleLine="true"
-                android:text="uls1021" />
+                android:text="" />
 
             <Button
                 android:id="@+id/sign_in_button"

+ 6 - 7
RedAnt Photo/res/layout/activity_main1.xml

@@ -9,8 +9,7 @@
         android:layout_height="fill_parent"
         android:layout_alignParentRight="true"
         android:layout_marginRight="0dp"
-        android:layout_marginTop="40dp"
-        android:orientation="vertical" >
+        android:layout_marginTop="40dp" >
 
         <ImageButton
             android:id="@+id/ibtnCapture"
@@ -74,15 +73,15 @@
             android:text="PID:"
             android:textAppearance="?android:attr/textAppearanceLarge" />
 
-        <EditText
-            android:id="@+id/edit"
+        <TextView
+            android:id="@+id/pidval"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
+            android:layout_gravity="bottom"
             android:layout_weight="1"
-            android:ems="8" >
+            android:textAppearance="?android:attr/textAppearanceLarge" >
+        </TextView>
 
-            <requestFocus />
-        </EditText>
     </LinearLayout>
 
     <ImageView

+ 54 - 0
RedAnt Photo/res/layout/activity_photo_preview.xml

@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2007 The Android Open Source Project
+
+     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.
+-->
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
+    android:layout_width="match_parent" 
+    android:layout_height="match_parent"> 
+    
+    <ImageSwitcher android:id="@+id/switcher"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:layout_alignParentTop="true"
+        android:layout_alignParentLeft="true"
+    >
+
+
+    </ImageSwitcher>
+         <HorizontalScrollView
+            android:id="@+id/hsv"
+            android:background="#55000000"
+            android:layout_width="match_parent"
+            android:layout_height="60dp"
+                    android:layout_alignParentBottom="true"
+        android:layout_alignParentLeft="true"
+        
+        android:gravity="center_vertical"
+       
+             >
+
+            <LinearLayout
+                android:id="@+id/linearLayout"
+                android:layout_width="wrap_content"
+                android:layout_height="match_parent"
+                android:orientation="horizontal"
+                 >
+            </LinearLayout>
+        </HorizontalScrollView>
+    
+
+
+</RelativeLayout>
+   

+ 33 - 0
RedAnt Photo/res/layout/activity_search.xml

@@ -0,0 +1,33 @@
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:layout_marginLeft="5dp" 
+    android:layout_marginRight="5dp" 
+
+    tools:context=".SearchActivity" >
+
+    <ListView
+        android:id="@android:id/list"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_alignParentTop="true"
+        android:layout_marginTop="45dp" >
+    </ListView>
+
+    <TextView
+        android:id="@+id/tvalert"
+        android:layout_width="290dp"
+        android:layout_height="wrap_content"
+        android:layout_alignParentRight="true"
+        android:layout_alignParentTop="true"
+        android:layout_marginRight="39dp"
+        android:layout_marginTop="5dp" 
+        android:ellipsize="marquee"
+        android:singleLine="true"
+        android:text=""
+        android:textAppearance="?android:attr/textAppearanceLarge"
+        android:textColor="#eeff0000" />
+
+</RelativeLayout>

+ 8 - 1
RedAnt Photo/res/layout/capture.xml

@@ -201,8 +201,15 @@
       android:id="@+id/textView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
-      android:text="Large Text"
+      android:text=""
       android:layout_gravity="center_horizontal"
       android:textAppearance="?android:attr/textAppearanceLarge" />
+  <Button
+      android:id="@+id/btn_switch"
+      android:layout_width="50dp"
+      android:layout_height="50dp"
+      android:layout_marginRight="20dp"
+      android:layout_gravity="center_vertical|right"
+      android:text="" />
 
 </merge>

+ 50 - 0
RedAnt Photo/res/layout/search_lvitem_edit.xml

@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content" >
+
+    <TextView
+        android:id="@+id/filename"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_alignParentTop="true"
+        android:text="Medium Text"
+        android:textAppearance="?android:attr/textAppearanceMedium" />
+    <TextView
+        android:id="@+id/pid"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_below="@+id/filename"
+        android:layout_marginTop="10dp"
+        android:text="PID:" />
+    
+    <TextView
+        android:id="@+id/err_code"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentRight="true"
+android:layout_alignParentTop="true"
+android:layout_marginTop="2dp"
+        android:text="TextView" />
+    <TextView
+        android:id="@+id/picker"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentRight="true"
+        android:layout_below="@+id/filename"
+        android:layout_marginTop="10dp"
+        android:text="TextView" />
+
+    <TextView
+        android:id="@+id/pidval"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignBaseline="@+id/pid"
+        android:layout_alignBottom="@+id/pid"
+        android:layout_marginLeft="3dp"
+        android:layout_toRightOf="@+id/pid"
+        android:text="TextView" />
+
+</RelativeLayout>

+ 10 - 4
RedAnt Photo/res/menu/main.xml

@@ -1,13 +1,19 @@
 <menu xmlns:android="http://schemas.android.com/apk/res/android" >
 
     <item
-        android:id="@+id/action_settings"
+        android:id="@+id/action_clear"
        
         android:showAsAction="never"
-        android:title="@string/action_settings"/>
+        android:title="@string/action_clear"/>
     <item
-        android:id="@+id/action_orientation"
+        android:id="@+id/action_type_pid"
        
         android:showAsAction="never"
-        android:title="@string/action_orientation"/>
+        android:title="@string/action_type_pid"/>
+     <item
+        android:id="@+id/action_view_queue"
+       
+        android:showAsAction="never"
+        android:title="@string/action_view_queue"/>   
+    
 </menu>

+ 5 - 2
RedAnt Photo/res/values/strings.xml

@@ -16,7 +16,9 @@
     <string name="error_incorrect_password">Not authorized or wrong password</string>
     <string name="error_field_required">This field is required</string>
     <string name="action_settings">Settings</string>
-    <string name="action_orientation">Change Orientation</string>
+    <string name="action_clear">Clear</string>
+    <string name="action_type_pid">Type PID</string>
+    <string name="action_view_queue">View upload queue</string>
     <string name="preferences_name">Settings</string>
     <string name="app_name">RedAnt Photo</string>
     <string name="button_ok">OK</string>
@@ -25,7 +27,7 @@
     <string name="menu_settings">Settings</string>
     <string name="msg_camera_framework_bug">Sorry, the Android camera encountered a problem. You may need to restart the device.</string>
     <string name="msg_default_status">Place a barcode inside the viewfinder rectangle to scan it.</string>
-    <string name="msg_net_resulterror">An error occur on server</string>
+    <string name="msg_user_wrong">Wrong user name or password.</string>
     <string name="msg_net_error">Can not connect to server</string>
     <string name="msg_connection_none">No available connection </string>
     <string name="preferences_actions_title">When a barcode is found\u2026</string>
@@ -61,6 +63,7 @@
     <string name="preferences_supplemental_title">Retrieve more info</string>
     <string name="preferences_vibrate_title">Vibrate</string>
     <string name="title_activity_main_activity1">MainActivity1</string>
+    <string name="title_input_pid">Input PID</string>
     <string name="hello_world">Hello world!</string>
 
 </resources>

+ 12 - 1
RedAnt Photo/src/com/usai/redant/photo/BootReceiver.java

@@ -1,5 +1,7 @@
 package com.usai.redant.photo;
 
+
+
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
@@ -17,7 +19,16 @@ public class BootReceiver extends BroadcastReceiver {
 	public void onReceive(Context context, Intent intent) {
 		// TODO Auto-generated method stub
 		if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
-			// Log.e("hg","收到广播");
+			
+			Intent intentservice = new Intent();
+			intentservice.setClass(context, UploadService.class);
+			if (intent.getExtras() != null)
+				intentservice.putExtras(intent.getExtras());
+			intentservice.setAction(intent.getAction());
+			context.startService(intentservice);
+			
+			
+			// Log.e("hg","锟秸碉拷锟姐播");
 		} else if (intent.getAction().equals(
 				ConnectivityManager.CONNECTIVITY_ACTION)) {
 

+ 836 - 659
RedAnt Photo/src/com/usai/redant/photo/CaptureActivity.java

@@ -22,6 +22,8 @@ import com.google.zxing.Result;
 import com.google.zxing.ResultPoint;
 import com.google.zxing.client.result.ResultParser;
 import com.usai.redant.camera.CameraManager;
+import com.usai.util.dbgUtil;
+
 import android.app.Activity;
 import android.app.AlertDialog;
 import android.content.Intent;
@@ -29,6 +31,7 @@ import android.content.pm.ActivityInfo;
 //import android.content.SharedPreferences;
 import android.graphics.Bitmap;
 import android.graphics.Canvas;
+import android.graphics.Color;
 import android.graphics.Paint;
 import android.os.Bundle;
 import android.os.Handler;
@@ -42,674 +45,848 @@ import android.view.MenuItem;
 import android.view.SurfaceHolder;
 import android.view.SurfaceView;
 import android.view.View;
+import android.view.View.OnClickListener;
 import android.view.Window;
 import android.view.WindowManager;
+import android.widget.Button;
 import android.widget.TextView;
 import java.io.IOException;
 import java.util.Collection;
 import java.util.Map;
+import java.util.Timer;
+import java.util.TimerTask;
 
 /**
- * This activity opens the camera and does the actual scanning on a background thread. It draws a
- * viewfinder to help the user place the barcode correctly, shows feedback as the image processing
- * is happening, and then overlays the results when a scan is successful.
- *
+ * This activity opens the camera and does the actual scanning on a background
+ * thread. It draws a viewfinder to help the user place the barcode correctly,
+ * shows feedback as the image processing is happening, and then overlays the
+ * results when a scan is successful.
+ * 
  * @author dswitkin@google.com (Daniel Switkin)
  * @author Sean Owen
  */
-public final class CaptureActivity extends Activity implements SurfaceHolder.Callback {
-
-  private static final String TAG = CaptureActivity.class.getSimpleName();
-
-//  private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
-//  private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
-
-//  private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
-
-//  public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
-
-//  private static final Collection<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
-//      EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
-//                 ResultMetadataType.SUGGESTED_PRICE,
-//                 ResultMetadataType.ERROR_CORRECTION_LEVEL,
-//                 ResultMetadataType.POSSIBLE_COUNTRY);
-
-  private CameraManager cameraManager;
-  private CaptureActivityHandler handler;
-  private Result savedResultToShow;
-  private ViewfinderView viewfinderView;
-  private TextView statusView;
-//  private View resultView;
-  private Result lastResult;
-  private boolean hasSurface;
-//  private boolean copyToClipboard;
-//  private IntentSource source;
-//  private String sourceUrl;
-//  private ScanFromWebPageManager scanFromWebPageManager;
-  private Collection<BarcodeFormat> decodeFormats;
-  private Map<DecodeHintType,?> decodeHints;
-  private String characterSet;
-//  private HistoryManager historyManager;
-  private InactivityTimer inactivityTimer;
-  private BeepManager beepManager;
-  private AmbientLightManager ambientLightManager;
-
-  ViewfinderView getViewfinderView() {
-    return viewfinderView;
-  }
-
-  public Handler getHandler() {
-    return handler;
-  }
-
-  CameraManager getCameraManager() {
-    return cameraManager;
-  }
-
-  @Override
-  public void onCreate(Bundle icicle) {
-	  Log.i(TAG,"==============>CaptureActivity created!");
-    super.onCreate(icicle);
-
-    Window window = getWindow();
-    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
-    
-    setContentView(R.layout.capture);
-
-    
-    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
-    hasSurface = false;
-//    historyManager = new HistoryManager(this);
-//    historyManager.trimHistory();
-    inactivityTimer = new InactivityTimer(this);
-    beepManager = new BeepManager(this);
-    ambientLightManager = new AmbientLightManager(this);
-
-    PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
-  }
-
-  @Override
-  protected void onResume() {
-    super.onResume();
-
-    // CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
-    // want to open the camera driver and measure the screen size if we're going to show the help on
-    // first launch. That led to bugs where the scanning rectangle was the wrong size and partially
-    // off screen.
-    cameraManager = new CameraManager(getApplication());
-
-    viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
-    viewfinderView.setCameraManager(cameraManager);
-
-//    resultView = findViewById(R.id.result_view);
-    statusView = (TextView) findViewById(R.id.status_view);
-
-    handler = null;
-    lastResult = null;
-
-    resetStatusView();
-
-    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
-    SurfaceHolder surfaceHolder = surfaceView.getHolder();
-    if (hasSurface) {
-      // The activity was paused but not stopped, so the surface still exists. Therefore
-      // surfaceCreated() won't be called, so init the camera here.
-      initCamera(surfaceHolder);
-    } else {
-      // Install the callback and wait for surfaceCreated() to init the camera.
-      surfaceHolder.addCallback(this);
-    }
-
-    beepManager.updatePrefs();
-    ambientLightManager.start(cameraManager);
-
-    inactivityTimer.onResume();
-
-    Intent intent = getIntent();
-
-//    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
-//    copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
-//        && (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
-
-//    source = IntentSource.NONE;
-    decodeFormats = null;
-    characterSet = null;
-
-    if (intent != null) {
-
-      String action = intent.getAction();
-//      String dataString = intent.getDataString();
-
-      if (Intents.Scan.ACTION.equals(action)) {
-
-        // Scan the formats the intent requested, and return the result to the calling activity.
-//        source = IntentSource.NATIVE_APP_INTENT;
-        decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
-        decodeHints = DecodeHintManager.parseDecodeHints(intent);
-
-        if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
-          int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
-          int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
-          if (width > 0 && height > 0) {
-            cameraManager.setManualFramingRect(width, height);
-          }
-        }
-        
-        String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
-        if (customPromptMessage != null) {
-          statusView.setText(customPromptMessage);
-        }
-
-      } 
-//      else if (dataString != null &&
-//                 dataString.contains("http://www.google") &&
-//                 dataString.contains("/m/products/scan")) {
-//
-//        // Scan only products and send the result to mobile Product Search.
-////        source = IntentSource.PRODUCT_SEARCH_LINK;
-//        sourceUrl = dataString;
-//        decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
-//
-//      } 
-//      else if (isZXingURL(dataString)) {
-//
-//        // Scan formats requested in query string (all formats if none specified).
-//        // If a return URL is specified, send the results there. Otherwise, handle it ourselves.
-//        source = IntentSource.ZXING_LINK;
-//        sourceUrl = dataString;
-//        Uri inputUri = Uri.parse(dataString);
-//        scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
-//        decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
-//        // Allow a sub-set of the hints to be specified by the caller.
-//        decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
-//
-//      }
-
-      characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
-
-    }
-  }
-  
-//  private static boolean isZXingURL(String dataString) {
-//    if (dataString == null) {
-//      return false;
-//    }
-//    for (String url : ZXING_URLS) {
-//      if (dataString.startsWith(url)) {
-//        return true;
-//      }
-//    }
-//    return false;
-//  }
-
-  @Override
-  protected void onPause() {
-    if (handler != null) {
-      handler.quitSynchronously();
-      handler = null;
-    }
-    inactivityTimer.onPause();
-    ambientLightManager.stop();
-    cameraManager.closeDriver();
-    if (!hasSurface) {
-      SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
-      SurfaceHolder surfaceHolder = surfaceView.getHolder();
-      surfaceHolder.removeCallback(this);
-    }
-    super.onPause();
-  }
-
-  @Override
-  protected void onDestroy() {
-    inactivityTimer.shutdown();
-    super.onDestroy();
-  }
-
-  @Override
-  public boolean onKeyDown(int keyCode, KeyEvent event) {
-    switch (keyCode) {
-//      case KeyEvent.KEYCODE_BACK:
-//        if (source == IntentSource.NATIVE_APP_INTENT) {
-//          setResult(RESULT_CANCELED);
-//          finish();
-//          return true;
-//        }
-//        if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) {
-//          restartPreviewAfterDelay(0L);
-//          return true;
-//        }
-//        break;
-      case KeyEvent.KEYCODE_FOCUS:
-      case KeyEvent.KEYCODE_CAMERA:
-        // Handle these events so they don't launch the Camera app
-        return true;
-      // Use volume up/down to turn on light
-      case KeyEvent.KEYCODE_VOLUME_DOWN:
-        cameraManager.setTorch(false);
-        return true;
-      case KeyEvent.KEYCODE_VOLUME_UP:
-        cameraManager.setTorch(true);
-        return true;
-    }
-    return super.onKeyDown(keyCode, event);
-  }
-
-  @Override
-  public boolean onCreateOptionsMenu(Menu menu) {
-    MenuInflater menuInflater = getMenuInflater();
-    menuInflater.inflate(R.menu.capture, menu);
-    return super.onCreateOptionsMenu(menu);
-  }
-
-  @Override
-  public boolean onOptionsItemSelected(MenuItem item) {
-    Intent intent = new Intent(Intent.ACTION_VIEW);
-    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
-    switch (item.getItemId()) {
-//      case R.id.menu_share:
-//        intent.setClassName(this, ShareActivity.class.getName());
-//        startActivity(intent);
-//        break;
-//      case R.id.menu_history:
-//        intent.setClassName(this, HistoryActivity.class.getName());
-//        startActivityForResult(intent, HISTORY_REQUEST_CODE);
-//        break;
-      case R.id.menu_settings:
-        intent.setClassName(this, PreferencesActivity.class.getName());
-        startActivity(intent);
-        break;
-//      case R.id.menu_help:
-//        intent.setClassName(this, HelpActivity.class.getName());
-//        startActivity(intent);
-//        break;
-      default:
-        return super.onOptionsItemSelected(item);
-    }
-    return true;
-  }
-
-//  @Override
-//  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
-//    if (resultCode == RESULT_OK) {
-////      if (requestCode == HISTORY_REQUEST_CODE) 
-////      {
-////        int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
-////        if (itemNumber >= 0) {
-////          HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
-////          decodeOrStoreSavedBitmap(null, historyItem.getResult());
-////        }
-////      }
-//    }
-//  }
-
-  private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
-    // Bitmap isn't used yet -- will be used soon
-    if (handler == null) {
-      savedResultToShow = result;
-    } else {
-      if (result != null) {
-        savedResultToShow = result;
-      }
-      if (savedResultToShow != null) {
-        Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
-        handler.sendMessage(message);
-      }
-      savedResultToShow = null;
-    }
-  }
-
-  @Override
-  public void surfaceCreated(SurfaceHolder holder) {
-    if (holder == null) {
-      Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
-    }
-    if (!hasSurface) {
-      hasSurface = true;
-      initCamera(holder);
-    }
-  }
-
-  @Override
-  public void surfaceDestroyed(SurfaceHolder holder) {
-    hasSurface = false;
-  }
-
-  @Override
-  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
-
-  }
-
-  /**
-   * A valid barcode has been found, so give an indication of success and show the results.
-   *
-   * @param rawResult The contents of the barcode.
-   * @param scaleFactor amount by which thumbnail was scaled
-   * @param barcode   A greyscale bitmap of the camera data which was decoded.
-   */
-  public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
-    inactivityTimer.onActivity();
-    lastResult = rawResult;
-    TextView debugTextView = (TextView)findViewById(R.id.textView1);
-    debugTextView.setText(rawResult.getText());
-//    ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
-    Log.i(TAG, "RESULT=========>"+rawResult.getText().toString());
-  //  ParsedResult result = parseResult(rawResult);
-    Log.i(TAG, "HANDLER========>"+ResultParser.parseResult(rawResult).getType().toString());
-    boolean fromLiveScan = barcode != null;
-    if (fromLiveScan) {
-//      historyManager.addHistoryItem(rawResult, resultHandler);
-      // Then not from history, so beep/vibrate and we have an image to draw on
-      beepManager.playBeepSoundAndVibrate();
-      drawResultPoints(barcode, scaleFactor, rawResult);
-    }
-
-    Intent result = new Intent();
-    result.putExtra("pid", rawResult.getText());
-    setResult(Activity.RESULT_OK, result);
-    finish();    
-//    restartPreviewAfterDelay(1000l);
- //   finish();
-//
-//    switch (source) {
-//      case NATIVE_APP_INTENT:
-//      case PRODUCT_SEARCH_LINK:
-//        handleDecodeExternally(rawResult, resultHandler, barcode);
-//        break;
-//      case ZXING_LINK:
-//        if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) {
-//          handleDecodeInternally(rawResult, resultHandler, barcode);
-//        } else {
-//          handleDecodeExternally(rawResult, resultHandler, barcode);
-//        }
-//        break;
-//      case NONE:
-//        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
-//        if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
-//          Toast.makeText(getApplicationContext(),
-//                         getResources().getString(R.string.msg_bulk_mode_scanned) + " (" + rawResult.getText() + ')',
-//                         Toast.LENGTH_SHORT).show();
-//          // Wait a moment or else it will scan the same barcode continuously about 3 times
-//          restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
-//        } else {
-//          handleDecodeInternally(rawResult, resultHandler, barcode);
-//        }
-//        break;
-//    }
-  }
-
-  /**
-   * Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
-   *
-   * @param barcode   A bitmap of the captured image.
-   * @param scaleFactor amount by which thumbnail was scaled
-   * @param rawResult The decoded results which contains the points to draw.
-   */
-  private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
-    ResultPoint[] points = rawResult.getResultPoints();
-    if (points != null && points.length > 0) {
-      Canvas canvas = new Canvas(barcode);
-      Paint paint = new Paint();
-      paint.setColor(getResources().getColor(R.color.result_points));
-      if (points.length == 2) {
-        paint.setStrokeWidth(4.0f);
-        drawLine(canvas, paint, points[0], points[1], scaleFactor);
-      } else if (points.length == 4 &&
-                 (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
-                  rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
-        // Hacky special case -- draw two lines, for the barcode and metadata
-        drawLine(canvas, paint, points[0], points[1], scaleFactor);
-        drawLine(canvas, paint, points[2], points[3], scaleFactor);
-      } else {
-        paint.setStrokeWidth(10.0f);
-        for (ResultPoint point : points) {
-          if (point != null) {
-            canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
-          }
-        }
-      }
-    }
-  }
-
-  private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
-    if (a != null && b != null) {
-      canvas.drawLine(scaleFactor * a.getX(), 
-                      scaleFactor * a.getY(), 
-                      scaleFactor * b.getX(), 
-                      scaleFactor * b.getY(), 
-                      paint);
-    }
-  }
-
-  // Put up our own UI for how to handle the decoded contents.
-//  private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
-//    statusView.setVisibility(View.GONE);
-//    viewfinderView.setVisibility(View.GONE);
-////    resultView.setVisibility(View.VISIBLE);
-//    Log.i(TAG, "RESULT=========>"+rawResult.getText().toString());
-//    Log.i(TAG, "HANDLER========>"+resultHandler.getType().toString());
-
-//    ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
-//    if (barcode == null) {
-//      barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
-//          R.drawable.ic_launcher));
-//    } else {
-//      barcodeImageView.setImageBitmap(barcode);
-//    }
-//
-//    TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
-//    formatTextView.setText(rawResult.getBarcodeFormat().toString());
-//
-//    TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
-//    typeTextView.setText(resultHandler.getType().toString());
-//
-//    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
-//    TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
-//    timeTextView.setText(formatter.format(new Date(rawResult.getTimestamp())));
-//
-//
-//    TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
-//    View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
-//    metaTextView.setVisibility(View.GONE);
-//    metaTextViewLabel.setVisibility(View.GONE);
-//    Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
-//    if (metadata != null) {
-//      StringBuilder metadataText = new StringBuilder(20);
-//      for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
-//        if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
-//          metadataText.append(entry.getValue()).append('\n');
-//        }
-//      }
-//      if (metadataText.length() > 0) {
-//        metadataText.setLength(metadataText.length() - 1);
-//        metaTextView.setText(metadataText);
-//        metaTextView.setVisibility(View.VISIBLE);
-//        metaTextViewLabel.setVisibility(View.VISIBLE);
-//      }
-//    }
-//
-//    TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
-//    CharSequence displayContents = resultHandler.getDisplayContents();
-//    contentsTextView.setText(displayContents);
-//    // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
-//    int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
-//    contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
-//
-//    TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
-//    supplementTextView.setText("");
-//    supplementTextView.setOnClickListener(null);
-////    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
-////        PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
-////      SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
-////                                                     resultHandler.getResult(),
-////                                                     historyManager,
-////                                                     this);
-////    }
-//
-//    int buttonCount = resultHandler.getButtonCount();
-//    ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
-//    buttonView.requestFocus();
-//    for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
-//      TextView button = (TextView) buttonView.getChildAt(x);
-//      if (x < buttonCount) {
-//        button.setVisibility(View.VISIBLE);
-//        button.setText(resultHandler.getButtonText(x));
-//        button.setOnClickListener(new ResultButtonListener(resultHandler, x));
-//      } else {
-//        button.setVisibility(View.GONE);
-//      }
-//    }
-//
-//    if (copyToClipboard && !resultHandler.areContentsSecure()) {
-//      ClipboardInterface.setText(displayContents, this);
-//    }
-//  }
-
-//  // Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
-//  private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
-//
-//    if (barcode != null) {
-//      viewfinderView.drawResultBitmap(barcode);
-//    }
-//
-//    long resultDurationMS;
-//    if (getIntent() == null) {
-//      resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
-//    } else {
-//      resultDurationMS = getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
-//                                                  DEFAULT_INTENT_RESULT_DURATION_MS);
-//    }
-//
-//    if (resultDurationMS > 0) {
-//      String rawResultString = String.valueOf(rawResult);
-//      if (rawResultString.length() > 32) {
-//        rawResultString = rawResultString.substring(0, 32) + " ...";
-//      }
-//      statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " + rawResultString);
-//    }
-//
-//    if (copyToClipboard && !resultHandler.areContentsSecure()) {
-//      CharSequence text = resultHandler.getDisplayContents();
-//      ClipboardInterface.setText(text, this);
-//    }
-//
-//    if (source == IntentSource.NATIVE_APP_INTENT) {
-//      
-//      // Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
-//      // the deprecated intent is retired.
-//      Intent intent = new Intent(getIntent().getAction());
-//      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
-//      intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
-//      intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
-//      byte[] rawBytes = rawResult.getRawBytes();
-//      if (rawBytes != null && rawBytes.length > 0) {
-//        intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
-//      }
-//      Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
-//      if (metadata != null) {
-//        if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
-//          intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
-//                          metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
-//        }
-//        Number orientation = (Number) metadata.get(ResultMetadataType.ORIENTATION);
-//        if (orientation != null) {
-//          intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
-//        }
-//        String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
-//        if (ecLevel != null) {
-//          intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
-//        }
-//        @SuppressWarnings("unchecked")
-//        Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS);
-//        if (byteSegments != null) {
-//          int i = 0;
-//          for (byte[] byteSegment : byteSegments) {
-//            intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment);
-//            i++;
-//          }
-//        }
-//      }
-//      sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
-//      
-//    } else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
-//      
-//      // Reformulate the URL which triggered us into a query, so that the request goes to the same
-//      // TLD as the scan URL.
-//      int end = sourceUrl.lastIndexOf("/scan");
-//      String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing";      
-//      sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
-//      
-//    } else if (source == IntentSource.ZXING_LINK) {
-//
-//      if (scanFromWebPageManager != null && scanFromWebPageManager.isScanFromWebPage()) {
-//        String replyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler);
-//        sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
-//      }
-//      
-//    }
-//  }
-  
-//  private void sendReplyMessage(int id, Object arg, long delayMS) {
-//    if (handler != null) {
-//      Message message = Message.obtain(handler, id, arg);
-//      if (delayMS > 0L) {
-//        handler.sendMessageDelayed(message, delayMS);
-//      } else {
-//        handler.sendMessage(message);
-//      }
-//    }
-//  }
-
-  private void initCamera(SurfaceHolder surfaceHolder) {
-    if (surfaceHolder == null) {
-      throw new IllegalStateException("No SurfaceHolder provided");
-    }
-    if (cameraManager.isOpen()) {
-      Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
-      return;
-    }
-    try {
-      cameraManager.openDriver(surfaceHolder);
-      // Creating the handler starts the preview, which can also throw a RuntimeException.
-      if (handler == null) {
-        handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
-      }
-      decodeOrStoreSavedBitmap(null, null);
-    } catch (IOException ioe) {
-      Log.w(TAG, ioe);
-      displayFrameworkBugMessageAndExit();
-    } catch (RuntimeException e) {
-      // Barcode Scanner has seen crashes in the wild of this variety:
-      // java.?lang.?RuntimeException: Fail to connect to camera service
-      Log.w(TAG, "Unexpected error initializing camera", e);
-      displayFrameworkBugMessageAndExit();
-    }
-  }
-
-  private void displayFrameworkBugMessageAndExit() {
-    AlertDialog.Builder builder = new AlertDialog.Builder(this);
-    builder.setTitle(getString(R.string.app_name));
-    builder.setMessage(getString(R.string.msg_camera_framework_bug));
-    builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
-    builder.setOnCancelListener(new FinishListener(this));
-    builder.show();
-  }
-
-  public void restartPreviewAfterDelay(long delayMS) {
-    if (handler != null) {
-      handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
-    }
-    resetStatusView();
-  }
-
-  private void resetStatusView() {
-//    resultView.setVisibility(View.GONE);
-    statusView.setText(R.string.msg_default_status);
-    statusView.setVisibility(View.VISIBLE);
-    viewfinderView.setVisibility(View.VISIBLE);
-    lastResult = null;
-  }
-
-  public void drawViewfinder() {
-    viewfinderView.drawViewfinder();
-  }
+public final class CaptureActivity extends Activity implements
+		SurfaceHolder.Callback
+{
+
+	private static final String			TAG	= CaptureActivity.class
+													.getSimpleName();
+
+	// private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
+	// private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
+
+	// private static final String[] ZXING_URLS = {
+	// "http://zxing.appspot.com/scan", "zxing://scan/" };
+
+	// public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
+
+	// private static final Collection<ResultMetadataType>
+	// DISPLAYABLE_METADATA_TYPES =
+	// EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
+	// ResultMetadataType.SUGGESTED_PRICE,
+	// ResultMetadataType.ERROR_CORRECTION_LEVEL,
+	// ResultMetadataType.POSSIBLE_COUNTRY);
+
+	private CameraManager				cameraManager;
+	private CaptureActivityHandler		handler;
+	private Result						savedResultToShow;
+	private ViewfinderView				viewfinderView;
+	private TextView					statusView;
+	// private View resultView;
+	private Result						lastResult;
+	private boolean						hasSurface;
+	// private boolean copyToClipboard;
+	// private IntentSource source;
+	// private String sourceUrl;
+	// private ScanFromWebPageManager scanFromWebPageManager;
+	private Collection<BarcodeFormat>	decodeFormats;
+	private Map<DecodeHintType, ?>		decodeHints;
+	private String						characterSet;
+	// private HistoryManager historyManager;
+	private InactivityTimer				inactivityTimer;
+	private BeepManager					beepManager;
+	private AmbientLightManager			ambientLightManager;
+
+
+
+	ViewfinderView getViewfinderView()
+	{
+		return viewfinderView;
+	}
+
+	public Handler getHandler()
+	{
+		return handler;
+	}
+
+	CameraManager getCameraManager()
+	{
+		return cameraManager;
+	}
+
+	Button	swith_button;
+
+	@Override
+	public void onCreate(Bundle icicle)
+	{
+		dbgUtil.Logd(TAG, "==============>CaptureActivity created!");
+
+		super.onCreate(icicle);
+
+		Window window = getWindow();
+		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+
+		setContentView(R.layout.capture);
+
+		swith_button = (Button) findViewById(R.id.btn_switch);
+		swith_button.setTag("false");
+		swith_button.setBackgroundColor(getResources().getColor(
+				R.color.message_fail));
+		swith_button.setOnClickListener(new OnClickListener()
+		{
+
+			@Override
+			public void onClick(View v)
+			{
+
+				// inactivityTimer.onPause();
+
+				if (Boolean.parseBoolean(v.getTag().toString()) == false)
+				{
+					// inactivityTimer.onResume();
+					v.setTag("true");
+					v.setBackgroundColor(getResources().getColor(
+							R.color.message_success));
+				}
+				else
+				{
+
+					// inactivityTimer.onPause();
+					v.setTag("false");
+					v.setBackgroundColor(getResources().getColor(
+							R.color.message_fail));
+				}
+
+			}
+		});
+
+		// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+		hasSurface = false;
+		// historyManager = new HistoryManager(this);
+		// historyManager.trimHistory();
+		inactivityTimer = new InactivityTimer(this);
+		beepManager = new BeepManager(this);
+		ambientLightManager = new AmbientLightManager(this);
+
+		// PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
+
+
+		Log.e(TAG, "finish oncreate");
+	}
+	
+	@Override
+	protected void onResume()
+	{
+		super.onResume();
+
+		// CameraManager must be initialized here, not in onCreate(). This is
+		// necessary because we don't
+		// want to open the camera driver and measure the screen size if we're
+		// going to show the help on
+		// first launch. That led to bugs where the scanning rectangle was the
+		// wrong size and partially
+		// off screen.
+		cameraManager = new CameraManager(getApplication());
+
+		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
+		viewfinderView.setCameraManager(cameraManager);
+
+		// resultView = findViewById(R.id.result_view);
+		statusView = (TextView) findViewById(R.id.status_view);
+
+		handler = null;
+		lastResult = null;
+
+		resetStatusView();
+
+		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
+		SurfaceHolder surfaceHolder = surfaceView.getHolder();
+		if (hasSurface)
+		{
+			// The activity was paused but not stopped, so the surface still
+			// exists. Therefore
+			// surfaceCreated() won't be called, so init the camera here.
+			initCamera(surfaceHolder);
+		}
+		else
+		{
+			// Install the callback and wait for surfaceCreated() to init the
+			// camera.
+			surfaceHolder.addCallback(this);
+		}
+
+		beepManager.updatePrefs();
+		ambientLightManager.start(cameraManager);
+
+		inactivityTimer.onResume();
+
+		Intent intent = getIntent();
+
+		// SharedPreferences prefs =
+		// PreferenceManager.getDefaultSharedPreferences(this);
+		// copyToClipboard =
+		// prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
+		// && (intent == null ||
+		// intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
+
+		// source = IntentSource.NONE;
+		decodeFormats = null;
+		characterSet = null;
+
+		if (intent != null)
+		{
+
+			String action = intent.getAction();
+			// String dataString = intent.getDataString();
+
+			if (Intents.Scan.ACTION.equals(action))
+			{
+
+				// Scan the formats the intent requested, and return the result
+				// to the calling activity.
+				// source = IntentSource.NATIVE_APP_INTENT;
+				decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
+				decodeHints = DecodeHintManager.parseDecodeHints(intent);
+
+				if (intent.hasExtra(Intents.Scan.WIDTH)
+						&& intent.hasExtra(Intents.Scan.HEIGHT))
+				{
+					int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
+					int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
+					if (width > 0 && height > 0)
+					{
+						cameraManager.setManualFramingRect(width, height);
+					}
+				}
+
+				String customPromptMessage = intent
+						.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
+				if (customPromptMessage != null)
+				{
+					statusView.setText(customPromptMessage);
+				}
+
+			}
+			// else if (dataString != null &&
+			// dataString.contains("http://www.google") &&
+			// dataString.contains("/m/products/scan")) {
+			//
+			// // Scan only products and send the result to mobile Product
+			// Search.
+			// // source = IntentSource.PRODUCT_SEARCH_LINK;
+			// sourceUrl = dataString;
+			// decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
+			//
+			// }
+			// else if (isZXingURL(dataString)) {
+			//
+			// // Scan formats requested in query string (all formats if none
+			// specified).
+			// // If a return URL is specified, send the results there.
+			// Otherwise, handle it ourselves.
+			// source = IntentSource.ZXING_LINK;
+			// sourceUrl = dataString;
+			// Uri inputUri = Uri.parse(dataString);
+			// scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
+			// decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
+			// // Allow a sub-set of the hints to be specified by the caller.
+			// decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
+			//
+			// }
+
+			characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
+
+		}
+	}
+
+	// private static boolean isZXingURL(String dataString) {
+	// if (dataString == null) {
+	// return false;
+	// }
+	// for (String url : ZXING_URLS) {
+	// if (dataString.startsWith(url)) {
+	// return true;
+	// }
+	// }
+	// return false;
+	// }
+
+	@Override
+	protected void onPause()
+	{
+		if (handler != null)
+		{
+			handler.quitSynchronously();
+			handler = null;
+		}
+		inactivityTimer.onPause();
+		ambientLightManager.stop();
+		cameraManager.closeDriver();
+		if (!hasSurface)
+		{
+			SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
+			SurfaceHolder surfaceHolder = surfaceView.getHolder();
+			surfaceHolder.removeCallback(this);
+		}
+		super.onPause();
+	}
+
+	@Override
+	protected void onDestroy()
+	{
+		inactivityTimer.shutdown();
+		super.onDestroy();
+	}
+
+	@Override
+	public boolean onKeyDown(int keyCode, KeyEvent event)
+	{
+		switch (keyCode)
+		{
+		// case KeyEvent.KEYCODE_BACK:
+		// if (source == IntentSource.NATIVE_APP_INTENT) {
+		// setResult(RESULT_CANCELED);
+		// finish();
+		// return true;
+		// }
+		// if ((source == IntentSource.NONE || source ==
+		// IntentSource.ZXING_LINK) && lastResult != null) {
+		// restartPreviewAfterDelay(0L);
+		// return true;
+		// }
+		// break;
+			case KeyEvent.KEYCODE_FOCUS:
+			case KeyEvent.KEYCODE_CAMERA:
+				// Handle these events so they don't launch the Camera app
+				return true;
+				// Use volume up/down to turn on light
+			case KeyEvent.KEYCODE_VOLUME_DOWN:
+				cameraManager.setTorch(false);
+				return true;
+			case KeyEvent.KEYCODE_VOLUME_UP:
+				cameraManager.setTorch(true);
+				return true;
+		}
+		return super.onKeyDown(keyCode, event);
+	}
+
+	@Override
+	public boolean onCreateOptionsMenu(Menu menu)
+	{
+		MenuInflater menuInflater = getMenuInflater();
+		menuInflater.inflate(R.menu.capture, menu);
+		return super.onCreateOptionsMenu(menu);
+	}
+
+	@Override
+	public boolean onOptionsItemSelected(MenuItem item)
+	{
+		Intent intent = new Intent(Intent.ACTION_VIEW);
+		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
+		switch (item.getItemId())
+		{
+		// case R.id.menu_share:
+		// intent.setClassName(this, ShareActivity.class.getName());
+		// startActivity(intent);
+		// break;
+		// case R.id.menu_history:
+		// intent.setClassName(this, HistoryActivity.class.getName());
+		// startActivityForResult(intent, HISTORY_REQUEST_CODE);
+		// break;
+			case R.id.menu_settings:
+				intent.setClassName(this, PreferencesActivity.class.getName());
+				startActivity(intent);
+				break;
+			// case R.id.menu_help:
+			// intent.setClassName(this, HelpActivity.class.getName());
+			// startActivity(intent);
+			// break;
+			default:
+				return super.onOptionsItemSelected(item);
+		}
+		return true;
+	}
+
+	// @Override
+	// public void onActivityResult(int requestCode, int resultCode, Intent
+	// intent) {
+	// if (resultCode == RESULT_OK) {
+	// // if (requestCode == HISTORY_REQUEST_CODE)
+	// // {
+	// // int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
+	// // if (itemNumber >= 0) {
+	// // HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
+	// // decodeOrStoreSavedBitmap(null, historyItem.getResult());
+	// // }
+	// // }
+	// }
+	// }
+
+	private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result)
+	{
+		// Bitmap isn't used yet -- will be used soon
+		if (handler == null)
+		{
+			savedResultToShow = result;
+		}
+		else
+		{
+			if (result != null)
+			{
+				savedResultToShow = result;
+			}
+			if (savedResultToShow != null)
+			{
+				Message message = Message.obtain(handler,
+						R.id.decode_succeeded, savedResultToShow);
+				handler.sendMessage(message);
+			}
+			savedResultToShow = null;
+		}
+	}
+
+	@Override
+	public void surfaceCreated(SurfaceHolder holder)
+	{
+		if (holder == null)
+		{
+			Log.e(TAG,
+					"*** WARNING *** surfaceCreated() gave us a null surface!");
+		}
+		if (!hasSurface)
+		{
+			hasSurface = true;
+			initCamera(holder);
+		}
+	}
+
+	@Override
+	public void surfaceDestroyed(SurfaceHolder holder)
+	{
+		hasSurface = false;
+	}
+
+	@Override
+	public void surfaceChanged(SurfaceHolder holder, int format, int width,
+			int height)
+	{
+
+	}
+
+	/**
+	 * A valid barcode has been found, so give an indication of success and show
+	 * the results.
+	 * 
+	 * @param rawResult
+	 *            The contents of the barcode.
+	 * @param scaleFactor
+	 *            amount by which thumbnail was scaled
+	 * @param barcode
+	 *            A greyscale bitmap of the camera data which was decoded.
+	 */
+	public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor)
+	{
+		String tag = swith_button.getTag().toString();
+		if (Boolean.parseBoolean(tag) == false)
+		{
+			restartPreviewAfterDelay(0L);
+			return;
+		}
+		inactivityTimer.onActivity();
+		lastResult = rawResult;
+		TextView debugTextView = (TextView) findViewById(R.id.textView1);
+		debugTextView.setText(rawResult.getText());
+		// ResultHandler resultHandler =
+		// ResultHandlerFactory.makeResultHandler(this, rawResult);
+		Log.i(TAG, "RESULT=========>" + rawResult.getText().toString());
+		// ParsedResult result = parseResult(rawResult);
+		Log.i(TAG, "HANDLER========>"
+				+ ResultParser.parseResult(rawResult).getType().toString());
+		boolean fromLiveScan = barcode != null;
+		if (fromLiveScan)
+		{
+			// historyManager.addHistoryItem(rawResult, resultHandler);
+			// Then not from history, so beep/vibrate and we have an image to
+			// draw on
+			beepManager.playBeepSoundAndVibrate();
+			// drawResultPoints(barcode, scaleFactor, rawResult);
+		}
+
+		Intent result = new Intent();
+		result.putExtra("pid", rawResult.getText());
+		setResult(Activity.RESULT_OK, result);
+		finish();
+		// restartPreviewAfterDelay(1000l);
+		// finish();
+		//
+		// switch (source) {
+		// case NATIVE_APP_INTENT:
+		// case PRODUCT_SEARCH_LINK:
+		// handleDecodeExternally(rawResult, resultHandler, barcode);
+		// break;
+		// case ZXING_LINK:
+		// if (scanFromWebPageManager == null ||
+		// !scanFromWebPageManager.isScanFromWebPage()) {
+		// handleDecodeInternally(rawResult, resultHandler, barcode);
+		// } else {
+		// handleDecodeExternally(rawResult, resultHandler, barcode);
+		// }
+		// break;
+		// case NONE:
+		// SharedPreferences prefs =
+		// PreferenceManager.getDefaultSharedPreferences(this);
+		// if (fromLiveScan &&
+		// prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
+		// Toast.makeText(getApplicationContext(),
+		// getResources().getString(R.string.msg_bulk_mode_scanned) + " (" +
+		// rawResult.getText() + ')',
+		// Toast.LENGTH_SHORT).show();
+		// // Wait a moment or else it will scan the same barcode continuously
+		// about 3 times
+		// restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
+		// } else {
+		// handleDecodeInternally(rawResult, resultHandler, barcode);
+		// }
+		// break;
+		// }
+	}
+
+	/**
+	 * Superimpose a line for 1D or dots for 2D to highlight the key features of
+	 * the barcode.
+	 * 
+	 * @param barcode
+	 *            A bitmap of the captured image.
+	 * @param scaleFactor
+	 *            amount by which thumbnail was scaled
+	 * @param rawResult
+	 *            The decoded results which contains the points to draw.
+	 */
+	// private void drawResultPoints(Bitmap barcode, float scaleFactor,
+	// Result rawResult)
+	// {
+	// ResultPoint[] points = rawResult.getResultPoints();
+	// if (points != null && points.length > 0)
+	// {
+	// Canvas canvas = new Canvas(barcode);
+	// Paint paint = new Paint();
+	// paint.setColor(getResources().getColor(R.color.result_points));
+	// if (points.length == 2)
+	// {
+	// paint.setStrokeWidth(4.0f);
+	// drawLine(canvas, paint, points[0], points[1], scaleFactor);
+	// }
+	// else if (points.length == 4
+	// && (rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A || rawResult
+	// .getBarcodeFormat() == BarcodeFormat.EAN_13))
+	// {
+	// // Hacky special case -- draw two lines, for the barcode and
+	// // metadata
+	// drawLine(canvas, paint, points[0], points[1], scaleFactor);
+	// drawLine(canvas, paint, points[2], points[3], scaleFactor);
+	// }
+	// else
+	// {
+	// paint.setStrokeWidth(10.0f);
+	// for (ResultPoint point : points)
+	// {
+	// if (point != null)
+	// {
+	// canvas.drawPoint(scaleFactor * point.getX(),
+	// scaleFactor * point.getY(), paint);
+	// }
+	// }
+	// }
+	// }
+	// }
+
+	private static void drawLine(Canvas canvas, Paint paint, ResultPoint a,
+			ResultPoint b, float scaleFactor)
+	{
+		if (a != null && b != null)
+		{
+			canvas.drawLine(scaleFactor * a.getX(), scaleFactor * a.getY(),
+					scaleFactor * b.getX(), scaleFactor * b.getY(), paint);
+		}
+	}
+
+	// Put up our own UI for how to handle the decoded contents.
+	// private void handleDecodeInternally(Result rawResult, ResultHandler
+	// resultHandler, Bitmap barcode) {
+	// statusView.setVisibility(View.GONE);
+	// viewfinderView.setVisibility(View.GONE);
+	// // resultView.setVisibility(View.VISIBLE);
+	// Log.i(TAG, "RESULT=========>"+rawResult.getText().toString());
+	// Log.i(TAG, "HANDLER========>"+resultHandler.getType().toString());
+
+	// ImageView barcodeImageView = (ImageView)
+	// findViewById(R.id.barcode_image_view);
+	// if (barcode == null) {
+	// barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
+	// R.drawable.ic_launcher));
+	// } else {
+	// barcodeImageView.setImageBitmap(barcode);
+	// }
+	//
+	// TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
+	// formatTextView.setText(rawResult.getBarcodeFormat().toString());
+	//
+	// TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
+	// typeTextView.setText(resultHandler.getType().toString());
+	//
+	// DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,
+	// DateFormat.SHORT);
+	// TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
+	// timeTextView.setText(formatter.format(new
+	// Date(rawResult.getTimestamp())));
+	//
+	//
+	// TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
+	// View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
+	// metaTextView.setVisibility(View.GONE);
+	// metaTextViewLabel.setVisibility(View.GONE);
+	// Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
+	// if (metadata != null) {
+	// StringBuilder metadataText = new StringBuilder(20);
+	// for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
+	// if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
+	// metadataText.append(entry.getValue()).append('\n');
+	// }
+	// }
+	// if (metadataText.length() > 0) {
+	// metadataText.setLength(metadataText.length() - 1);
+	// metaTextView.setText(metadataText);
+	// metaTextView.setVisibility(View.VISIBLE);
+	// metaTextViewLabel.setVisibility(View.VISIBLE);
+	// }
+	// }
+	//
+	// TextView contentsTextView = (TextView)
+	// findViewById(R.id.contents_text_view);
+	// CharSequence displayContents = resultHandler.getDisplayContents();
+	// contentsTextView.setText(displayContents);
+	// // Crudely scale betweeen 22 and 32 -- bigger font for shorter text
+	// int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
+	// contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
+	//
+	// TextView supplementTextView = (TextView)
+	// findViewById(R.id.contents_supplement_text_view);
+	// supplementTextView.setText("");
+	// supplementTextView.setOnClickListener(null);
+	// // if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
+	// // PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
+	// // SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
+	// // resultHandler.getResult(),
+	// // historyManager,
+	// // this);
+	// // }
+	//
+	// int buttonCount = resultHandler.getButtonCount();
+	// ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
+	// buttonView.requestFocus();
+	// for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
+	// TextView button = (TextView) buttonView.getChildAt(x);
+	// if (x < buttonCount) {
+	// button.setVisibility(View.VISIBLE);
+	// button.setText(resultHandler.getButtonText(x));
+	// button.setOnClickListener(new ResultButtonListener(resultHandler, x));
+	// } else {
+	// button.setVisibility(View.GONE);
+	// }
+	// }
+	//
+	// if (copyToClipboard && !resultHandler.areContentsSecure()) {
+	// ClipboardInterface.setText(displayContents, this);
+	// }
+	// }
+
+	// // Briefly show the contents of the barcode, then handle the result
+	// outside Barcode Scanner.
+	// private void handleDecodeExternally(Result rawResult, ResultHandler
+	// resultHandler, Bitmap barcode) {
+	//
+	// if (barcode != null) {
+	// viewfinderView.drawResultBitmap(barcode);
+	// }
+	//
+	// long resultDurationMS;
+	// if (getIntent() == null) {
+	// resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
+	// } else {
+	// resultDurationMS =
+	// getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
+	// DEFAULT_INTENT_RESULT_DURATION_MS);
+	// }
+	//
+	// if (resultDurationMS > 0) {
+	// String rawResultString = String.valueOf(rawResult);
+	// if (rawResultString.length() > 32) {
+	// rawResultString = rawResultString.substring(0, 32) + " ...";
+	// }
+	// statusView.setText(getString(resultHandler.getDisplayTitle()) + " : " +
+	// rawResultString);
+	// }
+	//
+	// if (copyToClipboard && !resultHandler.areContentsSecure()) {
+	// CharSequence text = resultHandler.getDisplayContents();
+	// ClipboardInterface.setText(text, this);
+	// }
+	//
+	// if (source == IntentSource.NATIVE_APP_INTENT) {
+	//
+	// // Hand back whatever action they requested - this can be changed to
+	// Intents.Scan.ACTION when
+	// // the deprecated intent is retired.
+	// Intent intent = new Intent(getIntent().getAction());
+	// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
+	// intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
+	// intent.putExtra(Intents.Scan.RESULT_FORMAT,
+	// rawResult.getBarcodeFormat().toString());
+	// byte[] rawBytes = rawResult.getRawBytes();
+	// if (rawBytes != null && rawBytes.length > 0) {
+	// intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
+	// }
+	// Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
+	// if (metadata != null) {
+	// if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
+	// intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
+	// metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
+	// }
+	// Number orientation = (Number)
+	// metadata.get(ResultMetadataType.ORIENTATION);
+	// if (orientation != null) {
+	// intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
+	// }
+	// String ecLevel = (String)
+	// metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
+	// if (ecLevel != null) {
+	// intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
+	// }
+	// @SuppressWarnings("unchecked")
+	// Iterable<byte[]> byteSegments = (Iterable<byte[]>)
+	// metadata.get(ResultMetadataType.BYTE_SEGMENTS);
+	// if (byteSegments != null) {
+	// int i = 0;
+	// for (byte[] byteSegment : byteSegments) {
+	// intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i,
+	// byteSegment);
+	// i++;
+	// }
+	// }
+	// }
+	// sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
+	//
+	// } else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
+	//
+	// // Reformulate the URL which triggered us into a query, so that the
+	// request goes to the same
+	// // TLD as the scan URL.
+	// int end = sourceUrl.lastIndexOf("/scan");
+	// String replyURL = sourceUrl.substring(0, end) + "?q=" +
+	// resultHandler.getDisplayContents() + "&source=zxing";
+	// sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
+	//
+	// } else if (source == IntentSource.ZXING_LINK) {
+	//
+	// if (scanFromWebPageManager != null &&
+	// scanFromWebPageManager.isScanFromWebPage()) {
+	// String replyURL = scanFromWebPageManager.buildReplyURL(rawResult,
+	// resultHandler);
+	// sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
+	// }
+	//
+	// }
+	// }
+
+	// private void sendReplyMessage(int id, Object arg, long delayMS) {
+	// if (handler != null) {
+	// Message message = Message.obtain(handler, id, arg);
+	// if (delayMS > 0L) {
+	// handler.sendMessageDelayed(message, delayMS);
+	// } else {
+	// handler.sendMessage(message);
+	// }
+	// }
+	// }
+
+	private void initCamera(SurfaceHolder surfaceHolder)
+	{
+		if (surfaceHolder == null)
+		{
+			throw new IllegalStateException("No SurfaceHolder provided");
+		}
+		if (cameraManager.isOpen())
+		{
+			Log.w(TAG,
+					"initCamera() while already open -- late SurfaceView callback?");
+			return;
+		}
+		try
+		{
+			cameraManager.openDriver(surfaceHolder);
+			// Creating the handler starts the preview, which can also throw a
+			// RuntimeException.
+			if (handler == null)
+			{
+				handler = new CaptureActivityHandler(this, decodeFormats,
+						decodeHints, characterSet, cameraManager);
+			}
+			decodeOrStoreSavedBitmap(null, null);
+		}
+		catch (IOException ioe)
+		{
+			Log.w(TAG, ioe);
+			displayFrameworkBugMessageAndExit();
+		}
+		catch (RuntimeException e)
+		{
+			// Barcode Scanner has seen crashes in the wild of this variety:
+			// java.?lang.?RuntimeException: Fail to connect to camera service
+			Log.w(TAG, "Unexpected error initializing camera", e);
+			displayFrameworkBugMessageAndExit();
+		}
+	}
+
+	private void displayFrameworkBugMessageAndExit()
+	{
+		AlertDialog.Builder builder = new AlertDialog.Builder(this);
+		builder.setTitle(getString(R.string.app_name));
+		builder.setMessage(getString(R.string.msg_camera_framework_bug));
+		builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
+		builder.setOnCancelListener(new FinishListener(this));
+		builder.show();
+	}
+
+	public void restartPreviewAfterDelay(long delayMS)
+	{
+		if (handler != null)
+		{
+			handler.sendEmptyMessageDelayed(R.id.decode_failed, delayMS);
+		}
+		resetStatusView();
+	}
+
+	private void resetStatusView()
+	{
+		// resultView.setVisibility(View.GONE);
+		statusView.setText(R.string.msg_default_status);
+		statusView.setVisibility(View.VISIBLE);
+		viewfinderView.setVisibility(View.VISIBLE);
+		lastResult = null;
+	}
+
+	public void drawViewfinder()
+	{
+		viewfinderView.drawViewfinder();
+	}
 }

+ 586 - 114
RedAnt Photo/src/com/usai/redant/photo/LockerActivity.java

@@ -1,5 +1,8 @@
 package com.usai.redant.photo;
 
+import com.usai.redant.photo.LoginActivity.UserLoginTask;
+import com.usai.util.Crypto;
+import com.usai.util.Network;
 import com.usai.util.dbUtil;
 
 import android.animation.Animator;
@@ -15,66 +18,99 @@ import android.os.Build;
 import android.os.Bundle;
 import android.text.TextUtils;
 import android.util.Log;
+import android.view.Gravity;
 import android.view.KeyEvent;
 import android.view.Menu;
 import android.view.View;
 import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputMethodManager;
+import android.widget.ArrayAdapter;
+import android.widget.AutoCompleteTextView;
 import android.widget.EditText;
 import android.widget.TextView;
+import android.widget.Toast;
 
 /**
  * Activity which displays a login screen to the user, offering registration as
  * well.
  */
-public class LockerActivity extends Activity {
+public class LockerActivity extends Activity
+{
+	// public static final int ERR_CODE_NONE = 0;
+	// public static final int ERR_CODE_NULLRETURN = 1;
+	// public static final int ERR_CODE_NONETWORK = 2;
+
 	/**
 	 * A dummy authentication store containing known user names and passwords.
 	 * TODO: remove after connecting to a real authentication system.
 	 */
-//	private static final String[] DUMMY_CREDENTIALS = new String[] {
-//			"foo@example.com:hello", "bar@example.com:world" };
+	// private static final String[] DUMMY_CREDENTIALS = new String[] {
+	// "foo@example.com:hello", "bar@example.com:world" };
 
 	/**
 	 * The default email to populate the email field with.
 	 */
-	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
+	// public static final String EXTRA_EMAIL =
+	// "com.example.android.authenticatordemo.extra.EMAIL";
+	// public static final String EXTRA_USER = "Login_User";
 
 	/**
 	 * Keep track of the login task to ensure we can cancel it if requested.
 	 */
-	private UserLoginTask mAuthTask = null;
-
-	SQLiteDatabase m_db;
+	private UserLoginTask	mAuthTask	= null;
+	ArrayAdapter<String>		adapter							= null;
+	// SQLiteDatabase m_db;
 	// Values for email and password at the time of the login attempt.
-	private String m_sName;
-	private String m_sPassword;
+	private String			m_sName;
+	private String			m_sPassword;
 
 	// UI references.
-	private EditText m_etName;
-	private EditText m_etPassword;
-	private View mLoginFormView;
-	private View mLoginStatusView;
-	private TextView mLoginStatusMessageView;
+	private AutoCompleteTextView		m_etName;
+	private EditText		m_etPassword;
+	private View			mLoginFormView;
+	private View			mLoginStatusView;
+	private TextView		mLoginStatusMessageView;
+
+//	@Override
+//	protected void onDestroy()
+//	{
+//		// TODO Auto-generated method stub
+////		dbUtil.CloseDB(m_db);
+////		super.onDestroy();
+//
+//	}
 
 	@Override
-	protected void onCreate(Bundle savedInstanceState) {
+	protected void onCreate(Bundle savedInstanceState)
+	{
 		super.onCreate(savedInstanceState);
+
 		setContentView(R.layout.activity_locker);
 
 		// Set up the login form.
-//		m_sName = getIntent().getStringExtra(EXTRA_USER);
-		m_etName = (EditText) findViewById(R.id.name);
-		
-//		m_etName.setText(m_sName);
+		// m_sName = getIntent().getStringExtra(EXTRA_USER);
+		m_etName = (AutoCompleteTextView) findViewById(R.id.name);
+
+		// m_etName.setText(m_sName);
 
 		m_etPassword = (EditText) findViewById(R.id.password);
 		m_etPassword
-				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
+				.setOnEditorActionListener(new TextView.OnEditorActionListener()
+				{
 					@Override
 					public boolean onEditorAction(TextView textView, int id,
-							KeyEvent keyEvent) {
-Log.d("onEditorAction", "id="+id+" keyevent="+keyEvent);
-						if (id == R.id.locker || id == EditorInfo.IME_ACTION_DONE ) {
+							KeyEvent keyEvent)
+					{
+						if (id == R.id.login
+								|| id == EditorInfo.IME_ACTION_DONE)
+						{
+							InputMethodManager inputMethodManager = (InputMethodManager) getApplicationContext()
+									.getSystemService(INPUT_METHOD_SERVICE);
+
+							// EditText editText =
+							// (EditText)findViewById(R.id.xxxx);
+							inputMethodManager.hideSoftInputFromWindow(
+									m_etPassword.getWindowToken(), 0); // 锟斤拷锟斤拷
 							attemptLogin();
 							return true;
 						}
@@ -87,41 +123,37 @@ Log.d("onEditorAction", "id="+id+" keyevent="+keyEvent);
 		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
 
 		findViewById(R.id.sign_in_button).setOnClickListener(
-				new View.OnClickListener() {
+				new View.OnClickListener()
+				{
 					@Override
-					public void onClick(View view) {
+					public void onClick(View view)
+					{
 						attemptLogin();
 					}
 				});
+		adapter = new ArrayAdapter<String>(this,
+				android.R.layout.simple_list_item_1,
+				dbUtil.get_userlist());
+		m_etName.setAdapter(adapter);
 	}
 
 	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
+	public boolean onCreateOptionsMenu(Menu menu)
+	{
 		super.onCreateOptionsMenu(menu);
-		getMenuInflater().inflate(R.menu.locker, menu);
+		getMenuInflater().inflate(R.menu.login, menu);
 		return true;
 	}
 
-	@Override
-	public boolean onKeyDown(int keyCode, KeyEvent event) {
-        if(keyCode == KeyEvent.KEYCODE_BACK){
-//            Intent myIntent = new Intent();
-//            myIntent = new Intent(EditActivity.this, tabActivity.class);
-//            startActivity(myIntent);
-//            this.finish();
-        	return true;
-        }
-        return super.onKeyDown(keyCode, event);
-
-	}
-
 	/**
 	 * Attempts to sign in or register the account specified by the login form.
 	 * If there are form errors (invalid email, missing fields, etc.), the
 	 * errors are presented and no actual login attempt is made.
 	 */
-	public void attemptLogin() {
-		if (mAuthTask != null) {
+	public void attemptLogin()
+	{
+		if (mAuthTask != null)
+		{
 			return;
 		}
 
@@ -137,18 +169,22 @@ Log.d("onEditorAction", "id="+id+" keyevent="+keyEvent);
 		View focusView = null;
 
 		// Check for a valid password.
-		if (TextUtils.isEmpty(m_sPassword)) {
+		if (TextUtils.isEmpty(m_sPassword))
+		{
 			m_etPassword.setError(getString(R.string.error_field_required));
 			focusView = m_etPassword;
 			cancel = true;
-		} else if (m_sPassword.length() < 4) {
+		}
+		else if (m_sPassword.length() < 4)
+		{
 			m_etPassword.setError(getString(R.string.error_invalid_password));
 			focusView = m_etPassword;
 			cancel = true;
 		}
 
 		// Check for a valid user name.
-		if (TextUtils.isEmpty(m_sName)) {
+		if (TextUtils.isEmpty(m_sName))
+		{
 			m_etName.setError(getString(R.string.error_field_required));
 			focusView = m_etName;
 			cancel = true;
@@ -159,11 +195,14 @@ Log.d("onEditorAction", "id="+id+" keyevent="+keyEvent);
 		// cancel = true;
 		// }
 
-		if (cancel) {
+		if (cancel)
+		{
 			// There was an error; don't attempt login and focus the first
 			// form field with an error.
 			focusView.requestFocus();
-		} else {
+		}
+		else
+		{
 			// Show a progress spinner, and kick off a background task to
 			// perform the user login attempt.
 			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
@@ -177,20 +216,24 @@ Log.d("onEditorAction", "id="+id+" keyevent="+keyEvent);
 	 * Shows the progress UI and hides the login form.
 	 */
 	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
-	private void showProgress(final boolean show) {
+	private void showProgress(final boolean show)
+	{
 		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
 		// for very easy animations. If available, use these APIs to fade-in
 		// the progress spinner.
-		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
+		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
+		{
 			int shortAnimTime = getResources().getInteger(
 					android.R.integer.config_shortAnimTime);
 
 			mLoginStatusView.setVisibility(View.VISIBLE);
 			mLoginStatusView.animate().setDuration(shortAnimTime)
 					.alpha(show ? 1 : 0)
-					.setListener(new AnimatorListenerAdapter() {
+					.setListener(new AnimatorListenerAdapter()
+					{
 						@Override
-						public void onAnimationEnd(Animator animation) {
+						public void onAnimationEnd(Animator animation)
+						{
 							mLoginStatusView.setVisibility(show ? View.VISIBLE
 									: View.GONE);
 						}
@@ -199,14 +242,18 @@ Log.d("onEditorAction", "id="+id+" keyevent="+keyEvent);
 			mLoginFormView.setVisibility(View.VISIBLE);
 			mLoginFormView.animate().setDuration(shortAnimTime)
 					.alpha(show ? 0 : 1)
-					.setListener(new AnimatorListenerAdapter() {
+					.setListener(new AnimatorListenerAdapter()
+					{
 						@Override
-						public void onAnimationEnd(Animator animation) {
+						public void onAnimationEnd(Animator animation)
+						{
 							mLoginFormView.setVisibility(show ? View.GONE
 									: View.VISIBLE);
 						}
 					});
-		} else {
+		}
+		else
+		{
 			// The ViewPropertyAnimator APIs are not available, so simply show
 			// and hide the relevant UI components.
 			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
@@ -218,80 +265,505 @@ Log.d("onEditorAction", "id="+id+" keyevent="+keyEvent);
 	 * Represents an asynchronous login/registration task used to authenticate
 	 * the user.
 	 */
-	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
-		@Override
-		protected Boolean doInBackground(Void... params) {
-
-			m_db = dbUtil.OpenDB(LockerActivity.this, null, true);
-
-			Cursor cursor = m_db.query("users", new String[] {  "pass",
-					"_id" }, "name= '"+m_sName+"'", null, null, null, "_id desc", null);
-			if (cursor.moveToNext()) {
-				// user exist in local db;
-//				Log.d(TAG, "USER "+m_sName+" exist!");
-				String pass = cursor.getString(0);
-				if (pass.equals(m_sPassword))
-					return true;
-				else {
-					return false;// wrong password
-				}
-			} else {
-				// user not exist in local db;
-				try {
-					// Simulate network access.
-					Thread.sleep(2000);
-				} catch (InterruptedException e) {
-					return false;
-				}
-				// TODO: register the new account here.
-				// online check user here;
-				if (true)// check pass create user in local db;
-				{
-					ContentValues cv = new ContentValues();
-					cv.put("name", m_sName);
-					cv.put("pass", m_sPassword);
-
-
-					m_db.insert("users", null, cv);
+	public class UserLoginTask extends AsyncTask<Void, Void, Boolean>
+	{
+		// int err_code = ERR_CODE_NONE;
+		int	verifyuser	= Network.RESULT_TRUE;
 
-					return true;
+		// int netconnect;
 
-				} else {
-					// no user exist on the server;
-					return false;
-				}
-			}
+		@Override
+		protected Boolean doInBackground(Void... params)
+		{
+
+			verifyuser = Network.VerifyUser(m_sName, m_sPassword);
+			if (verifyuser == Network.RESULT_TRUE)
+				return true;
+			else
+				return false;
 		}
-		
+
 		@Override
-		protected void onPostExecute(final Boolean success) {
+		protected void onPostExecute(final Boolean success)
+		{
+			Log.i("onPostExecute", "entry");
 			mAuthTask = null;
 			showProgress(false);
 
-			if (success) {
-				
-//				SharedPreferences.Editor editor = RunOnce.edit();
-//				editor.putBoolean("FirstRun"+globalUtil.getVerName(this), false);
-//				// Don't forget to commit your edits!!!
-//				editor.commit();
-                
-                Intent intent = new Intent();
-                intent.putExtra("user", m_sName);
-                /*
-                 * 调用setResult方法表示我将Intent对象返回给之前的那个Activity,这样就可以在onActivityResult方法中得到Intent对象,
-                 */
-                setResult(Activity.RESULT_OK, intent);			
+			if (success)
+			{
+				String encryptUser="";
+				String encryptPass="";
+				try
+				{
+					encryptUser=Crypto.encrypt("apexu", m_sName);
+					encryptPass=Crypto.encrypt("apexp", m_sPassword);
+				}
+				catch (Exception e1)
+				{
+					// TODO Auto-generated catch block
+					e1.printStackTrace();
+				}
+
+				SQLiteDatabase db = dbUtil.OpenDB(LockerActivity.this, null,
+						true);
+				Cursor cursor = db
+						.query("users", new String[] { "_id" }, "name='"
+								+ encryptUser + "'", null, null, null, "_id", null);
+				if (cursor.moveToNext())
+				{
+					int _id = cursor.getInt(0);
+					String sql = "update users set pass='" + encryptPass
+							+ "' where _id=" + _id;
+					db.execSQL(sql);
+				}
+				else
+				{
+					String sql = "insert into users(name,pass) values('"
+							+ encryptUser + "','" + encryptPass + "')";
+					db.execSQL(sql);
+				}
+				dbUtil.CloseCursor(cursor);
+				dbUtil.CloseDB(db);
+
+				RedAntApplication.user = m_sName;
+				RedAntApplication.password = m_sPassword;
+				Intent intent = new Intent();
+				setResult(Activity.RESULT_OK, intent);
 				finish();
-			} else {
-				m_etPassword
+			}
+			else
+			{
+				switch (verifyuser)
+				{
+					case Network.RESULT_NET_NOTAVAILABLE:
+					{
+						SQLiteDatabase db = dbUtil.OpenDB(LockerActivity.this,
+								null, true);
+
+						String encryptUser="";
+						try
+						{
+							encryptUser=Crypto.encrypt("apexu", m_sName);
+						}
+						catch (Exception e1)
+						{
+							// TODO Auto-generated catch block
+							e1.printStackTrace();
+						}
+						Cursor cursor = db.query("users", new String[] {
+								"pass", "_id" }, "name= '" + encryptUser + "'",
+								null, null, null, "_id desc", null);
+						if (cursor.moveToNext())
+						{
+							String pass="";
+							try
+							{
+								pass = Crypto.decrypt("apexp", cursor.getString(0));
+							}
+							catch (Exception e)
+							{
+								// TODO Auto-generated catch block
+								e.printStackTrace();
+							}
+							if (pass.equals(m_sPassword))
+							{
+								dbUtil.CloseCursor(cursor);
+								dbUtil.CloseDB(db);
+								RedAntApplication.user = m_sName;
+								RedAntApplication.password = m_sPassword;
+								Intent intent = new Intent();
+								setResult(Activity.RESULT_OK, intent);
+								finish();
+
+							}
+							else
+							{
+								// wrong password
+								Toast toast = Toast.makeText(getApplicationContext(),
+										getText(R.string.msg_user_wrong),
+										Toast.LENGTH_LONG);
+								toast.setGravity(Gravity.CENTER, 0, 0);
+								toast.show();
+								m_etPassword
+								.setError(getString(R.string.error_incorrect_password));
+						m_etPassword.requestFocus();
+								dbUtil.CloseCursor(cursor);
+								dbUtil.CloseDB(db);
+							}
+						}
+						else
+						{//wrong user
+							Toast toast = Toast.makeText(getApplicationContext(),
+									getText(R.string.msg_user_wrong),
+									Toast.LENGTH_LONG);
+							toast.setGravity(Gravity.CENTER, 0, 0);
+							toast.show();
+							m_etPassword
+							.setError(getString(R.string.error_incorrect_password));
+					m_etPassword.requestFocus();
+							dbUtil.CloseCursor(cursor);
+							dbUtil.CloseDB(db);
+
+						}
+
+						break;
+					}
+					case Network.RESULT_NET_ERROR:
+					{
+						Toast toast = Toast.makeText(getApplicationContext(),
+								getText(R.string.msg_net_error),
+								Toast.LENGTH_LONG);
+						toast.setGravity(Gravity.CENTER, 0, 0);
+						toast.show();
+						return;
+					}
+					case Network.RESULT_FALSE:
+					{
+						Toast toast = Toast.makeText(getApplicationContext(),
+								getText(R.string.msg_user_wrong),
+								Toast.LENGTH_LONG);
+						toast.setGravity(Gravity.CENTER, 0, 0);
+						toast.show();
+						m_etPassword
 						.setError(getString(R.string.error_incorrect_password));
 				m_etPassword.requestFocus();
+						return;
+					}
+
+					default:
+						break;
+				}
+
+
 			}
 		}
+
 		@Override
-		protected void onCancelled() {
+		protected void onCancelled()
+		{
 			mAuthTask = null;
 			showProgress(false);
 		}
-	}
+	}	
+	
+//	/**
+//	 * A dummy authentication store containing known user names and passwords.
+//	 * TODO: remove after connecting to a real authentication system.
+//	 */
+//	// private static final String[] DUMMY_CREDENTIALS = new String[] {
+//	// "foo@example.com:hello", "bar@example.com:world" };
+//
+//	/**
+//	 * The default email to populate the email field with.
+//	 */
+//	public static final String	EXTRA_EMAIL	= "com.example.android.authenticatordemo.extra.EMAIL";
+//
+//	/**
+//	 * Keep track of the login task to ensure we can cancel it if requested.
+//	 */
+//	private UserLoginTask		mAuthTask	= null;
+//	ArrayAdapter<String>		adapter							= null;
+//	SQLiteDatabase				m_db;
+//	// Values for email and password at the time of the login attempt.
+//	private String				m_sName;
+//	private String				m_sPassword;
+//
+//	// UI references.
+//	private AutoCompleteTextView			m_etName;
+//	private EditText			m_etPassword;
+//	private View				mLoginFormView;
+//	private View				mLoginStatusView;
+//	private TextView			mLoginStatusMessageView;
+//
+//	@Override
+//	protected void onCreate(Bundle savedInstanceState)
+//	{
+//		super.onCreate(savedInstanceState);
+//		setContentView(R.layout.activity_locker);
+//
+//		// Set up the login form.
+//		// m_sName = getIntent().getStringExtra(EXTRA_USER);
+//		m_etName = (AutoCompleteTextView) findViewById(R.id.name);
+//
+//		// m_etName.setText(m_sName);
+//
+//		m_etPassword = (EditText) findViewById(R.id.password);
+//		m_etPassword
+//				.setOnEditorActionListener(new TextView.OnEditorActionListener()
+//				{
+//					@Override
+//					public boolean onEditorAction(TextView textView, int id,
+//							KeyEvent keyEvent)
+//					{
+//						Log.d("onEditorAction", "id=" + id + " keyevent="
+//								+ keyEvent);
+//						if (id == R.id.locker
+//								|| id == EditorInfo.IME_ACTION_DONE)
+//						{
+//							attemptLogin();
+//							return true;
+//						}
+//						return false;
+//					}
+//				});
+//
+//		mLoginFormView = findViewById(R.id.login_form);
+//		mLoginStatusView = findViewById(R.id.login_status);
+//		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
+//
+//		findViewById(R.id.sign_in_button).setOnClickListener(
+//				new View.OnClickListener()
+//				{
+//					@Override
+//					public void onClick(View view)
+//					{
+//						attemptLogin();
+//					}
+//				});
+//		
+//		adapter = new ArrayAdapter<String>(this,
+//				android.R.layout.simple_list_item_1,
+//				dbUtil.get_userlist());
+//		m_etName.setAdapter(adapter);
+//	}
+//
+//	@Override
+//	public boolean onCreateOptionsMenu(Menu menu)
+//	{
+//		super.onCreateOptionsMenu(menu);
+//		getMenuInflater().inflate(R.menu.locker, menu);
+//		return true;
+//	}
+//
+//	@Override
+//	public boolean onKeyDown(int keyCode, KeyEvent event)
+//	{
+//		if (keyCode == KeyEvent.KEYCODE_BACK)
+//		{
+//			// Intent myIntent = new Intent();
+//			// myIntent = new Intent(EditActivity.this, tabActivity.class);
+//			// startActivity(myIntent);
+//			// this.finish();
+//			return true;
+//		}
+//		return super.onKeyDown(keyCode, event);
+//
+//	}
+//
+//	/**
+//	 * Attempts to sign in or register the account specified by the login form.
+//	 * If there are form errors (invalid email, missing fields, etc.), the
+//	 * errors are presented and no actual login attempt is made.
+//	 */
+//	public void attemptLogin()
+//	{
+//		if (mAuthTask != null)
+//		{
+//			return;
+//		}
+//
+//		// Reset errors.
+//		m_etName.setError(null);
+//		m_etPassword.setError(null);
+//
+//		// Store values at the time of the login attempt.
+//		m_sName = m_etName.getText().toString();
+//		m_sPassword = m_etPassword.getText().toString();
+//
+//		boolean cancel = false;
+//		View focusView = null;
+//
+//		// Check for a valid password.
+//		if (TextUtils.isEmpty(m_sPassword))
+//		{
+//			m_etPassword.setError(getString(R.string.error_field_required));
+//			focusView = m_etPassword;
+//			cancel = true;
+//		}
+//		else if (m_sPassword.length() < 4)
+//		{
+//			m_etPassword.setError(getString(R.string.error_invalid_password));
+//			focusView = m_etPassword;
+//			cancel = true;
+//		}
+//
+//		// Check for a valid user name.
+//		if (TextUtils.isEmpty(m_sName))
+//		{
+//			m_etName.setError(getString(R.string.error_field_required));
+//			focusView = m_etName;
+//			cancel = true;
+//		}
+//		// else if (!m_sName.contains("@")) {
+//		// m_etName.setError(getString(R.string.error_invalid_email));
+//		// focusView = m_etName;
+//		// cancel = true;
+//		// }
+//
+//		if (cancel)
+//		{
+//			// There was an error; don't attempt login and focus the first
+//			// form field with an error.
+//			focusView.requestFocus();
+//		}
+//		else
+//		{
+//			// Show a progress spinner, and kick off a background task to
+//			// perform the user login attempt.
+//			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
+//			showProgress(true);
+//			mAuthTask = new UserLoginTask();
+//			mAuthTask.execute((Void) null);
+//		}
+//	}
+//
+//	/**
+//	 * Shows the progress UI and hides the login form.
+//	 */
+//	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
+//	private void showProgress(final boolean show)
+//	{
+//		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
+//		// for very easy animations. If available, use these APIs to fade-in
+//		// the progress spinner.
+//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
+//		{
+//			int shortAnimTime = getResources().getInteger(
+//					android.R.integer.config_shortAnimTime);
+//
+//			mLoginStatusView.setVisibility(View.VISIBLE);
+//			mLoginStatusView.animate().setDuration(shortAnimTime)
+//					.alpha(show ? 1 : 0)
+//					.setListener(new AnimatorListenerAdapter()
+//					{
+//						@Override
+//						public void onAnimationEnd(Animator animation)
+//						{
+//							mLoginStatusView.setVisibility(show ? View.VISIBLE
+//									: View.GONE);
+//						}
+//					});
+//
+//			mLoginFormView.setVisibility(View.VISIBLE);
+//			mLoginFormView.animate().setDuration(shortAnimTime)
+//					.alpha(show ? 0 : 1)
+//					.setListener(new AnimatorListenerAdapter()
+//					{
+//						@Override
+//						public void onAnimationEnd(Animator animation)
+//						{
+//							mLoginFormView.setVisibility(show ? View.GONE
+//									: View.VISIBLE);
+//						}
+//					});
+//		}
+//		else
+//		{
+//			// The ViewPropertyAnimator APIs are not available, so simply show
+//			// and hide the relevant UI components.
+//			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
+//			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
+//		}
+//	}
+//
+//	/**
+//	 * Represents an asynchronous login/registration task used to authenticate
+//	 * the user.
+//	 */
+//	public class UserLoginTask extends AsyncTask<Void, Void, Boolean>
+//	{
+//		@Override
+//		protected Boolean doInBackground(Void... params)
+//		{
+//
+//			m_db = dbUtil.OpenDB(LockerActivity.this, null, true);
+//
+//			Cursor cursor = m_db.query("users", new String[] { "pass", "_id" },
+//					"name= '" + m_sName + "'", null, null, null, "_id desc",
+//					null);
+//			if (cursor.moveToNext())
+//			{
+//				// user exist in local db;
+//				// Log.d(TAG, "USER "+m_sName+" exist!");
+//				String pass = cursor.getString(0);
+//				if (pass.equals(m_sPassword))
+//					return true;
+//				else
+//				{
+//					return false;// wrong password
+//				}
+//			}
+//			else
+//			{
+//				// user not exist in local db;
+//				try
+//				{
+//					// Simulate network access.
+//					Thread.sleep(2000);
+//				}
+//				catch (InterruptedException e)
+//				{
+//					return false;
+//				}
+//				// TODO: register the new account here.
+//				// online check user here;
+//				if (true)// check pass create user in local db;
+//				{
+//					ContentValues cv = new ContentValues();
+//					cv.put("name", m_sName);
+//					cv.put("pass", m_sPassword);
+//
+//					m_db.insert("users", null, cv);
+//
+//					return true;
+//
+//				}
+//				else
+//				{
+//					// no user exist on the server;
+//					return false;
+//				}
+//			}
+//		}
+//
+//		@Override
+//		protected void onPostExecute(final Boolean success)
+//		{
+//			mAuthTask = null;
+//			showProgress(false);
+//
+//			if (success)
+//			{
+//
+//				// SharedPreferences.Editor editor = RunOnce.edit();
+//				// editor.putBoolean("FirstRun"+globalUtil.getVerName(this),
+//				// false);
+//				// // Don't forget to commit your edits!!!
+//				// editor.commit();
+//
+//				Intent intent = new Intent();
+//				intent.putExtra("user", m_sName);
+//				/*
+//				 * 锟斤拷锟斤拷setResult锟斤拷锟斤拷锟斤拷示锟揭斤拷Intent锟斤拷锟襟返回革拷之前锟斤拷锟角革拷Activity锟斤拷锟斤拷锟斤拷锟酵匡拷锟斤拷
+//				 * 锟斤拷onActivityResult锟斤拷锟斤拷锟叫得碉拷Intent锟斤拷锟斤拷
+//				 */
+//				setResult(Activity.RESULT_OK, intent);
+//				finish();
+//			}
+//			else
+//			{
+//				m_etPassword
+//						.setError(getString(R.string.error_incorrect_password));
+//				m_etPassword.requestFocus();
+//			}
+//		}
+//
+//		@Override
+//		protected void onCancelled()
+//		{
+//			mAuthTask = null;
+//			showProgress(false);
+//		}
+//	}
 }

+ 182 - 115
RedAnt Photo/src/com/usai/redant/photo/LoginActivity.java

@@ -4,6 +4,7 @@ import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
 
+import com.usai.util.Crypto;
 import com.usai.util.Network;
 import com.usai.util.dbUtil;
 //import com.example.com.apex.usa.test1.R.id;
@@ -36,6 +37,8 @@ import android.view.Menu;
 import android.view.View;
 import android.view.inputmethod.EditorInfo;
 import android.view.inputmethod.InputMethodManager;
+import android.widget.ArrayAdapter;
+import android.widget.AutoCompleteTextView;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Toast;
@@ -47,9 +50,9 @@ import android.widget.Toast;
 public class LoginActivity extends Activity
 {
 
-//	public static final int ERR_CODE_NONE = 0;
-//	public static final int ERR_CODE_NULLRETURN = 1;
-//	public static final int ERR_CODE_NONETWORK = 2;
+	// public static final int ERR_CODE_NONE = 0;
+	// public static final int ERR_CODE_NULLRETURN = 1;
+	// public static final int ERR_CODE_NONETWORK = 2;
 
 	/**
 	 * A dummy authentication store containing known user names and passwords.
@@ -68,28 +71,28 @@ public class LoginActivity extends Activity
 	/**
 	 * Keep track of the login task to ensure we can cancel it if requested.
 	 */
-	private UserLoginTask mAuthTask = null;
-
-	SQLiteDatabase m_db;
+	private UserLoginTask	mAuthTask	= null;
+	ArrayAdapter<String>		adapter							= null;
+	// SQLiteDatabase m_db;
 	// Values for email and password at the time of the login attempt.
-	private String m_sName;
-	private String m_sPassword;
+	private String			m_sName;
+	private String			m_sPassword;
 
 	// UI references.
-	private EditText m_etName;
-	private EditText m_etPassword;
-	private View mLoginFormView;
-	private View mLoginStatusView;
-	private TextView mLoginStatusMessageView;
-
-	@Override
-	protected void onDestroy()
-	{
-		// TODO Auto-generated method stub
-		dbUtil.CloseDB(m_db);
-		super.onDestroy();
-
-	}
+	private AutoCompleteTextView		m_etName;
+	private EditText		m_etPassword;
+	private View			mLoginFormView;
+	private View			mLoginStatusView;
+	private TextView		mLoginStatusMessageView;
+
+//	@Override
+//	protected void onDestroy()
+//	{
+//		// TODO Auto-generated method stub
+////		dbUtil.CloseDB(m_db);
+////		super.onDestroy();
+//
+//	}
 
 	@Override
 	protected void onCreate(Bundle savedInstanceState)
@@ -100,7 +103,7 @@ public class LoginActivity extends Activity
 
 		// Set up the login form.
 		// m_sName = getIntent().getStringExtra(EXTRA_USER);
-		m_etName = (EditText) findViewById(R.id.name);
+		m_etName = (AutoCompleteTextView) findViewById(R.id.name);
 
 		// m_etName.setText(m_sName);
 
@@ -142,6 +145,10 @@ public class LoginActivity extends Activity
 						attemptLogin();
 					}
 				});
+		adapter = new ArrayAdapter<String>(this,
+				android.R.layout.simple_list_item_1,
+				dbUtil.get_userlist());
+		m_etName.setAdapter(adapter);
 	}
 
 	@Override
@@ -182,14 +189,12 @@ public class LoginActivity extends Activity
 			focusView = m_etPassword;
 			cancel = true;
 		}
-		else
-			if (m_sPassword.length() < 4)
-			{
-				m_etPassword
-						.setError(getString(R.string.error_invalid_password));
-				focusView = m_etPassword;
-				cancel = true;
-			}
+		else if (m_sPassword.length() < 4)
+		{
+			m_etPassword.setError(getString(R.string.error_invalid_password));
+			focusView = m_etPassword;
+			cancel = true;
+		}
 
 		// Check for a valid user name.
 		if (TextUtils.isEmpty(m_sName))
@@ -276,55 +281,20 @@ public class LoginActivity extends Activity
 	 */
 	public class UserLoginTask extends AsyncTask<Void, Void, Boolean>
 	{
-//		int err_code = ERR_CODE_NONE;
-		int verifyuser = Network.RESULT_TRUE;
-		int netconnect;
+		// int err_code = ERR_CODE_NONE;
+		int	verifyuser	= Network.RESULT_TRUE;
+
+		// int netconnect;
 
 		@Override
 		protected Boolean doInBackground(Void... params)
 		{
 
-			// if (Network.NetworkIsAvailable(LoginActivity.this))
-			// {
-			// Network.VerifyUser(m_sName, m_sPassword,LoginActivity.this);
-			// return false;
-			// }
-			m_db = dbUtil.OpenDB(LoginActivity.this, null, true);
-
-			Cursor cursor = m_db.query("users", new String[] { "pass", "_id" },
-					"name= '" + m_sName + "'", null, null, null, "_id desc",
-					null);
-			if (cursor.moveToNext())
-			{
-				// user exist in local db;
-				// Log.d(TAG, "USER "+m_sName+" exist!");
-				String pass = cursor.getString(0);
-				if (pass.equals(m_sPassword))
-					return true;
-				else
-				{
-					return false;// wrong password
-				}
-			}
+			verifyuser = Network.VerifyUser(m_sName, m_sPassword);
+			if (verifyuser == Network.RESULT_TRUE)
+				return true;
 			else
-			{
-				/*
-				 * user not exist in local db; check online if user is
-				 * authorized create user in local db;
-				 */
-
-				if (!Network.NetworkIsAvailable(LoginActivity.this))
-				{
-					netconnect = Network.RESULT_NET_ERROR;
-
-					return false;
-				}
-				verifyuser = Network.VerifyUser(m_sName, m_sPassword);
-				if(verifyuser==Network.RESULT_TRUE)
-					return true;
-
-			}
-			return false;
+				return false;
 		}
 
 		@Override
@@ -333,60 +303,157 @@ public class LoginActivity extends Activity
 			Log.i("onPostExecute", "entry");
 			mAuthTask = null;
 			showProgress(false);
-			if(netconnect==Network.RESULT_NET_ERROR)
-			{
-				Toast toast = Toast.makeText(getApplicationContext(),
-						getText(R.string.msg_connection_none),
-						Toast.LENGTH_LONG);
-				toast.setGravity(Gravity.CENTER, 0, 0);
-				toast.show();				
-			}
-			switch (verifyuser)
-			{
-			case Network.RESULT_NET_ERROR:
-			{
-				Toast toast = Toast.makeText(getApplicationContext(),
-						getText(R.string.msg_net_error),
-						Toast.LENGTH_LONG);
-				toast.setGravity(Gravity.CENTER, 0, 0);
-				toast.show();
-				return;
-			}
-			case Network.RESULT_ERROR:
-//			case Network.RESULT_RESPONSE_NULL:
-			{
-				Toast toast = Toast.makeText(getApplicationContext(),
-						getText(R.string.msg_net_resulterror),
-						Toast.LENGTH_LONG);
-				toast.setGravity(Gravity.CENTER, 0, 0);
-				toast.show();
-				return;
-			}
-				
-			default:
-				break;
-			}
 
 			if (success)
 			{
+				String encryptUser="";
+				String encryptPass="";
+				try
+				{
+					encryptUser=Crypto.encrypt("apexu", m_sName);
+					encryptPass=Crypto.encrypt("apexp", m_sPassword);
+				}
+				catch (Exception e1)
+				{
+					// TODO Auto-generated catch block
+					e1.printStackTrace();
+				}
 
-				// SharedPreferences.Editor editor = RunOnce.edit();
-				// editor.putBoolean("FirstRun"+globalUtil.getVerName(this),
-				// false);
-				// // Don't forget to commit your edits!!!
-				// editor.commit();
+				SQLiteDatabase db = dbUtil.OpenDB(LoginActivity.this, null,
+						true);
+				Cursor cursor = db
+						.query("users", new String[] { "_id" }, "name='"
+								+ encryptUser + "'", null, null, null, "_id", null);
+				if (cursor.moveToNext())
+				{
+					int _id = cursor.getInt(0);
+					String sql = "update users set pass='" + encryptPass
+							+ "' where _id=" + _id;
+					db.execSQL(sql);
+				}
+				else
+				{
+					String sql = "insert into users(name,pass) values('"
+							+ encryptUser + "','" + encryptPass + "')";
+					db.execSQL(sql);
+				}
+				dbUtil.CloseCursor(cursor);
+				dbUtil.CloseDB(db);
+
+				RedAntApplication.user = m_sName;
+				RedAntApplication.password = m_sPassword;
 				Intent intent = new Intent();
 				intent.setClass(LoginActivity.this, MainActivity.class);
-				intent.putExtra("user", m_sName);
-				intent.putExtra("password", m_sPassword);
+
 				startActivity(intent);
 				finish();
 			}
 			else
 			{
-				m_etPassword
+				switch (verifyuser)
+				{
+					case Network.RESULT_NET_NOTAVAILABLE:
+					{
+						SQLiteDatabase db = dbUtil.OpenDB(LoginActivity.this,
+								null, true);
+
+						String encryptUser="";
+						try
+						{
+							encryptUser=Crypto.encrypt("apexu", m_sName);
+						}
+						catch (Exception e1)
+						{
+							// TODO Auto-generated catch block
+							e1.printStackTrace();
+						}
+						Cursor cursor = db.query("users", new String[] {
+								"pass", "_id" }, "name= '" + encryptUser + "'",
+								null, null, null, "_id desc", null);
+						if (cursor.moveToNext())
+						{
+							String pass="";
+							try
+							{
+								pass = Crypto.decrypt("apexp", cursor.getString(0));
+							}
+							catch (Exception e)
+							{
+								// TODO Auto-generated catch block
+								e.printStackTrace();
+							}
+							if (pass.equals(m_sPassword))
+							{
+								dbUtil.CloseCursor(cursor);
+								dbUtil.CloseDB(db);
+								RedAntApplication.user = m_sName;
+								RedAntApplication.password = m_sPassword;
+								Intent intent = new Intent();
+								intent.setClass(LoginActivity.this,
+										MainActivity.class);
+
+								startActivity(intent);
+								finish();
+							}
+							else
+							{
+								// wrong password
+								Toast toast = Toast.makeText(getApplicationContext(),
+										getText(R.string.msg_user_wrong),
+										Toast.LENGTH_LONG);
+								toast.setGravity(Gravity.CENTER, 0, 0);
+								toast.show();
+								m_etPassword
+								.setError(getString(R.string.error_incorrect_password));
+						m_etPassword.requestFocus();
+								dbUtil.CloseCursor(cursor);
+								dbUtil.CloseDB(db);
+							}
+						}
+						else
+						{//user not exist
+							Toast toast = Toast.makeText(getApplicationContext(),
+									getText(R.string.msg_net_error),
+									Toast.LENGTH_LONG);
+							toast.setGravity(Gravity.CENTER, 0, 0);
+							toast.show();
+							m_etPassword
+							.setError(getString(R.string.error_incorrect_password));
+					m_etPassword.requestFocus();
+							dbUtil.CloseCursor(cursor);
+							dbUtil.CloseDB(db);
+
+						}
+
+						break;
+					}
+					case Network.RESULT_NET_ERROR:
+					{
+						Toast toast = Toast.makeText(getApplicationContext(),
+								getText(R.string.msg_net_error),
+								Toast.LENGTH_LONG);
+						toast.setGravity(Gravity.CENTER, 0, 0);
+						toast.show();
+						return;
+					}
+					case Network.RESULT_FALSE:
+					{
+						Toast toast = Toast.makeText(getApplicationContext(),
+								getText(R.string.msg_user_wrong),
+								Toast.LENGTH_LONG);
+						toast.setGravity(Gravity.CENTER, 0, 0);
+						toast.show();
+						m_etPassword
 						.setError(getString(R.string.error_incorrect_password));
 				m_etPassword.requestFocus();
+						return;
+					}
+
+					default:
+						break;
+				}
+
+
 			}
 		}
 

+ 563 - 341
RedAnt Photo/src/com/usai/redant/photo/MainActivity.java

@@ -5,10 +5,10 @@ import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.Serializable;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
-
 import com.usai.util.Network;
 import com.usai.util.dbUtil;
 
@@ -16,17 +16,17 @@ import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 import android.media.ThumbnailUtils;
 import android.net.Uri;
-import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Environment;
 import android.provider.MediaStore;
 import android.app.Activity;
+import android.app.AlertDialog;
 import android.content.BroadcastReceiver;
 import android.content.ContentValues;
 import android.content.Context;
+import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.pm.ActivityInfo;
 import android.database.sqlite.SQLiteDatabase;
 import android.text.Editable;
 import android.text.TextWatcher;
@@ -43,61 +43,90 @@ public class MainActivity extends Activity
 {
 	// static final int ACTIVITY_CAMERA = 0;
 	// static final int ACTIVITY_VIEW = 1;
-//	static final String serverurl = "http://192.168.23.1/xampp/";
-	static final String TAG = "MainActivity";
-	static final int REQUEST_TAKE_PHOTO = 1;
-	static final int REQUEST_SCAN_BARCODE = 2;
-	static final int REQUEST_LOCKER = 3;
-
-//	private String thumbpath = null;
-	private int iwidth = 640;
-	private int iheight = 480;
-	private File photoFile = null;
-	Bitmap thumbBitmap = null;
+	// static final String serverurl = "http://192.168.23.1/xampp/";
+	static final String				TAG						= "MainActivity";
+	static final int				REQUEST_TAKE_PHOTO		= 1;
+	static final int				REQUEST_SCAN_BARCODE	= 2;
+	static final int				REQUEST_LOCKER			= 3;
+	// HashMap<String, String> hashMap = new HashMap<String, String>();
+
+	// ArrayList<String> pic_file = new ArrayList<String>();
+	// ArrayList<bitmap>
+	// ArrayList<>
+	// private String thumbpath = null;
+	private int						iwidth					= 640;
+	private int						iheight					= 480;
+	private File					photoFile				= null;
+	Bitmap							thumbBitmap				= null;
 	// private int iPhotoCount = 0;
-	public String LastFileName = "";
-	private boolean m_blocked = false;
-	TextView m_tvalert;
+	public String					LastFileName			= "";
+	private boolean					m_blocked				= false;
+	TextView						m_tvalert;
 	// private String user;
 	// private String password;
-	String m_sName;
-	String m_sPassword;
-	ArrayList<String> photoList = new ArrayList<String>();
+	// String m_sName;
+	// String m_sPassword;
+	ArrayList<String>				photoList				= new ArrayList<String>();
 	// private SurfaceView picSV;
 	// private Camera camera;
 	//
-	private final BroadcastReceiver m_lockedReceiver = new BroadcastReceiver()
-	{
-		@Override
-		public void onReceive(Context context, Intent intent)
-		{
-			String action = intent.getAction();
-			if (action.equals(Intent.ACTION_SCREEN_OFF))
-			{
-				Log.e("hg", "收到广播!!!=======>m_blocked=" + m_blocked);
-				if (m_blocked == true)
-					return;
-				Intent activityintent = new Intent();
-				activityintent
-						.setClass(MainActivity.this, LockerActivity.class);
-				startActivityForResult(activityintent, REQUEST_LOCKER);
-				Log.e(TAG, "===================>start locker");
-				m_blocked = true;
-			}
-			// if (action.equals(Intent.ACTION_USER_PRESENT)) {
-			//
-			// Log.e("hg", "收到广播!!!=======>m_blocked=" + m_blocked);
-			// if (m_blocked == true)
-			// return;
-			// Intent activityintent = new Intent();
-			// activityintent
-			// .setClass(MainActivity.this, LockerActivity.class);
-			// startActivityForResult(activityintent, REQUEST_LOCKER);
-			// Log.e(TAG, "===================>start locker");
-			// m_blocked = true;
-			// }
-		}
-	};
+//	private final BroadcastReceiver	m_lockedReceiver		= new BroadcastReceiver()
+//															{
+//																@Override
+//																public void onReceive(
+//																		Context context,
+//																		Intent intent)
+//																{
+//																	String action = intent
+//																			.getAction();
+//																	if (action
+//																			.equals(Intent.ACTION_SCREEN_OFF))
+//																	{
+//																		Log.e("hg",
+//																				"锟秸碉拷锟姐播!!!=======>m_blocked="
+//																						+ m_blocked);
+//																		if (m_blocked == true)
+//																			return;
+//																		Intent activityintent = new Intent();
+//																		activityintent
+//																				.setClass(
+//																						MainActivity.this,
+//																						LockerActivity.class);
+//																		startActivityForResult(
+//																				activityintent,
+//																				REQUEST_LOCKER);
+//																		Log.e(TAG,
+//																				"===================>start locker");
+//																		m_blocked = true;
+//																	}
+//																	// if
+//																	// (action.equals(Intent.ACTION_USER_PRESENT))
+//																	// {
+//																	//
+//																	// Log.e("hg",
+//																	// "锟秸碉拷锟姐播!!!=======>m_blocked="
+//																	// +
+//																	// m_blocked);
+//																	// if
+//																	// (m_blocked
+//																	// == true)
+//																	// return;
+//																	// Intent
+//																	// activityintent
+//																	// = new
+//																	// Intent();
+//																	// activityintent
+//																	// .setClass(MainActivity.this,
+//																	// LockerActivity.class);
+//																	// startActivityForResult(activityintent,
+//																	// REQUEST_LOCKER);
+//																	// Log.e(TAG,
+//																	// "===================>start locker");
+//																	// m_blocked
+//																	// = true;
+//																	// }
+//																}
+//															};
 
 	// @Override
 	// protected void onStart() {
@@ -156,17 +185,48 @@ public class MainActivity extends Activity
 		Log.e(TAG, "=======================>MainActivity Created!");
 		super.onCreate(savedInstanceState);
 		setContentView(R.layout.activity_main1);
-		IntentFilter msgFilter = new IntentFilter();
-		Intent intent = getIntent();
 
-		m_sName = intent.getStringExtra("user");
-		m_sPassword = intent.getStringExtra("password");
 
-		Log.e(TAG, "user=" + m_sName + ",password=" + m_sPassword);
+		ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
+		thumbsImageView.setOnClickListener(new View.OnClickListener()
+		{
+
+			@Override
+			public void onClick(View v)
+			{
+
+				Intent intent = new Intent(MainActivity.this,
+						PhotoPreviewActivity.class);
+				intent.putExtra("pic_list", (Serializable) photoList);
+				startActivity(intent);
+
+				// File folder = new
+				// File(Environment.getExternalStorageDirectory().getPath()+"/redant/pop/temp");
+				// File[] allFiles = folder.listFiles();
+				// new SingleMediaScanner(MainActivity.this, allFiles[0]);
+				// Intent intent = new Intent();
+				// // Intent.ACTION_PICK,
+				// //
+				// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
+				// // startActivityForResult(intent, REQUEST_SCAN_BARCODE);
+				//
+				// intent.setClass(MainActivity.this, CaptureActivity.class);
+				// startActivityForResult(intent, REQUEST_SCAN_BARCODE);
+			}
+		});
+		// m_sName = intent.getStringExtra("user");
+		// m_sPassword = intent.getStringExtra("password");
 
+		Log.e(TAG, "user=" + RedAntApplication.user + ",password="
+				+ RedAntApplication.password);
+		IntentFilter msgFilter = new IntentFilter();
+		Intent intent = getIntent();
 		msgFilter.addAction("android.intent.action.SCREEN_OFF");
+//		msgFilter.addAction("REDANT.POP.USER_CHECK_FAILED");
+		msgFilter.addAction("REDANT.POP.FINISH_UPLOAD_QUEUE");
+		msgFilter.addAction("REDANT.POP.FINISH_UPLOAD_QUEUE_WITH_ERROR");
 		msgFilter.setPriority(2147483647);
-		registerReceiver(m_lockedReceiver, msgFilter);
+		registerReceiver(MainActivityReceiver, msgFilter);
 		Log.e(TAG, "=======================>msgFilter registed!");
 		if (savedInstanceState != null)
 		{
@@ -180,56 +240,57 @@ public class MainActivity extends Activity
 			// savedInstanceState.getStringArrayList("photoList");
 			photoFile = (File) savedInstanceState.getSerializable("photoFile");
 			// iPhotoCount = savedInstanceState.getInt("iPhotoCount");
-//			thumbpath = savedInstanceState.getString("thumbpath");
-			if (savedInstanceState.getString("m_sName") != null)
-				m_sName = savedInstanceState.getString("m_sName");
-			if (savedInstanceState.getString("m_sPassword") != null)
-				m_sPassword = savedInstanceState.getString("m_sPassword");
-			ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
+			// thumbpath = savedInstanceState.getString("thumbpath");
+			// if (savedInstanceState.getString("m_sName") != null)
+			// m_sName = savedInstanceState.getString("m_sName");
+			// if (savedInstanceState.getString("m_sPassword") != null)
+			// m_sPassword = savedInstanceState.getString("m_sPassword");
+			// ImageView thumbsImageView = (ImageView)
+			// findViewById(R.id.ivThumbs);
 			if (thumbBitmap != null)
 			{
 				thumbsImageView.setImageBitmap(thumbBitmap);
-//				Log.e(TAG, "load thumbpath==" + thumbpath);
+				// Log.e(TAG, "load thumbpath==" + thumbpath);
 			}
 			// photoFile.delete();
 			TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
 			countTextView.setText(photoList.size() + " Photos");
 
 		}
-		EditText edit = (EditText) findViewById(R.id.edit);
-
-		edit.addTextChangedListener(new TextWatcher()
-		{
-			@Override
-			public void onTextChanged(CharSequence s, int start, int before,
-					int count)
-			{
-
-			}
-
-			@Override
-			public void beforeTextChanged(CharSequence s, int start, int count,
-					int after)
-			{
-			}
-
-			@Override
-			public void afterTextChanged(Editable s)
-			{
-				// EditText edit = (EditText) findViewById(R.id.edit);
-				ImageButton ibtnUpload = (ImageButton) findViewById(R.id.ibtnOk);
-				if (photoList.size() > 0 && s.length() > 0)
-				{
-					ibtnUpload.setVisibility(View.VISIBLE);
-
-				}
-				else
-				{
-					ibtnUpload.setVisibility(View.INVISIBLE);
+//		EditText edit = (EditText) findViewById(R.id.pidval);
 
-				}
-			}
-		});
+//		edit.addTextChangedListener(new TextWatcher()
+//		{
+//			@Override
+//			public void onTextChanged(CharSequence s, int start, int before,
+//					int count)
+//			{
+//
+//			}
+//
+//			@Override
+//			public void beforeTextChanged(CharSequence s, int start, int count,
+//					int after)
+//			{
+//			}
+//
+//			@Override
+//			public void afterTextChanged(Editable s)
+//			{
+//				// EditText edit = (EditText) findViewById(R.id.edit);
+//				ImageButton ibtnUpload = (ImageButton) findViewById(R.id.ibtnOk);
+//				if (photoList.size() > 0 && s.length() > 0)
+//				{
+//					ibtnUpload.setVisibility(View.VISIBLE);
+//
+//				}
+//				else
+//				{
+//					ibtnUpload.setVisibility(View.INVISIBLE);
+//
+//				}
+//			}
+//		});
 		// if (getRequestedOrientation() ==
 		// ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
 		// LinearLayout landLayout = (LinearLayout) findViewById(R.id.land);
@@ -245,6 +306,7 @@ public class MainActivity extends Activity
 			@Override
 			public void onClick(View v)
 			{
+				Log.e(TAG,"==============>Click Scan button");
 				Intent intent = new Intent();
 				// Intent.ACTION_PICK,
 				// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
@@ -273,14 +335,35 @@ public class MainActivity extends Activity
 			@Override
 			public void onClick(View v)
 			{
+				SQLiteDatabase db = dbUtil
+						.OpenDB(MainActivity.this, null, true);
+				TextView pidval = (TextView) findViewById(R.id.pidval);
+				String pid = pidval.getText().toString();
+				for (int i = 0; i < photoList.size(); i++)
+				{
 
-				new UploadTask().execute((Void) null);
+					ContentValues cv = new ContentValues();
+					cv.put("picker", RedAntApplication.user);
+					cv.put("err_code", Network.STATUS_WAIT);
+					cv.put("pid", pid);
+					cv.put("local_path", photoList.get(i));
+					db.insert("pics", null, cv);
+
+				}
+				dbUtil.CloseDB(db);
+				// new UploadTask().execute((Void) null);
+				clearfornew();
+				Intent intent = new Intent("REDANT.POP.MODIFY_QUEUE");
+				sendBroadcast(intent);
 			}
 		});
 
 		m_tvalert = (TextView) findViewById(R.id.tvalert);
 		m_tvalert.setSelected(true);
 
+		// Intent intent = ;
+		sendBroadcast(new Intent("REDANT.POP.MODIFY_QUEUE"));
+
 	}
 
 	@Override
@@ -288,7 +371,7 @@ public class MainActivity extends Activity
 	{
 		// TODO Auto-generated method stub
 		Log.e(TAG, "=======================>MainActivity Destroyed!");
-		unregisterReceiver(m_lockedReceiver);
+		unregisterReceiver(MainActivityReceiver);
 		Log.e(TAG, "=======================>msgFilter unregisted!");
 		super.onDestroy();
 	}
@@ -307,8 +390,29 @@ public class MainActivity extends Activity
 		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
 				.format(new Date());
 		String imageFileName = "JPEG_" + timeStamp + "_";
-		File storageDir = Environment
-				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
+		File storageDir = new File(Environment.getExternalStorageDirectory()
+				.getPath() + "/redant/pop/temp/");
+
+		File dir1 = new File(Environment.getExternalStorageDirectory()
+				.getPath() + "/redant");
+		File dir2 = new File(Environment.getExternalStorageDirectory()
+				.getPath() + "/redant/pop");
+		File dir3 = new File(Environment.getExternalStorageDirectory()
+				.getPath() + "/redant/pop/temp");
+
+		if (!dir1.exists())
+		{
+			boolean b = dir1.mkdir();
+		}
+		if (!dir2.exists())
+		{
+			boolean b = dir2.mkdir();
+		}
+		if (!dir3.exists())
+		{
+			boolean b = dir3.mkdir();
+		}
+		// Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
 		// Log.d(TAG, "DIR:" + storageDir);
 		LastFileName = storageDir + imageFileName + ".jpg";
 		Log.d(TAG, "File:" + LastFileName);
@@ -322,29 +426,29 @@ public class MainActivity extends Activity
 		return image;
 	}
 
-//	public static void savePic(Bitmap b, String strFileName)
-//	{
-//		FileOutputStream fos = null;
-//		try
-//		{
-//			fos = new FileOutputStream(strFileName);
-//			if (null != fos)
-//			{
-//
-//				b.compress(Bitmap.CompressFormat.PNG, 90, fos);
-//				fos.flush();
-//				fos.close();
-//			}
-//		}
-//		catch (FileNotFoundException e)
-//		{
-//			e.printStackTrace();
-//		}
-//		catch (IOException e)
-//		{
-//			e.printStackTrace();
-//		}
-//	}
+	// public static void savePic(Bitmap b, String strFileName)
+	// {
+	// FileOutputStream fos = null;
+	// try
+	// {
+	// fos = new FileOutputStream(strFileName);
+	// if (null != fos)
+	// {
+	//
+	// b.compress(Bitmap.CompressFormat.PNG, 90, fos);
+	// fos.flush();
+	// fos.close();
+	// }
+	// }
+	// catch (FileNotFoundException e)
+	// {
+	// e.printStackTrace();
+	// }
+	// catch (IOException e)
+	// {
+	// e.printStackTrace();
+	// }
+	// }
 
 	boolean createDir(String path)
 	{
@@ -369,9 +473,9 @@ public class MainActivity extends Activity
 
 	void updateUploadButton()
 	{
-		EditText edit = (EditText) findViewById(R.id.edit);
+		TextView pidval = (TextView) findViewById(R.id.pidval);
 		ImageButton ibtnUpload = (ImageButton) findViewById(R.id.ibtnOk);
-		if (photoList.size() > 0 && edit.getText().length() > 0)
+		if (photoList.size() > 0 && pidval.getText().length() > 0)
 		{
 			ibtnUpload.setVisibility(View.VISIBLE);
 
@@ -395,8 +499,8 @@ public class MainActivity extends Activity
 	{
 
 		if (requestCode == REQUEST_TAKE_PHOTO)
-			// 处理照相机拍照的图片
-			if (resultCode == Activity.RESULT_OK) // 继续拍照
+			// 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷盏锟酵计�
+			if (resultCode == Activity.RESULT_OK) // 锟斤拷锟斤拷锟斤拷锟斤拷
 
 			{
 				// Log.e(TAG, msg)
@@ -404,7 +508,7 @@ public class MainActivity extends Activity
 				// if(thumbBitmap!=null)
 				// thumbBitmap=null;
 				// thumbBitmap = (Bitmap) bundle.get("data");
-				// // 获取相机返回的数据,并转换为Bitmap图片格
+				// // 锟斤拷取锟斤拷锟斤拷锟斤拷氐锟斤拷锟斤拷荩锟斤拷锟阶�拷锟轿狟itmap图片锟斤拷
 				// Bitmap thumbBitmap = BitmapFactory.decodeFile(photoFile
 				// .toString());
 
@@ -417,8 +521,8 @@ public class MainActivity extends Activity
 				// thumbsImageView.getHeight(), false));
 				// Log.i(TAG, "thumb size" + thumbBitmap.getHeight() + "x"
 				// + thumbBitmap.getWidth());
-//				thumbpath = photoFile.toString();
-//				Log.e(TAG, "get thumbpath==" + thumbpath);
+				// thumbpath = photoFile.toString();
+				// Log.e(TAG, "get thumbpath==" + thumbpath);
 				StartCamera();
 				// iPhotoCount++;
 				super.onActivityResult(requestCode, resultCode, data);
@@ -426,24 +530,27 @@ public class MainActivity extends Activity
 			}
 			else
 			{
-				// 退出拍照
+				// 锟剿筹拷锟斤拷锟斤拷
 				// File emptyFile = new File(LastFileName);
 				// boolean b=emptyFile.delete();
-//				Log.i(TAG, "lastpicPath: " + thumbpath);
+				// Log.i(TAG, "lastpicPath: " + thumbpath);
 				ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
+				// LayerDrawable
+				// thumbsImageView.setImageDrawable(drawable);
 				// thumbBitmap=getImageThumbnail(thumbpath, iwidth,iheight);
-				if(photoList.size()>0)
+				if (photoList.size() > 0)
 				{
-					thumbBitmap = ThumbnailUtils.extractThumbnail(
-							BitmapFactory.decodeFile(photoList.get(photoList.size()-1)), iwidth, iheight);
+					thumbBitmap = ThumbnailUtils.extractThumbnail(BitmapFactory
+							.decodeFile(photoList.get(photoList.size() - 1)),
+							iwidth, iheight);
 					if (thumbBitmap != null)
 						thumbsImageView.setImageBitmap(thumbBitmap);
 				}
-//				thumbBitmap = ThumbnailUtils.extractThumbnail(
-//						BitmapFactory.decodeFile(thumbpath), iwidth, iheight);
+				// thumbBitmap = ThumbnailUtils.extractThumbnail(
+				// BitmapFactory.decodeFile(thumbpath), iwidth, iheight);
 				// saveMyBitmap("thumbtest",thumbBitmap);
-//				if (thumbBitmap != null)
-//					thumbsImageView.setImageBitmap(thumbBitmap);
+				// if (thumbBitmap != null)
+				// thumbsImageView.setImageBitmap(thumbBitmap);
 				photoFile.delete();
 				TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
 				countTextView.setText(photoList.size() + " Photos");
@@ -453,26 +560,25 @@ public class MainActivity extends Activity
 
 			}
 
-		else
-			if (requestCode == REQUEST_LOCKER)
+		else if (requestCode == REQUEST_LOCKER)
+		{
+			if (resultCode == Activity.RESULT_OK)
+				m_blocked = false;
+		}
+		else if (requestCode == REQUEST_SCAN_BARCODE)
+		{
+			if (resultCode == Activity.RESULT_OK)
 			{
-				if (resultCode == Activity.RESULT_OK)
-					m_blocked = false;
-			}
-			else
-				if (requestCode == REQUEST_SCAN_BARCODE)
-				{
-					if (resultCode == Activity.RESULT_OK)
-					{
-						Bundle bundle = data.getExtras();
-						String pid = bundle.getString("pid");
-						Log.e(TAG, "REQUEST_SCAN_BARCODE==========>pid="
+				Bundle bundle = data.getExtras();
+				String pid = bundle.getString("pid");
+				Log.e(TAG,
+						"REQUEST_SCAN_BARCODE==========>pid="
 								+ bundle.getString("pid"));
-						EditText edit = (EditText) findViewById(R.id.edit);
-						edit.setText(pid);
-						// updateUploadButton();
-					}
-				}
+				TextView pidval = (TextView) findViewById(R.id.pidval);
+				pidval.setText(pid);
+				// updateUploadButton();
+			}
+		}
 		super.onActivityResult(requestCode, resultCode, data);
 	}
 
@@ -486,7 +592,7 @@ public class MainActivity extends Activity
 		catch (IOException e)
 		{
 			// TODO Auto-generated catch block
-			// DebugMessage.put("在保存图片时出错:" + e.toString());
+			// DebugMessage.put("锟节憋拷锟斤拷图片时锟斤拷锟斤拷" + e.toString());
 		}
 		FileOutputStream fOut = null;
 		try
@@ -522,17 +628,43 @@ public class MainActivity extends Activity
 		// TODO Auto-generated method stub
 		switch (item.getItemId())
 		{
-		case R.id.action_orientation:
-			if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
-				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
-			else
+			case R.id.action_clear:
+				clearfornew();
+				break;
+			case R.id.action_type_pid:
 			{
-				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
+	            final View edit = new EditText(this);
+	             new AlertDialog.Builder(this)
+	                .setIconAttribute(android.R.attr.alertDialogIcon)
+	                .setTitle(R.string.title_input_pid)
+	                .setView(edit)
+	                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
+	                    public void onClick(DialogInterface dialog, int whichButton) {
+	                    	String pid = ((EditText)edit).getText().toString();
+	                    	TextView pidval = (TextView) findViewById(R.id.pidval);
+	                    	pidval.setText(pid);              	
+	    
+	                        /* User clicked OK so do some stuff */
+	                    }
+	                })
+	                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
+	                    public void onClick(DialogInterface dialog, int whichButton) {
+
+	                        /* User clicked cancel so do some stuff */
+	                    }
+	                })
+	                .create().show();				
 			}
-			break;
-
-		default:
-			break;
+				break;
+			case R.id.action_view_queue:
+			{
+				  Intent intent = new Intent();
+				  intent.setClass(MainActivity.this, UploadQueueActivity.class);
+				  startActivity(intent);
+				break;
+			}
+			default:
+				break;
 		}
 		return super.onOptionsItemSelected(item);
 	}
@@ -548,204 +680,294 @@ public class MainActivity extends Activity
 		if (thumbBitmap != null)
 			outState.putByteArray("thumbBitmap", getBytes(thumbBitmap));// ("thumbBitmap",
 																		// (Object)thumbBitmap);
-//		outState.putString("thumbpath", thumbpath);
-		outState.putString("m_sName", m_sName);
-		outState.putString("m_sPassword", m_sPassword);
+																		// outState.putString("thumbpath",
+																		// thumbpath);
+		// outState.putString("m_sName", m_sName);
+		// outState.putString("m_sPassword", m_sPassword);
 
 		outState.putStringArrayList("photoList", photoList);
-//		Log.e(TAG, "save thumbpath==" + thumbpath);
+		// Log.e(TAG, "save thumbpath==" + thumbpath);
 		outState.putInt("iPhotoCount", photoList.size());
 	}
 
 	public static byte[] getBytes(Bitmap bitmap)
 	{
-		// 实例化字节数组输出流
+		// 实锟斤拷锟斤拷锟街斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟�
 		ByteArrayOutputStream baos = new ByteArrayOutputStream();
-		bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);// 压位图
-		return baos.toByteArray();// 创建分配字节数组
+		bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);// 压锟斤拷位图
+		return baos.toByteArray();// 锟斤拷锟斤拷锟斤拷锟斤拷锟街斤拷锟斤拷锟斤拷
 	}
 
 	public static Bitmap getBitmap(byte[] data)
 	{
 		if (data == null)
 			return null;
-		return BitmapFactory.decodeByteArray(data, 0, data.length);// 从字节数组解码位图
+		return BitmapFactory.decodeByteArray(data, 0, data.length);// 锟斤拷锟街斤拷锟斤拷锟斤拷锟斤拷锟轿煌�
 	}
 
 	private void clearfornew()
 	{
 		photoList.clear();
-		EditText edit = (EditText) findViewById(R.id.edit);
-		edit.setText("");
+		TextView pidval = (TextView) findViewById(R.id.pidval);
+		pidval.setText("");
 		updateUploadButton();
 		ImageView thumbsImageView = (ImageView) findViewById(R.id.ivThumbs);
-		thumbsImageView.setImageResource(R.drawable.no_pic);	
-		thumbBitmap=null;
+		thumbsImageView.setImageResource(R.drawable.no_pic);
+		thumbBitmap = null;
 		TextView countTextView = (TextView) findViewById(R.id.tvPhotoCount);
 		countTextView.setText("no photo");
 
 	}
-	public class UploadTask extends AsyncTask<Void, Void, Boolean>
-	{
-		String err_msg="";
-		@Override
-		protected Boolean doInBackground(Void... params)
-		{
-			boolean bret=true;
-
-
-			SQLiteDatabase db = dbUtil.OpenDB(MainActivity.this, null, true);
-			EditText edit = (EditText) findViewById(R.id.edit);
-			String pid = edit.getText().toString();
-
-			if (Network.NetworkIsAvailable(MainActivity.this))
-			{
-				int verifyresult = Network.VerifyUser(m_sName, m_sPassword);
-				if (verifyresult == Network.RESULT_TRUE)
-				{
-					/* user is authorized */
-					for (int i = 0; i < photoList.size(); i++)
-					{
-						int uploadresult = Network.UploadFile(photoList.get(i),
-								m_sName, m_sPassword, pid);
-						if (uploadresult != Network.RESULT_TRUE)
-						{
-							/*
-							 * upload failed write to local db upload when
-							 * connect to network next time;
-							 */
-
-							/*
-							 * serious error occur must notify user
-							 * immediately
-							 */
-							if (uploadresult == Network.RESULT_LOCALFILE_ERROR)
-								err_msg+="Warring! Local picture file not found!      ";
-							if( uploadresult == Network.RESULT_USERAUTH_ERROR)
-								err_msg+="Warring! Authorize check failed when uploading photos!      ";
-
-							ContentValues cv = new ContentValues();
-							cv.put("picker", m_sName);
-							cv.put("err_code", uploadresult);
-							cv.put("pid", pid);
-							cv.put("local_path", photoList.get(i));
-							db.insert("pics", null, cv);
-							bret=false;
-						}
-						else
-						{
-							/* upload success delete file */
-							File file = new File(photoList.get(i));
-							file.delete();
-						}
-
-					}
-
-				}
-				else
-					if (verifyresult == Network.RESULT_FALSE)
-					{
-						/*
-						 * user is not authorized serious error occur must
-						 * notify user
-						 */
-						Log.e(TAG, "notification====================>");
-						// String text=m_tvalert.getText().toString();
-						err_msg+="Warring! Authorize check failed when uploading photos!";
-						bret=false;
-						for (int i = 0; i < photoList.size(); i++)
-						{
-							ContentValues cv = new ContentValues();
-							cv.put("picker", m_sName);
-							cv.put("err_code", Network.RESULT_USERAUTH_ERROR);
-							cv.put("pid", pid);
-							cv.put("local_path", photoList.get(i));
-							db.insert("pics", null, cv);
-						}
-
-					}
-					else
-					{
-						/* an error occur */
-						for (int i = 0; i < photoList.size(); i++)
-						{
-							ContentValues cv = new ContentValues();
-							cv.put("picker", m_sName);
-							cv.put("err_code", Network.RESULT_NET_ERROR);
-							cv.put("pid", pid);
-							cv.put("local_path", photoList.get(i));
-							db.insert("pics", null, cv);
-						}
-						bret = false;
-					}
-			}
-			else
-			{
-				/*
-				 * net work is not available store into local DB it will auto
-				 * upload when connect to network next time;
-				 */
-
-				for (int i = 0; i < photoList.size(); i++)
-				{
-					ContentValues cv = new ContentValues();
-					cv.put("picker", m_sName);
-					cv.put("err_code", Network.RESULT_NET_ERROR);
-					cv.put("pid", pid);
-					cv.put("local_path", photoList.get(i));
-					db.insert("pics", null, cv);
-				}
-				bret=false;
-				// m_tvalert.setText("Upload failed when uploading photos!");
 
-			}
-
-			dbUtil.CloseDB(db);
-			return bret;
-		}
-
-		@Override
-		protected void onPostExecute(final Boolean success)
-		{
-			if(success)
-			{
-				m_tvalert.setTextColor(getResources().getColor(R.color.message_success));
-				m_tvalert.setText("Upload successed!");
-			}
-			else
-			{
-				m_tvalert.setTextColor(getResources().getColor(R.color.message_fail));
-				m_tvalert.setText(err_msg);
-			}
-			
-			clearfornew();
-			// mAuthTask = null;
-			// showProgress(false);
-			//
-			// if (success) {
-			//
-			// // SharedPreferences.Editor editor = RunOnce.edit();
-			// // editor.putBoolean("FirstRun"+globalUtil.getVerName(this),
-			// false);
-			// // // Don't forget to commit your edits!!!
-			// // editor.commit();
-			// Intent intent = new Intent();
-			// intent.setClass(LoginActivity.this, MainActivity.class);
-			// startActivity(intent);
-			// finish();
-			// } else {
-			// m_etPassword
-			// .setError(getString(R.string.error_incorrect_password));
-			// m_etPassword.requestFocus();
-			// }
-		}
+	// public class UploadTask extends AsyncTask<Void, Void, Boolean>
+	// {
+	// String err_msg="";
+	// @Override
+	// protected Boolean doInBackground(Void... params)
+	// {
+	// boolean bret=true;
+	//
+	//
+	// SQLiteDatabase db = dbUtil.OpenDB(MainActivity.this, null, true);
+	// EditText edit = (EditText) findViewById(R.id.edit);
+	// String pid = edit.getText().toString();
+	//
+	// if (Network.NetworkIsAvailable(MainActivity.this))
+	// {
+	// int verifyresult = Network.VerifyUser(m_sName, m_sPassword);
+	// if (verifyresult == Network.RESULT_TRUE)
+	// {
+	// /* user is authorized */
+	// for (int i = 0; i < photoList.size(); i++)
+	// {
+	// int uploadresult = Network.UploadFile(photoList.get(i),
+	// m_sName, m_sPassword, pid);
+	// if (uploadresult != Network.RESULT_TRUE)
+	// {
+	// /*
+	// * upload failed write to local db upload when
+	// * connect to network next time;
+	// */
+	//
+	// /*
+	// * serious error occur must notify user
+	// * immediately
+	// */
+	// if (uploadresult == Network.RESULT_LOCALFILE_ERROR)
+	// err_msg+="Warring! Local picture file not found!      ";
+	// if( uploadresult == Network.RESULT_USERAUTH_ERROR)
+	// err_msg+="Warring! Authorize check failed when uploading photos!      ";
+	//
+	// ContentValues cv = new ContentValues();
+	// cv.put("picker", m_sName);
+	// cv.put("err_code", uploadresult);
+	// cv.put("pid", pid);
+	// cv.put("local_path", photoList.get(i));
+	// db.insert("pics", null, cv);
+	// bret=false;
+	// }
+	// else
+	// {
+	// /* upload success delete file */
+	// File file = new File(photoList.get(i));
+	// file.delete();
+	// }
+	//
+	// }
+	//
+	// }
+	// else
+	// if (verifyresult == Network.RESULT_FALSE)
+	// {
+	// /*
+	// * user is not authorized serious error occur must
+	// * notify user
+	// */
+	// Log.e(TAG, "notification====================>");
+	// // String text=m_tvalert.getText().toString();
+	// err_msg+="Warring! Authorize check failed when uploading photos!";
+	// bret=false;
+	// for (int i = 0; i < photoList.size(); i++)
+	// {
+	// ContentValues cv = new ContentValues();
+	// cv.put("picker", m_sName);
+	// cv.put("err_code", Network.RESULT_USERAUTH_ERROR);
+	// cv.put("pid", pid);
+	// cv.put("local_path", photoList.get(i));
+	// db.insert("pics", null, cv);
+	// }
+	//
+	// }
+	// else
+	// {
+	// /* an error occur */
+	// for (int i = 0; i < photoList.size(); i++)
+	// {
+	// ContentValues cv = new ContentValues();
+	// cv.put("picker", m_sName);
+	// cv.put("err_code", Network.RESULT_NET_ERROR);
+	// cv.put("pid", pid);
+	// cv.put("local_path", photoList.get(i));
+	// db.insert("pics", null, cv);
+	// }
+	// bret = false;
+	// }
+	// }
+	// else
+	// {
+	// /*
+	// * net work is not available store into local DB it will auto
+	// * upload when connect to network next time;
+	// */
+	//
+	// for (int i = 0; i < photoList.size(); i++)
+	// {
+	// ContentValues cv = new ContentValues();
+	// cv.put("picker", m_sName);
+	// cv.put("err_code", Network.RESULT_NET_ERROR);
+	// cv.put("pid", pid);
+	// cv.put("local_path", photoList.get(i));
+	// db.insert("pics", null, cv);
+	// }
+	// bret=false;
+	// // m_tvalert.setText("Upload failed when uploading photos!");
+	//
+	// }
+	//
+	// dbUtil.CloseDB(db);
+	// return bret;
+	// }
+	//
+	// @Override
+	// protected void onPostExecute(final Boolean success)
+	// {
+	// if(success)
+	// {
+	// m_tvalert.setTextColor(getResources().getColor(R.color.message_success));
+	// m_tvalert.setText("Upload successed!");
+	// }
+	// else
+	// {
+	// m_tvalert.setTextColor(getResources().getColor(R.color.message_fail));
+	// m_tvalert.setText(err_msg);
+	// }
+	//
+	//
+	// // mAuthTask = null;
+	// // showProgress(false);
+	// //
+	// // if (success) {
+	// //
+	// // // SharedPreferences.Editor editor = RunOnce.edit();
+	// // // editor.putBoolean("FirstRun"+globalUtil.getVerName(this),
+	// // false);
+	// // // // Don't forget to commit your edits!!!
+	// // // editor.commit();
+	// // Intent intent = new Intent();
+	// // intent.setClass(LoginActivity.this, MainActivity.class);
+	// // startActivity(intent);
+	// // finish();
+	// // } else {
+	// // m_etPassword
+	// // .setError(getString(R.string.error_incorrect_password));
+	// // m_etPassword.requestFocus();
+	// // }
+	// }
+	//
+	// @Override
+	// protected void onCancelled()
+	// {
+	// // mAuthTask = null;
+	// // showProgress(false);
+	// }
+	// }
+	// public class SingleMediaScanner implements MediaScannerConnectionClient {
+	//
+	// private MediaScannerConnection mMs;
+	// private File mFile;
+	//
+	// public SingleMediaScanner(Context context, File f) {
+	// mFile = f;
+	// mMs = new MediaScannerConnection(context, this);
+	// mMs.connect();
+	// }
+	//
+	// public void onMediaScannerConnected() {
+	// Log.d(null, ""+mFile.getAbsolutePath());
+	// Log.d(null,
+	// ""+Environment.getExternalStorageDirectory().getPath()+"/photo/");
+	// Log.d(null, new
+	// File(Environment.getExternalStorageDirectory().getPath()+"/photo/").getAbsolutePath());
+	//
+	// mMs.scanFile(mFile.getAbsolutePath(), null);
+	// }
+	//
+	// public void onScanCompleted(String path, Uri uri) {
+	// Intent intent = new Intent(Intent.ACTION_VIEW);
+	// intent.setData(uri);
+	// startActivity(intent);
+	// mMs.disconnect();
+	// }
+	//
+	// }
 
-		@Override
-		protected void onCancelled()
-		{
-			// mAuthTask = null;
-			// showProgress(false);
-		}
-	}
+	private final BroadcastReceiver	MainActivityReceiver	= new BroadcastReceiver()
+														{
+
+															public void onReceive(
+																	Context context,
+																	Intent intent)
+															{
+																String action = intent
+																		.getAction();
+																// 濡傛灉鎹曟崏鍒扮殑action鏄疉CTION_BATTERY_CHANGED
+
+																if ("REDANT.POP.USER_CHECK_FAILED"
+																		.equals(action))
+																{
+																	m_tvalert
+																			.setTextColor(getResources()
+																					.getColor(
+																							R.color.message_fail));
+																	m_tvalert
+																			.setText("Upload failed:user verify failure.");
+
+																}
+																else if ("REDANT.POP.FINISH_UPLOAD_QUEUE"
+																		.equals(action))
+																{
+																	 m_tvalert.setTextColor(getResources().getColor(R.color.message_success));
+																	 m_tvalert.setText("Upload successes!");
+
+																}
+																else if ("REDANT.POP.FINISH_UPLOAD_QUEUE_WITH_ERROR"
+																		.equals(action))
+																{
+																	 m_tvalert.setTextColor(getResources().getColor(R.color.message_fail));
+																	 m_tvalert.setText("Upload finish with some error!");
+
+																}
+																else if (action
+																		.equals(Intent.ACTION_SCREEN_OFF))
+																{
+																	Log.e("hg",
+																			"锟秸碉拷锟姐播!!!=======>m_blocked="
+																					+ m_blocked);
+																	if (m_blocked == true)
+																		return;
+																	Intent activityintent = new Intent();
+																	activityintent
+																			.setClass(
+																					MainActivity.this,
+																					LockerActivity.class);
+																	startActivityForResult(
+																			activityintent,
+																			REQUEST_LOCKER);
+																	Log.e(TAG,
+																			"===================>start locker");
+																	m_blocked = true;
+																}
+															}
+														};
 
 }

+ 191 - 0
RedAnt Photo/src/com/usai/redant/photo/PhotoPreviewActivity.java

@@ -0,0 +1,191 @@
+package com.usai.redant.photo;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import android.R.integer;
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.media.ThumbnailUtils;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.view.ViewGroup;
+import android.view.Window;
+import android.view.animation.AnimationUtils;
+import android.widget.AdapterView;
+import android.widget.BaseAdapter;
+import android.widget.Gallery;
+import android.widget.HorizontalScrollView;
+import android.widget.ImageSwitcher;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.ViewSwitcher;
+import android.widget.Gallery.LayoutParams;
+import android.widget.ViewSwitcher.ViewFactory;
+
+public class PhotoPreviewActivity extends Activity implements
+		 ViewSwitcher.ViewFactory
+{
+
+	@Override
+	public void onCreate(Bundle savedInstanceState)
+	{
+		super.onCreate(savedInstanceState);
+		requestWindowFeature(Window.FEATURE_NO_TITLE);
+
+		setContentView(R.layout.activity_photo_preview);
+
+		mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
+		mSwitcher.setFactory(this);
+		mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
+				android.R.anim.fade_in));
+		mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
+				android.R.anim.fade_out));
+
+		pic_file = (ArrayList<String>) getIntent().getSerializableExtra(
+				"pic_list");
+
+		findViewById(R.id.hsv);
+		HorizontalScrollView hsv = (HorizontalScrollView) findViewById(R.id.hsv);
+		
+		LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout);
+	
+		for(int i=0;i<pic_file.size();i++)
+		{
+			ImageView imgview = new ImageView(this);
+//
+//			Bitmap thumb = thumbs.get(i);
+//			if (thumb == null)
+//			{
+				Log.d("getView", "create thumb position:" + i);
+				Bitmap thumb = ThumbnailUtils.extractThumbnail(
+						BitmapFactory.decodeFile(pic_file.get(i)), 160,
+						120);
+			//	thumbs.put(i, thumb);
+//			}
+			imgview.setImageBitmap(thumb);
+			// i.setImageResource(mThumbIds[position]);
+			imgview.setAdjustViewBounds(true);
+			LinearLayout.LayoutParams searchParams = new LinearLayout.LayoutParams(
+					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1);
+			searchParams.leftMargin = 40;
+			imgview.setScaleType(ImageView.ScaleType.FIT_CENTER);
+			imgview.setLayoutParams(searchParams);
+			imgview.setBackgroundResource(R.drawable.picture_frame);
+			imgview.setTag(pic_file.get(i));
+			imgview.setOnClickListener(new OnClickListener()
+			{
+				
+				@Override
+				public void onClick(View v)
+				{
+					v.getTag();
+					mSwitcher.setImageURI(Uri.fromFile(new File(v.getTag().toString())));
+					// TODO Auto-generated method stub
+					
+				}
+			});
+			
+			ll.addView(imgview);
+			
+			
+			mSwitcher.setImageURI(Uri.fromFile(new File(pic_file.get(0))));
+			
+		}
+		// hsv.inflate(context, resource, root)
+
+		// Gallery g = (Gallery) findViewById(R.id.gallery);
+		// g.setAdapter(new ImageAdapter(this));
+		// g.setOnItemSelectedListener(this);
+	}
+
+//	public void onItemSelected(AdapterView<?> parent, View v, int position,
+//			long id)
+//	{
+//		mSwitcher.setImageURI(Uri.fromFile(new File(pic_file.get(position))));
+//		// mSwitcher.setImageResource(mImageIds[position]);
+//	}
+//
+//	public void onNothingSelected(AdapterView<?> parent)
+//	{
+//	}
+
+	public View makeView()
+	{
+		ImageView i = new ImageView(this);
+		i.setBackgroundColor(0xFF000000);
+		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
+		i.setLayoutParams(new ImageSwitcher.LayoutParams(
+				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
+		return i;
+	}
+
+	private ImageSwitcher	mSwitcher;
+
+//	public class ImageAdapter extends BaseAdapter
+//	{
+//		public ImageAdapter(Context c)
+//		{
+//			mContext = c;
+//		}
+//
+//		public int getCount()
+//		{
+//			return pic_file.size();// mThumbIds.length;
+//		}
+//
+//		public Object getItem(int position)
+//		{
+//			return position;
+//		}
+//
+//		public long getItemId(int position)
+//		{
+//			return position;
+//		}
+//
+//		public View getView(int position, View convertView, ViewGroup parent)
+//		{
+//			ImageView i = new ImageView(mContext);
+//
+//			Bitmap thumb = thumbs.get(position);
+//			if (thumb == null)
+//			{
+//				Log.d("getView", "create thumb position:" + position);
+//				thumb = ThumbnailUtils.extractThumbnail(
+//						BitmapFactory.decodeFile(pic_file.get(position)), 320,
+//						240);
+//				thumbs.put(position, thumb);
+//			}
+//			i.setImageBitmap(thumb);
+//			// i.setImageResource(mThumbIds[position]);
+//			i.setAdjustViewBounds(true);
+//			i.setLayoutParams(new Gallery.LayoutParams(
+//					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
+//			i.setBackgroundResource(R.drawable.picture_frame);
+//			return i;
+//		}
+//
+//		private Context	mContext;
+//
+//	}
+
+	ArrayList<String>			pic_file;
+//	HashMap<Integer, Bitmap>	thumbs	= new HashMap<Integer, Bitmap>();
+	// private Integer[] mThumbIds = {
+	// };
+
+	// private Integer[] mImageIds = {
+	// };
+
+}

+ 35 - 0
RedAnt Photo/src/com/usai/redant/photo/RedAntApplication.java

@@ -0,0 +1,35 @@
+package com.usai.redant.photo;
+
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import android.app.Application;
+import android.content.Intent;
+
+public class RedAntApplication extends Application
+{
+    private static RedAntApplication instance;  
+    public static ReadWriteLock lock = new ReentrantReadWriteLock(true);  
+    public static Lock writeLock   = lock.writeLock();   
+    public static String user;
+    public static String password;
+    public static RedAntApplication getInstance() {  
+        return instance;  
+    }  
+  
+    @Override  
+    public void onCreate() {  
+        // TODO Auto-generated method stub  
+        super.onCreate();  
+        instance = this;  
+        
+		Intent intentservice = new Intent();
+		intentservice.setClass( this, UploadService.class);
+//		if (intent.getExtras() != null)
+//			intentservice.putExtras(intent.getExtras());
+//		intentservice.setAction(intent.getAction());
+		startService(intentservice);
+		
+    }  
+}

+ 335 - 0
RedAnt Photo/src/com/usai/redant/photo/UploadQueueActivity.java

@@ -0,0 +1,335 @@
+package com.usai.redant.photo;
+
+import java.io.File;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import com.usai.util.Network;
+import com.usai.util.dbUtil;
+
+import android.app.ListActivity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.graphics.Color;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.SimpleCursorAdapter;
+import android.widget.TextView;
+
+public class UploadQueueActivity extends ListActivity
+{
+	private SQLiteDatabase m_db = null;
+	private Cursor m_cursor = null;
+	RecordsAdapter m_listadapter;
+	private TextView					m_tvalert;
+	Timer timer = new Timer();
+	TimerTask task = new TimerTask()
+	{
+		boolean change = false;
+		public void run()
+		{
+		 
+			runOnUiThread(new Runnable()
+			{
+				public void run()
+				{
+					if (change)
+					{
+						change = false;
+						m_tvalert.setTextColor(Color.TRANSPARENT); // 这个是透明,=看不到文字
+					}
+					else
+					{
+						change = true;
+						m_tvalert.setTextColor(getResources().getColor(
+								R.color.message_success));
+					}
+				}
+			});
+		}
+	};
+	public class RecordsAdapter extends SimpleCursorAdapter
+	{
+
+
+		public RecordsAdapter(Context context, int layout, Cursor c,
+				String[] from, int[] to)
+		{
+			
+			super(context, layout, c, from, to);
+			// TODO Auto-generated constructor stub
+		}
+
+		
+
+		@Override
+		public void bindView(View view, Context context, Cursor cursor)
+		{
+			 String path = cursor.getString(3);
+			 int err_code = cursor.getInt(1);
+
+			File f = new File(path);
+			final String filename=f.getName();
+		
+			final TextView filetext = (TextView) view.findViewById(R.id.filename);
+			filetext.setText(filename);
+			
+			final TextView err_codetext = (TextView) view.findViewById(R.id.err_code);
+			switch (err_code)
+			{
+				case Network.RESULT_LOCALFILE_ERROR:
+					err_codetext.setText("Local file error.");
+					break;
+				case Network.RESULT_NET_ERROR:
+					err_codetext.setText("Network error.");
+					break;
+				case Network.RESULT_USERAUTH_ERROR:
+					err_codetext.setText("User authorization error.");
+					break;
+				case Network.RESULT_ERROR:
+					err_codetext.setText("Unknown error.");
+					break;
+				case Network.RESULT_FALSE:
+					err_codetext.setText("Upload failed.");
+					break;
+				case Network.STATUS_WAIT:
+					err_codetext.setText("Wait for upload.");
+					break;
+			
+				default:
+					break;
+			}
+			super.bindView(view, context, cursor);
+
+	
+
+		}
+
+	}
+
+	@Override
+	protected void onDestroy()
+	{
+		unregisterReceiver(UploadQueueReceiver);
+		dbUtil.CloseDB(m_db);
+		super.onDestroy();
+	}
+
+	@Override
+	protected void onCreate(Bundle savedInstanceState)
+	{
+		super.onCreate(savedInstanceState);
+//		user = ApexTrackingApplication.get_user();
+//		
+//		password = ApexTrackingApplication.get_pass();
+//		function_name = getIntent().getStringExtra("function_name");
+		setContentView(R.layout.activity_search);
+		m_db = dbUtil.OpenDB(this, null, true);
+		// m_TextView = (TextView) findViewById(R.id.summarytext);
+		// m_TextView.setText(getString(m_Activityinfo.TextViewValue));
+		// m_ListView = (ListView) findViewById(android.R.id.list);
+		m_cursor = m_db.query("pics", new String[] { "picker",
+				"err_code", "pid", "local_path","_id" }, null, null, null, null,
+				"_id", null);
+		startManagingCursor(m_cursor);
+		m_listadapter = new RecordsAdapter(this,
+		// Use a template that displays a text view
+				R.layout.search_lvitem_edit,
+				// Give the cursor to the list adatper
+				m_cursor,
+				// Map the NAME column in the people database to...
+				new String[] { "pid",  "picker" },
+				// The "text1" view defined in the XML template
+				new int[] { R.id.pidval, R.id.picker });
+		setListAdapter(m_listadapter);
+//		Button btnok = (Button) findViewById(R.id.btnok);
+//		btnok.setOnClickListener(this);
+//		Button btncancel = (Button) findViewById(R.id.btncancel);
+//		btncancel.setOnClickListener(this);
+//
+//		SharedPreferences RunOnce = getSharedPreferences("Apex", 0);
+
+//		String vername;
+//		try
+//		{
+//			vername = getPackageManager().getPackageInfo("com.usai.apex", 0).versionName;
+//			boolean bFirstRun = RunOnce.getBoolean("FirstRun" + vername
+//					+ "_search", true);
+//			if (bFirstRun)
+//			{
+//				SharedPreferences.Editor editor = RunOnce.edit();
+//				editor.putBoolean("FirstRun" + vername + "_search", false);
+//				// Don't forget to commit your edits!!!
+//				editor.commit();
+//				Intent intent = new Intent();
+//				intent.setClass(this, HelpActivity.class);
+//				intent.putExtra("caller", "search");
+//				startActivity(intent);
+//
+//			}
+//		}
+//		catch (NameNotFoundException e)
+//		{
+//			// TODO Auto-generated catch block
+//			e.printStackTrace();
+//		}
+		// initlist();
+
+		// m_ListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
+
+		// m_listadapter = new FieldsAdapter(this, data, resource, from, to);
+
+		// m_listadapter = new RecordsAdapter(this,
+		// // Use a template that displays a text view
+		// m_iListItemID,
+		// // Give the cursor to the list adatper
+		// m_cursor,
+		// // Map the NAME column in the people database to...
+		// m_sDispFields,
+		// // The "text1" view defined in the XML template
+		// m_iViewIDs);
+		IntentFilter msgFilter = new IntentFilter();
+		
+		msgFilter.addAction("REDANT.POP.UPDATE_QUEUE_VIEW");
+		msgFilter.addAction("REDANT.POP.UPLOAD_STATE_TRUE");
+		msgFilter.addAction("REDANT.POP.UPLOAD_STATE_FALSE");
+		msgFilter.addAction("REDANT.POP.FINISH_UPLOAD_QUEUE");
+		
+		registerReceiver(UploadQueueReceiver, msgFilter);
+		
+		m_tvalert = (TextView) findViewById(R.id.tvalert);
+		m_tvalert.setSelected(true);
+
+		
+		//timer.schedule(task, 1, 300); // 参数分别是delay(多长时间后执行),duration(执行间隔)
+		sendBroadcast(new Intent("REDANT.POP.QUERY_UPLOAD_STATE"));
+		
+	}
+
+//	private void RefreshList()
+//	{
+//		// if (dbUtil.isRecordExist(m_db,
+//		// "user_numberlist","type = "+m_Activityinfo.NumberType))
+//		// {
+//		// m_TextView.setVisibility(ListView.INVISIBLE);
+//		// m_ListView.setVisibility(ListView.VISIBLE);
+//		//
+//		// }
+//		// else
+//		// {
+//		// m_TextView.setVisibility(ListView.VISIBLE);
+//		// m_ListView.setVisibility(ListView.INVISIBLE);
+//		// }
+//		hashMap.clear();
+//		m_cursor.requery();
+//	}
+
+	// private void initlist()
+	// {
+	// m_ListView = (ListView) findViewById(android.R.id.list);
+	// ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String,
+	// Object>>();
+	// HashMap<String, Object> map = null;
+	//
+	// String[] strings = { "alias", "type", "name" };// Map的key集合数组
+	// int[] ids = { R.id.aliasName, R.id.tv_type };// 对应布局文件的id
+	// SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,
+	// R.layout.search_lvitem_edit, strings, ids);
+	//
+	// // listView1.setAdapter(simpleAdapter);//绑定适配器
+	// setListAdapter(simpleAdapter);
+	// }
+
+//	@Override
+//	public boolean onCreateOptionsMenu(Menu menu)
+//	{
+//		// Inflate the menu; this adds items to the action bar if it is present.
+//		getMenuInflater().inflate(R.menu.search, menu);
+//		return true;
+//	}
+
+//	@Override
+//	public boolean onOptionsItemSelected(MenuItem item)
+//	{
+//		Intent intent = new Intent();
+//		switch (item.getItemId())
+//		{
+//		case R.id.action_custom_fields:
+//			intent.setClass(this, CustomizeFieldsActivity.class);
+//			intent.putExtra("user", user);
+//			// intent.putExtra("password", password);
+//			intent.putExtra("function_name", function_name);
+//			intent.putExtra("behavior", Network.BEHAVIOR_SEARCH);
+//			startActivity(intent);
+//			break;
+//		case R.id.action_help:
+//			// Intent intent = new Intent();
+//			intent.setClass(this, HelpActivity.class);
+//			intent.putExtra("caller", "search");
+//			// // intent.putExtra("password", password);
+//			// intent.putExtra("function_name", function_name);
+//			// intent.putExtra("behavior", Network.BEHAVIOR_SEARCH);
+//			startActivity(intent);
+//			break;
+//		default:
+//			break;
+//		}
+//		return super.onOptionsItemSelected(item);
+//	}
+	private final BroadcastReceiver	UploadQueueReceiver	= new BroadcastReceiver()
+	{
+
+		public void onReceive(
+				Context context,
+				Intent intent)
+		{
+			String action = intent
+					.getAction();
+			// 如果捕捉到的action是ACTION_BATTERY_CHANGED
+
+			if ("REDANT.POP.UPDATE_QUEUE_VIEW"
+					.equals(action))
+			{
+				m_cursor.requery();
+				
+
+			}
+			else if ("REDANT.POP.UPLOAD_STATE_FALSE"
+					.equals(action))
+			{
+				timer.cancel();
+				m_tvalert.setText("");
+//				m_tvalert.setTextColor(getResources().getColor(
+//						R.color.message_success));
+				
+				
+				
+			}
+			else if ("REDANT.POP.UPLOAD_STATE_TRUE"
+					.equals(action))
+			{
+				m_tvalert.setText("Uploading ...");
+				timer.schedule(task, 1, 300);
+				
+				
+			}
+			else if ("REDANT.POP.FINISH_UPLOAD_QUEUE"
+					.equals(action))
+			{
+				timer.cancel();
+				m_tvalert.setText("Finish upload.");
+				m_tvalert.setTextColor(getResources().getColor(
+						R.color.message_success));
+				
+				
+			}
+			
+		}
+	};
+	
+}

+ 247 - 2
RedAnt Photo/src/com/usai/redant/photo/UploadService.java

@@ -1,15 +1,260 @@
 package com.usai.redant.photo;
 
+import java.io.File;
+
+import com.usai.util.Crypto;
+import com.usai.util.Network;
+import com.usai.util.dbUtil;
+
 import android.app.Service;
+import android.content.BroadcastReceiver;
+import android.content.ContentValues;
+import android.content.Context;
 import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
+import android.os.Bundle;
 import android.os.IBinder;
+import android.util.Log;
+import android.widget.EditText;
+
+public class UploadService extends Service
+{
+
+	private UploadThread	uploadThread;
 
-public class UploadService extends Service {
+	private boolean			queue_changed	= false;
 
 	@Override
-	public IBinder onBind(Intent intent) {
+	public IBinder onBind(Intent intent)
+	{
 		// TODO Auto-generated method stub
 		return null;
 	}
 
+	@Override
+	public void onCreate()
+	{
+
+		Log.e("", "create upload Service!!!");
+		if (uploadThread == null)
+		{
+			uploadThread = new UploadThread();
+			Log.e("", "create upload thread!!!");
+			// upleadThread.start();
+
+		}
+		
+		IntentFilter msgFilter = new IntentFilter();
+		
+		msgFilter.addAction("REDANT.POP.MODIFY_QUEUE");
+		msgFilter.addAction("REDANT.POP.QUERY_UPLOAD_STATE");
+
+		
+		registerReceiver(uploadReceiver, msgFilter);
+//		registerReceiver(uploadReceiver,
+//				new IntentFilter("modify upload queue"));
+		super.onCreate();
+
+	}
+
+	void loadlist()
+	{
+
+	}
+
+	public class UploadThread extends Thread
+	{
+		@Override
+		public void run()
+		{
+
+			Log.e("", "upload thread running");
+
+			super.run();
+			doupload();
+			Log.e("", "upload thread stop");
+
+		}
+
+		private void doupload()
+		{
+			boolean error = false;
+			boolean didupload = false;
+			// int verifyresult = Network.VerifyUser(RedAntApplication.user,
+			// RedAntApplication.password);
+			// if (verifyresult == Network.RESULT_TRUE)
+			// {
+			SQLiteDatabase dbr = dbUtil.OpenDB(UploadService.this, null, false);
+			Cursor cursor = dbr.query("pics", new String[] { "_id", "pid",
+					"local_path", "picker" }, "err_code!="
+					+ Network.AP_UPLOAD_SUCCESS, null, null, null, "_id", null);
+			while (cursor.moveToNext())
+			{
+				didupload = true;
+				if (queue_changed)
+				{
+					queue_changed = false;
+					dbUtil.CloseCursor(cursor);
+					cursor = dbr.query("pics", new String[] { "_id", "pid",
+							"local_path", "picker" }, "err_code!="
+							+ Network.AP_UPLOAD_SUCCESS, null, null, null,
+							"_id", null);
+					if (!cursor.moveToNext())
+						break;
+
+				}
+				int _id = cursor.getInt(0);
+				String pid = cursor.getString(1);
+				String path = cursor.getString(2);
+				String picker = cursor.getString(3);
+				
+				
+				String encryptUser="";
+				
+				try
+				{
+					encryptUser=Crypto.encrypt("apexu", picker);
+					
+				}
+				catch (Exception e1)
+				{
+					// TODO Auto-generated catch block
+					e1.printStackTrace();
+				}
+				
+				Cursor cursor_user = dbr.query("users",
+						new String[] { "pass" }, "name='" + encryptUser + "'", null,
+						null, null, "_id", null);
+				String pass = "";
+				if (cursor_user.moveToNext())
+					pass = cursor_user.getString(0);
+				try
+				{
+					pass = Crypto.decrypt("apexp", pass);
+				}
+				catch (Exception e)
+				{
+					// TODO Auto-generated catch block
+					e.printStackTrace();
+				}
+				
+				int uploadresult = Network.UploadFile(path, picker, pass, pid);
+				if (uploadresult == Network.RESULT_TRUE)
+				{
+					RedAntApplication.writeLock.lock();
+
+					{
+						// write sql process
+						SQLiteDatabase dbw = dbUtil.OpenDB(UploadService.this,
+								null, true);
+						// String sql = "update pics set err_code ="
+						// + Network.AP_UPLOAD_SUCCESS + " where _id="
+						// + _id;
+						String sql = "delete from pics  where _id=" + _id;
+						dbw.execSQL(sql);
+						File pic = new File(path);
+						pic.delete();
+						dbUtil.CloseDB(dbw);
+					}
+					RedAntApplication.writeLock.unlock();
+				}
+				else
+				{
+					error = true;
+					RedAntApplication.writeLock.lock();
+
+					{
+						// write sql process
+						SQLiteDatabase dbw = dbUtil.OpenDB(UploadService.this,
+								null, true);
+						String sql = "update pics set err_code ="
+								+ uploadresult + " where _id=" + _id;
+
+						dbw.execSQL(sql);
+						dbUtil.CloseDB(dbw);
+					}
+					RedAntApplication.writeLock.unlock();
+				}
+
+				sendBroadcast(new Intent("REDANT.POP.UPDATE_QUEUE_VIEW"));
+			}
+
+			dbUtil.CloseCursor(cursor);
+			dbUtil.CloseDB(dbr);
+
+			// }
+			// else
+			// {
+			// Log.e("upload thread", "user check failed!");
+			//
+			// sendBroadcast(new Intent("REDANT.POP.USER_CHECK_FAILED"));
+			// }
+
+			if (queue_changed)
+			{
+				queue_changed = false;
+				doupload();
+			}
+			if (didupload)
+			{
+				if (error)
+					sendBroadcast(new Intent(
+							"REDANT.POP.FINISH_UPLOAD_QUEUE_WITH_ERROR"));
+				else
+					sendBroadcast(new Intent("REDANT.POP.FINISH_UPLOAD_QUEUE"));
+			}
+		}
+	}
+
+	private BroadcastReceiver	uploadReceiver	= new BroadcastReceiver()
+												{
+
+													public void onReceive(
+															Context context,
+															Intent intent)
+													{
+														String action = intent
+																.getAction();
+														// 如果捕捉到的action是ACTION_BATTERY_CHANGED
+
+														if ("REDANT.POP.MODIFY_QUEUE"
+																.equals(action))
+														{
+															Log.e("uploadservice",
+																	"recieve upload queue change");
+															if (uploadThread != null)
+															{
+																if (uploadThread
+																		.isAlive())
+																{
+
+																	Log.e("uploadReceiver",
+																			"upload thread alive");
+																}
+																else
+																{
+																	Log.e("uploadReceiver",
+																			"start upload thread");
+																	uploadThread = new UploadThread();
+																	uploadThread
+																			.start();
+																}
+															}
+														}
+														else if ("REDANT.POP.QUERY_UPLOAD_STATE"
+																.equals(action))
+														{
+															if (uploadThread
+																	.isAlive())
+															{
+																sendBroadcast(new Intent("REDANT.POP.UPLOAD_STATE_TRUE"));
+															}
+															else {
+																sendBroadcast(new Intent("REDANT.POP.UPLOAD_STATE_FALSE"));
+															}
+														}
+													}
+												};
 }

+ 133 - 0
RedAnt Photo/src/com/usai/util/Crypto.java

@@ -0,0 +1,133 @@
+package com.usai.util;
+
+import java.security.SecureRandom;
+
+import javax.crypto.Cipher;
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * Usage:
+ * 
+ * <pre>
+ * String crypto = Crypto.encrypt(masterpassword, cleartext) 
+ * ... 
+ * String cleartext = Crypto.decrypt(masterpassword, crypto)
+ * </pre>
+ * 
+ * @author ferenc.hechler
+ */
+public class Crypto
+{
+//    public static SecretKeySpec setSecretKey(String password) throws Exception {
+//        SecretKeySpec key = null;
+//        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
+//        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
+//        sr.setSeed(password.getBytes());
+//        kgen.init(128, sr);
+//        SecretKey secretKey = kgen.generateKey();
+//        byte[] enCodeFormat = secretKey.getEncoded();
+//        key = new SecretKeySpec(enCodeFormat, SecretKeySpec.ALGORITHM);
+//
+//        return key;
+//    }
+
+	public static String encrypt(String seed, String cleartext)
+			throws Exception
+	{
+		byte[] rawKey = getRawKey(seed.getBytes());
+		byte[] result = encrypt(rawKey, cleartext.getBytes());
+		return toHex(result);
+	}
+
+	public static String decrypt(String seed, String encrypted)
+			throws Exception
+	{
+		byte[] rawKey = getRawKey(seed.getBytes());
+		byte[] enc = toByte(encrypted);
+		byte[] result = decrypt(rawKey, enc);
+		return new String(result);
+	}
+
+	private static byte[] getRawKey(byte[] seed) throws Exception
+	{
+		
+        KeyGenerator kgen = KeyGenerator.getInstance("AES");
+        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
+        sr.setSeed(seed);
+        kgen.init(128, sr);
+        SecretKey secretKey = kgen.generateKey();	
+        byte[] enCodeFormat = secretKey.getEncoded();
+//        key = new SecretKeySpec(enCodeFormat, SecretKeySpec.ALGORITHM);
+        return enCodeFormat;
+//
+//        return key;	
+//		KeyGenerator kgen = KeyGenerator.getInstance("AES");
+//		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
+//		sr.setSeed(seed);
+//		kgen.init(128, sr); // 192 and 256 bits may not be available
+//		SecretKey skey = kgen.generateKey();
+//		byte[] raw = skey.getEncoded();
+//		return raw;
+	}
+
+	private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception
+	{
+		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+		Cipher cipher = Cipher.getInstance("AES");
+		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
+		byte[] encrypted = cipher.doFinal(clear);
+		return encrypted;
+	}
+
+	private static byte[] decrypt(byte[] raw, byte[] encrypted)
+			throws Exception
+	{
+		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
+		Cipher cipher = Cipher.getInstance("AES");
+		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
+		byte[] decrypted = cipher.doFinal(encrypted);
+		return decrypted;
+	}
+
+	public static String toHex(String txt)
+	{
+		return toHex(txt.getBytes());
+	}
+
+	public static String fromHex(String hex)
+	{
+		return new String(toByte(hex));
+	}
+
+	public static byte[] toByte(String hexString)
+	{
+		int len = hexString.length() / 2;
+		byte[] result = new byte[len];
+		for (int i = 0; i < len; i++)
+			result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
+					16).byteValue();
+		return result;
+	}
+
+	public static String toHex(byte[] buf)
+	{
+		if (buf == null)
+			return "";
+		StringBuffer result = new StringBuffer(2 * buf.length);
+		for (int i = 0; i < buf.length; i++)
+		{
+			appendHex(result, buf[i]);
+		}
+		return result.toString();
+	}
+
+	private final static String HEX = "0123456789ABCDEF";
+
+	private static void appendHex(StringBuffer sb, byte b)
+	{
+		sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
+	}
+
+}

+ 627 - 258
RedAnt Photo/src/com/usai/util/Network.java

@@ -2,217 +2,352 @@ package com.usai.util;
 
 import java.io.BufferedReader;
 import java.io.File;
+import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.util.Set;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
 
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
+import org.apache.http.HttpVersion;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ClientConnectionManager;
 import org.apache.http.conn.ConnectTimeoutException;
+import org.apache.http.conn.scheme.PlainSocketFactory;
+import org.apache.http.conn.scheme.Scheme;
+import org.apache.http.conn.scheme.SchemeRegistry;
+import org.apache.http.conn.ssl.SSLSocketFactory;
 import org.apache.http.entity.mime.HttpMultipartMode;
 import org.apache.http.entity.mime.MultipartEntity;
 import org.apache.http.entity.mime.content.FileBody;
 import org.apache.http.entity.mime.content.StringBody;
 import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
 import org.apache.http.params.BasicHttpParams;
 import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.params.HttpParams;
+import org.apache.http.params.HttpProtocolParams;
+import org.apache.http.protocol.HTTP;
+import org.json.JSONException;
 import org.json.JSONObject;
 
+import com.usai.redant.photo.RedAntApplication;
+
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
+import android.os.Bundle;
 import android.util.Log;
 
 public class Network
 {
-	private static final int REQUEST_TIMEOUT = 5 * 1000;// request time out 20
-														// secs
-	private static final int SO_TIMEOUT = 5 * 1000; // so time out 20 secs;
-	public static int AP_USER_AUTH = 1;
-	public static int AP_USER_NOT_AUTH = 2;
-	public static int AP_USER_NOT_EXIST = 3;
-	public static int AP_UPLOAD_SUCCESS = 4;
-	public static int AP_UPLOAD_FAIL = 5;
-//
-	public static final int RESULT_FALSE = 0;
-	public static final int RESULT_TRUE = 1;
-	public static final int RESULT_NET_ERROR = 3;
-	public static final int RESULT_ERROR = 5;
-	public static final int RESULT_LOCALFILE_ERROR= 7;
-	public static final int RESULT_USERAUTH_ERROR = 9;
-//	public static final int RESULT_NOCONNECT = 2;
-//	public static final int RESULT_CONNECT = 3;
-//	public static final int RESULT_TIMEOUT = 4;
-//	public static final int RESULT_RESPONSE_NULL= 6;
-//	public static final int RESULT_ERR_USERAUTH= 8;
-
-//	enum RES_VERIFYUSER{RESULT_FALSE,RESULT_TRUE,}
-//	public static int PROTOCAL_FALSE = 0;
-//	public static int PROTOCAL_TRUE = 1;
-//	public static int PROTOCAL_NOT_AUTH = 2;
-//	public static int PROTOCAL_SUCCESS = 1;
-//	public static int PROTOCAL_FAILED = 1;
-	// public static int PROTOCAL_MORE=4;
-//	public static int ERR_LOCALFILE = 0;
-
-//	static String URL_JSON_TEST = "http://192.168.23.1/xampp/json_test.php";
-//	static String URL_VERIFY_USER = "http://192.168.1.10/xampp/verify_user.php";
-//	static String URL_UPLOAD_PHOTO = "http://192.168.1.10/xampp/save_upload_file.php";
-	static String URL_VERIFY_USER = "http://69.199.249.16/handset_login.php";
-	static String URL_UPLOAD_PHOTO = "http://69.199.249.16/handset.php";
-
-//	public static String VerifyUser(String user, String password,
-//			Context context)
-//	{
-//		String TAG = "net_dbg@VerifyUser";
-//		Log.d(TAG, "entry");
-//		try
-//		{
-//			BasicHttpParams httpParams = new BasicHttpParams();
-//			HttpConnectionParams.setConnectionTimeout(httpParams,
-//					REQUEST_TIMEOUT);
-//			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
-//			HttpClient client = new DefaultHttpClient(httpParams);
-//			HttpPost post = new HttpPost(URL_VERIFY_USER);
-//			MultipartEntity reqEntity = new MultipartEntity(
-//					HttpMultipartMode.BROWSER_COMPATIBLE);
-//			reqEntity.addPart("user", new StringBody(user));
-//			reqEntity.addPart("password", new StringBody(password));
-//
-//			post.setEntity(reqEntity);
-//			HttpResponse response = client.execute(post);
-//			int statucode = response.getStatusLine().getStatusCode();
-//			if (statucode == HttpStatus.SC_OK)
-//			{
-//				HttpEntity resEntity = response.getEntity();
-//				if (resEntity != null)
-//				{
-//					Log.d(TAG,
-//							"Response: content len==>"
-//									+ resEntity.getContentLength());
-//					InputStream is = resEntity.getContent();
-//					try
-//					{
-//
-//						BufferedReader br = new BufferedReader(
-//								new InputStreamReader(is, "utf-8"), 8);
-//						StringBuilder sb = new StringBuilder();
-//						String line = null;
-//						while ((line = br.readLine()) != null)
-//						{
-//							sb.append(line + "\n");
-//						}
-//
-//						Log.d(TAG, "Response: content begin");
-//						Log.d(TAG, sb.toString());
-//						Log.d(TAG, "Response: content end");
-//						return sb.toString();
-//					}
-//					catch (Exception e)
-//					{
-//						Log.e(TAG, e.toString());
-//						// TODO: handle exception
-//					}
-//					finally
-//					{
-//						is.close();
-//
-//					}
-//
-//				}
-//				else
-//				{
-//					/*
-//					 * resEntity is null
-//					 */
-//					Log.d(TAG, "RESPONSE ENTITY IS NULL");
-//					return null;
-//				}
-//
-//			}
-//			else
-//			{
-//				/*
-//				 * Http error; out put error code;
-//				 */
-//				Log.d(TAG, "HTTP " + statucode);
-//
-//				HttpEntity resEntity = response.getEntity();
-//				if (resEntity != null)
-//				{
-//
-//					InputStream is = resEntity.getContent();
-//					try
-//					{
-//
-//						BufferedReader br = new BufferedReader(
-//								new InputStreamReader(is, "utf-8"), 8);
-//						StringBuilder sb = new StringBuilder();
-//						String line = null;
-//						while ((line = br.readLine()) != null)
-//						{
-//							sb.append(line + "\n");
-//						}
-//
-//						Log.d(TAG, "Response: content begin");
-//						Log.d(TAG, sb.toString());
-//						Log.d(TAG, "Response: content end");
-//						return null;
-//					}
-//					catch (Exception e)
-//					{
-//						Log.e(TAG, e.toString());
-//						// TODO: handle exception
-//					}
-//					finally
-//					{
-//						is.close();
-//
-//					}
-//
-//				}
-//				else
-//				{
-//					/*
-//					 * resEntity is null
-//					 */
-//					Log.e(TAG, "RESPONSE ENTITY IS NULL");
-//					return null;
-//				}
-//				return null;
-//			}
-//
-//		}
-//		catch (ConnectTimeoutException e)
-//		{
-//			Log.d(TAG, "request time out");
-//
-//		}
-//		catch (Exception e)
-//		{
-//			Log.d(TAG, e.toString());
-//		}
-//		return null;
-//	}
+	private static final int	REQUEST_TIMEOUT					= 15 * 1000;										// request
+																													// time
+																													// out
+																													// 20
+																													// secs
+	private static final int	SO_TIMEOUT						= 15 * 1000;										// so
+																													// time
+																													// out
+																													// 20
+																													// secs;
+	public static int			AP_USER_AUTH					= 1;
+	public static int			AP_USER_NOT_AUTH				= 2;
+	public static int			AP_USER_NOT_EXIST				= 3;
+	public static int			AP_UPLOAD_SUCCESS				= 4;
+	public static int			AP_UPLOAD_FAIL					= 5;
+	//
+	// public static final int RESULT_FALSE = 0;
+	// public static final int RESULT_TRUE = 1;
+	// public static final int RESULT_NET_ERROR = 3;
+	// public static final int RESULT_ERROR = 5;
+	// public static final int RESULT_LOCALFILE_ERROR= 7;
+	// public static final int RESULT_USERAUTH_ERROR = 9;
+
+	public static int			AP_MESSAGE_NEW					= 5;
+	public static int			AP_MESSAGE_NONE					= 6;
+	//
+	public static final int		RESULT_FALSE					= 0;
+	public static final int		RESULT_TRUE						= -1;
+	public static final int		RESULT_NET_ERROR				= -3;
+	public static final int		RESULT_NET_NOTAVAILABLE			= -4;
+	public static final int		RESULT_ERROR					= -5;
+	public static final int		RESULT_LOCALFILE_ERROR			= -7;
+	public static final int		RESULT_USERAUTH_ERROR			= -9;
+	public static final int		RESULT_UPDATE_USERAUTH_ERROR	= -11;
+	public static final int		RESULT_SESSION_EXPIRED			= -13;
+	public static final int		RESULT_VER_LOW					= -15;
+	public static final int		STATUS_WAIT = -17;
+	static String				URL_UPLOAD_PHOTO				= "https://cherry.united-us.com/handset.php";
+	static String				URL_VERIFY_USER					= "https://cherry.united-us.com/handset_login.php";
+
+	// public static String VerifyUser(String user, String password,
+	// Context context)
+	// {
+	// String TAG = "net_dbg@VerifyUser";
+	// Log.d(TAG, "entry");
+	// try
+	// {
+	// BasicHttpParams httpParams = new BasicHttpParams();
+	// HttpConnectionParams.setConnectionTimeout(httpParams,
+	// REQUEST_TIMEOUT);
+	// HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
+	// HttpClient client = new DefaultHttpClient(httpParams);
+	// HttpPost post = new HttpPost(URL_VERIFY_USER);
+	// MultipartEntity reqEntity = new MultipartEntity(
+	// HttpMultipartMode.BROWSER_COMPATIBLE);
+	// reqEntity.addPart("user", new StringBody(user));
+	// reqEntity.addPart("password", new StringBody(password));
+	//
+	// post.setEntity(reqEntity);
+	// HttpResponse response = client.execute(post);
+	// int statucode = response.getStatusLine().getStatusCode();
+	// if (statucode == HttpStatus.SC_OK)
+	// {
+	// HttpEntity resEntity = response.getEntity();
+	// if (resEntity != null)
+	// {
+	// Log.d(TAG,
+	// "Response: content len==>"
+	// + resEntity.getContentLength());
+	// InputStream is = resEntity.getContent();
+	// try
+	// {
+	//
+	// BufferedReader br = new BufferedReader(
+	// new InputStreamReader(is, "utf-8"), 8);
+	// StringBuilder sb = new StringBuilder();
+	// String line = null;
+	// while ((line = br.readLine()) != null)
+	// {
+	// sb.append(line + "\n");
+	// }
+	//
+	// Log.d(TAG, "Response: content begin");
+	// Log.d(TAG, sb.toString());
+	// Log.d(TAG, "Response: content end");
+	// return sb.toString();
+	// }
+	// catch (Exception e)
+	// {
+	// Log.e(TAG, e.toString());
+	// // TODO: handle exception
+	// }
+	// finally
+	// {
+	// is.close();
+	//
+	// }
+	//
+	// }
+	// else
+	// {
+	// /*
+	// * resEntity is null
+	// */
+	// Log.d(TAG, "RESPONSE ENTITY IS NULL");
+	// return null;
+	// }
+	//
+	// }
+	// else
+	// {
+	// /*
+	// * Http error; out put error code;
+	// */
+	// Log.d(TAG, "HTTP " + statucode);
+	//
+	// HttpEntity resEntity = response.getEntity();
+	// if (resEntity != null)
+	// {
+	//
+	// InputStream is = resEntity.getContent();
+	// try
+	// {
+	//
+	// BufferedReader br = new BufferedReader(
+	// new InputStreamReader(is, "utf-8"), 8);
+	// StringBuilder sb = new StringBuilder();
+	// String line = null;
+	// while ((line = br.readLine()) != null)
+	// {
+	// sb.append(line + "\n");
+	// }
+	//
+	// Log.d(TAG, "Response: content begin");
+	// Log.d(TAG, sb.toString());
+	// Log.d(TAG, "Response: content end");
+	// return null;
+	// }
+	// catch (Exception e)
+	// {
+	// Log.e(TAG, e.toString());
+	// // TODO: handle exception
+	// }
+	// finally
+	// {
+	// is.close();
+	//
+	// }
+	//
+	// }
+	// else
+	// {
+	// /*
+	// * resEntity is null
+	// */
+	// Log.e(TAG, "RESPONSE ENTITY IS NULL");
+	// return null;
+	// }
+	// return null;
+	// }
+	//
+	// }
+	// catch (ConnectTimeoutException e)
+	// {
+	// Log.d(TAG, "request time out");
+	//
+	// }
+	// catch (Exception e)
+	// {
+	// Log.d(TAG, e.toString());
+	// }
+	// return null;
+	// }
+	public static class SSLSocketFactoryEx extends SSLSocketFactory
+	{
 
-	public static int VerifyUser(String user, String password)
+		SSLContext	sslContext	= SSLContext.getInstance("TLS");
+
+		public SSLSocketFactoryEx(KeyStore truststore)
+				throws NoSuchAlgorithmException, KeyManagementException,
+				KeyStoreException, UnrecoverableKeyException
+		{
+			super(truststore);
+
+			TrustManager tm = new X509TrustManager()
+			{
+				public java.security.cert.X509Certificate[] getAcceptedIssuers()
+				{
+					return null;
+				}
+
+				@Override
+				public void checkClientTrusted(
+						java.security.cert.X509Certificate[] chain,
+						String authType)
+						throws java.security.cert.CertificateException
+				{
+				}
+
+				@Override
+				public void checkServerTrusted(
+						java.security.cert.X509Certificate[] chain,
+						String authType)
+						throws java.security.cert.CertificateException
+				{
+				}
+			};
+			sslContext.init(null, new TrustManager[] { tm }, null);
+		}
+
+		@Override
+		public Socket createSocket(Socket socket, String host, int port,
+				boolean autoClose) throws IOException, UnknownHostException
+		{
+			return sslContext.getSocketFactory().createSocket(socket, host,
+					port, autoClose);
+		}
+
+		@Override
+		public Socket createSocket() throws IOException
+		{
+			return sslContext.getSocketFactory().createSocket();
+		}
+	}
+
+	private static HttpClient getNewHttpClient()
+	{
+		try
+		{
+			KeyStore trustStore = KeyStore.getInstance(KeyStore
+					.getDefaultType());
+			trustStore.load(null, null);
+
+			SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
+			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
+
+			HttpParams params = new BasicHttpParams();
+			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
+			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
+			HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
+			HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
+			SchemeRegistry registry = new SchemeRegistry();
+			registry.register(new Scheme("http", PlainSocketFactory
+					.getSocketFactory(), 80));
+			registry.register(new Scheme("https", sf, 443));
+
+			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
+					params, registry);
+
+			return new DefaultHttpClient(ccm, params);
+		}
+		catch (Exception e)
+		{
+			return new DefaultHttpClient();
+		}
+	}
+
+	public static String getJson(String url, Bundle parms)
 	{
-		String TAG = "net_dbg@VerifyUser";
+		String TAG = "net_dbg@GetJson";
 		Log.d(TAG, "entry");
+
+		// parms.putString("sessionid",
+		// ApexTrackingApplication.get_sessionid());
+
+		// if (true)
+		// return fakegetJson(url);
 		try
 		{
-			BasicHttpParams httpParams = new BasicHttpParams();
-			HttpConnectionParams.setConnectionTimeout(httpParams,
-					REQUEST_TIMEOUT);
-			HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
-			HttpClient client = new DefaultHttpClient(httpParams);
-			HttpPost post = new HttpPost(URL_VERIFY_USER);
+			// BasicHttpParams httpParams = new BasicHttpParams();
+			// HttpConnectionParams.setConnectionTimeout(httpParams,
+			// REQUEST_TIMEOUT);
+			// HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
+			HttpClient client = getNewHttpClient();// new
+													// DefaultHttpClient(httpParams);
+			HttpPost post = new HttpPost(url);
 			MultipartEntity reqEntity = new MultipartEntity(
 					HttpMultipartMode.BROWSER_COMPATIBLE);
-			reqEntity.addPart("user", new StringBody(user));
-			reqEntity.addPart("password", new StringBody(password));
+
+			Set<String> keys = parms.keySet();
+			Log.d(TAG, "================parms============");
+			for (String key : keys)
+			{
+				if (key.contains("_file"))
+				{
+					;
+				}
+				else
+					reqEntity.addPart(key, new StringBody(parms.get(key)
+							.toString()));
+				Log.d(TAG, "key=" + key + "    val="
+						+ parms.get(key).toString());
+			}
+			Log.d(TAG, "================parms============");
 
 			post.setEntity(reqEntity);
 			HttpResponse response = client.execute(post);
@@ -242,39 +377,18 @@ public class Network
 						Log.d(TAG, sb.toString());
 						Log.d(TAG, "Response: content end");
 
-						if (sb.length()<=0)
-						{
-							
-							return RESULT_NET_ERROR;
-						}
-						JSONObject obj = new JSONObject(sb.toString());
-						if (obj.length() > 0)
+						if (sb.length() <= 0)
 						{
-							// JSONObject obj = array.getJSONObject(0);
-							try
-							{
-								int verifyresult = Integer.parseInt(obj
-										.getString("result"));
-								if (verifyresult == Network.AP_USER_AUTH)
-								{
-									return RESULT_TRUE;
-								}
-								else
-								{
-									return RESULT_FALSE;
-								}
-							}
-							catch (Exception e)
-							{
-								Log.e(TAG, e.toString());
-								return RESULT_ERROR;
-							}
+
+							return null;
 						}
+						return sb.toString();
+
 					}
 					catch (Exception e)
 					{
 						Log.e(TAG, e.toString());
-						return RESULT_ERROR;
+						return null;
 						// TODO: handle exception
 					}
 					finally
@@ -290,7 +404,7 @@ public class Network
 					 * resEntity is null
 					 */
 					Log.d(TAG, "RESPONSE ENTITY IS NULL");
-					return RESULT_NET_ERROR;
+					return null;
 				}
 
 			}
@@ -321,12 +435,12 @@ public class Network
 						Log.d(TAG, "Response: content begin");
 						Log.d(TAG, sb.toString());
 						Log.d(TAG, "Response: content end");
-						return RESULT_ERROR;
+						return null;
 					}
 					catch (Exception e)
 					{
 						Log.e(TAG, e.toString());
-						return RESULT_ERROR;
+						return null;
 						// TODO: handle exception
 					}
 					finally
@@ -342,7 +456,7 @@ public class Network
 					 * resEntity is null
 					 */
 					Log.e(TAG, "RESPONSE ENTITY IS NULL");
-					return RESULT_NET_ERROR;
+					return null;
 				}
 			}
 
@@ -350,19 +464,274 @@ public class Network
 		catch (ConnectTimeoutException e)
 		{
 			Log.d(TAG, "request time out");
-			return RESULT_NET_ERROR;
+			return null;
 
 		}
 		catch (Exception e)
 		{
 			Log.d(TAG, e.toString());
-			return RESULT_ERROR;
+			return null;
 		}
-		return RESULT_ERROR;
+
 	}
 
-	public static int UploadFile( String path, String user,
-			String password, String pid)
+	public static boolean NetworkIsAvailable()// Context context)
+	{
+		String TAG = "net_dbg@CheckNetwork";
+		
+		ConnectivityManager connManager = (ConnectivityManager) RedAntApplication
+				.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
+		// .getSystemService(Context.CONNECTIVITY_SERVICE);
+
+		NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
+		if (networkInfo == null)
+		{
+			Log.d(TAG, "can not get Active NetworkInfo!"); 
+			// dbgUtil.Log(Log.DEBUG, "Current Network info",
+			// "can not get Active NetworkInfo!");
+			return false;
+		}
+		NetworkInfo.State netState = networkInfo.getState();
+		if (netState != NetworkInfo.State.CONNECTED)
+		{
+			Log.d(TAG, "not Connected!State=" + netState);
+			// dbgUtil.Log(Log.DEBUG, "Current Network info",
+			// "not Connected!State=" + netState);
+			return false;
+		}
+
+		boolean bavailable = networkInfo.isAvailable();
+		String strtype = networkInfo.getTypeName();
+
+		Log.d(TAG, " type = " + strtype + " abailable = " + bavailable
+				+ " state " + netState);
+
+		return bavailable;
+	}
+
+	public static int VerifyUser(String user, String password)
+	{
+		String TAG = "net_dbg@get_Auth";
+		Log.d(TAG, "u:" + user + ";p:" + password);
+		if (!Network.NetworkIsAvailable())
+		{
+			Log.d(TAG, "network not available!");
+			return Network.RESULT_NET_NOTAVAILABLE; // network not available
+		}
+		Bundle parms = new Bundle();
+		parms.putString("user", user);
+		parms.putString("password", password);
+//		parms.putString("action", "handset_login");
+//		int ver = ApexTrackingApplication
+//				.get_instance()
+//				.getSharedPreferences(name + "_Apex_auth", Context.MODE_PRIVATE)
+//				.getInt("AuthInfoVer", 0);
+//		parms.putString("auth_ver", ver + "");
+		String jstr = getJson(Network.URL_VERIFY_USER, parms);
+		/*
+		 * error occur while get authorization info from server. include can not
+		 * reach server , wrong parms ,server get wrong , etc.
+		 */
+		if (jstr == null || jstr.length() <= 0)
+		{
+			Log.d(TAG, "json is wrong");
+			return Network.RESULT_NET_ERROR;
+		}
+		JSONObject jsobj;
+		try
+		{
+			jsobj = new JSONObject(jstr);
+			if (jsobj.length() > 0)
+			{
+				int iresult = jsobj.getInt("result");
+				if (iresult == Network.AP_USER_AUTH)
+				{
+					return RESULT_TRUE;
+				}
+				
+				else
+				{
+					
+				return RESULT_FALSE;
+				}
+			}
+			return RESULT_NET_ERROR;
+		}
+		catch (JSONException e)
+		{
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+			return RESULT_NET_ERROR;
+		}
+		
+		
+	//	return parse_authinfo(jstr, name, password);
+		// if(true)
+		// return RESULT_TRUE;
+		// String TAG = "net_dbg@VerifyUser";
+		// Log.d(TAG, "entry");
+		// try
+		// {
+		// BasicHttpParams httpParams = new BasicHttpParams();
+		// HttpConnectionParams.setConnectionTimeout(httpParams,
+		// REQUEST_TIMEOUT);
+		// HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
+		// HttpClient client = new DefaultHttpClient(httpParams);
+		// HttpPost post = new HttpPost(URL_VERIFY_USER);
+		// MultipartEntity reqEntity = new MultipartEntity(
+		// HttpMultipartMode.BROWSER_COMPATIBLE);
+		// reqEntity.addPart("user", new StringBody(user));
+		// reqEntity.addPart("password", new StringBody(password));
+		//
+		// post.setEntity(reqEntity);
+		// HttpResponse response = client.execute(post);
+		// int statucode = response.getStatusLine().getStatusCode();
+		// if (statucode == HttpStatus.SC_OK)
+		// {
+		// HttpEntity resEntity = response.getEntity();
+		// if (resEntity != null)
+		// {
+		// Log.d(TAG,
+		// "Response: content len==>"
+		// + resEntity.getContentLength());
+		// InputStream is = resEntity.getContent();
+		// try
+		// {
+		//  
+		// BufferedReader br = new BufferedReader(
+		// new InputStreamReader(is, "utf-8"), 8);
+		// StringBuilder sb = new StringBuilder();
+		// String line = null;
+		// while ((line = br.readLine()) != null)
+		// {
+		// sb.append(line + "\n");
+		// }
+		//
+		// Log.d(TAG, "Response: content begin");
+		// Log.d(TAG, sb.toString());
+		// Log.d(TAG, "Response: content end");
+		//
+		// if (sb.length()<=0)
+		// {
+		//
+		// return RESULT_NET_ERROR;
+		// }
+		// JSONObject obj = new JSONObject(sb.toString());
+		// if (obj.length() > 0)
+		// {
+		// // JSONObject obj = array.getJSONObject(0);
+		// try
+		// {
+		// int verifyresult = Integer.parseInt(obj
+		// .getString("result"));
+		// if (verifyresult == Network.AP_USER_AUTH)
+		// {
+		// return RESULT_TRUE;
+		// }
+		// else
+		// {
+		// return RESULT_FALSE;
+		// }
+		// }
+		// catch (Exception e)
+		// {
+		// Log.e(TAG, e.toString());
+		// return RESULT_ERROR;
+		// }
+		// }
+		// }
+		// catch (Exception e)
+		// {
+		// Log.e(TAG, e.toString());
+		// return RESULT_ERROR;
+		// // TODO: handle exception
+		// }
+		// finally
+		// {
+		// is.close();
+		//
+		// }
+		//
+		// }
+		// else
+		// {
+		// /*
+		// * resEntity is null
+		// */
+		// Log.d(TAG, "RESPONSE ENTITY IS NULL");
+		// return RESULT_NET_ERROR;
+		// }
+		//
+		// }
+		// else
+		// {
+		// /*
+		// * Http error; out put error code;
+		// */
+		// Log.d(TAG, "HTTP " + statucode);
+		//
+		// HttpEntity resEntity = response.getEntity();
+		// if (resEntity != null)
+		// {
+		//
+		// InputStream is = resEntity.getContent();
+		// try
+		// {
+		//
+		// BufferedReader br = new BufferedReader(
+		// new InputStreamReader(is, "utf-8"), 8);
+		// StringBuilder sb = new StringBuilder();
+		// String line = null;
+		// while ((line = br.readLine()) != null)
+		// {
+		// sb.append(line + "\n");
+		// }
+		//
+		// Log.d(TAG, "Response: content begin");
+		// Log.d(TAG, sb.toString());
+		// Log.d(TAG, "Response: content end");
+		// return RESULT_ERROR;
+		// }
+		// catch (Exception e)
+		// {
+		// Log.e(TAG, e.toString());
+		// return RESULT_ERROR;
+		// // TODO: handle exception
+		// }
+		// finally
+		// {
+		// is.close();
+		//
+		// }
+		//
+		// }
+		// else
+		// {
+		// /*
+		// * resEntity is null
+		// */
+		// Log.e(TAG, "RESPONSE ENTITY IS NULL");
+		// return RESULT_NET_ERROR;
+		// }
+		// }
+		//
+		// }
+		// catch (ConnectTimeoutException e)
+		// {
+		// Log.d(TAG, "request time out");
+		// return RESULT_NET_ERROR;
+		//
+		// }
+		// catch (Exception e)
+		// {
+		// Log.d(TAG, e.toString());
+		// return RESULT_ERROR;
+		// }
+		// return RESULT_ERROR;
+	}
+
+	public static int UploadFile(String path, String user, String password,
+			String pid)
 	{
 		String TAG = "net_dbg@UploadFile";
 		Log.d(TAG, "entry");
@@ -372,13 +741,13 @@ public class Network
 
 		if (file.exists() == false)
 			return RESULT_LOCALFILE_ERROR;
-		String md5= MD5.md5sum(path);
-		Log.d(TAG, "MD5:"+md5);
-		if(md5==null)
+		String md5 = MD5.md5sum(path);
+		Log.d(TAG, "MD5:" + md5);
+		if (md5 == null)
 		{
 			Log.d(TAG, "md5 sum failed");
 			return RESULT_LOCALFILE_ERROR;
-			
+
 		}
 		try
 		{
@@ -394,7 +763,7 @@ public class Network
 			reqEntity.addPart("password", new StringBody(password));
 			reqEntity.addPart("pid", new StringBody(pid));
 			reqEntity.addPart("md5", new StringBody(md5));
-			
+
 			FileBody bin = new FileBody(file);
 			reqEntity.addPart("imagefile", bin);
 			post.setEntity(reqEntity);
@@ -425,9 +794,9 @@ public class Network
 						Log.d(TAG, sb.toString());
 						Log.d(TAG, "Response: content end");
 
-						if (sb.length()<=0)
+						if (sb.length() <= 0)
 						{
-							
+
 							return RESULT_NET_ERROR;
 						}
 						JSONObject obj = new JSONObject(sb.toString());
@@ -442,9 +811,9 @@ public class Network
 								{
 									return RESULT_TRUE;
 								}
-								else if(uploadresult == Network.AP_USER_NOT_AUTH)
+								else if (uploadresult == Network.AP_USER_NOT_AUTH)
 								{
-									Log.d(TAG,"RESULT_ERR_USERAUTH");
+									Log.d(TAG, "RESULT_ERR_USERAUTH");
 									return RESULT_USERAUTH_ERROR;
 								}
 								else
@@ -545,42 +914,42 @@ public class Network
 		{
 			Log.d(TAG, e.toString());
 			return RESULT_ERROR;
-		}		
-		
+		}
+
 		return RESULT_FALSE;
 
-//		try
-//		{
-//			HttpClient client = new DefaultHttpClient();
-//			HttpPost post = new HttpPost(url);
-//			MultipartEntity reqEntity = new MultipartEntity(
-//					HttpMultipartMode.BROWSER_COMPATIBLE);
-//			reqEntity.addPart("user", new StringBody(user));
-//			reqEntity.addPart("password", new StringBody(password));
-//			reqEntity.addPart("pid", new StringBody(pid));
-//			FileBody bin = new FileBody(file);
-//			reqEntity.addPart("imagefile", bin);
-//			post.setEntity(reqEntity);
-//			HttpResponse response = client.execute(post);
-//			HttpEntity resEntity = response.getEntity();
-//			if (resEntity != null)
-//			{
-//
-//				String result = EntityUtils.toString(resEntity);
-//				Log.d(TAG, "Response:" + result);
-//				return Integer.parseInt(result);
-//				// if(Boolean.parseBoolean(result)==true)
-//				// return true;
-//				// else
-//				// return false;
-//			}
-//
-//		}
-//		catch (Exception e)
-//		{
-//			e.printStackTrace();
-//		}
-//		return 0;
+		// try
+		// {
+		// HttpClient client = new DefaultHttpClient();
+		// HttpPost post = new HttpPost(url);
+		// MultipartEntity reqEntity = new MultipartEntity(
+		// HttpMultipartMode.BROWSER_COMPATIBLE);
+		// reqEntity.addPart("user", new StringBody(user));
+		// reqEntity.addPart("password", new StringBody(password));
+		// reqEntity.addPart("pid", new StringBody(pid));
+		// FileBody bin = new FileBody(file);
+		// reqEntity.addPart("imagefile", bin);
+		// post.setEntity(reqEntity);
+		// HttpResponse response = client.execute(post);
+		// HttpEntity resEntity = response.getEntity();
+		// if (resEntity != null)
+		// {
+		//
+		// String result = EntityUtils.toString(resEntity);
+		// Log.d(TAG, "Response:" + result);
+		// return Integer.parseInt(result);
+		// // if(Boolean.parseBoolean(result)==true)
+		// // return true;
+		// // else
+		// // return false;
+		// }
+		//
+		// }
+		// catch (Exception e)
+		// {
+		// e.printStackTrace();
+		// }
+		// return 0;
 	}
 
 	public static boolean NetworkIsAvailable(Context context)

+ 40 - 1
RedAnt Photo/src/com/usai/util/dbUtil.java

@@ -1,5 +1,10 @@
 package com.usai.util;
 
+import java.util.ArrayList;
+import java.util.List;
+
+import com.usai.redant.photo.RedAntApplication;
+
 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
@@ -354,7 +359,7 @@ public class dbUtil
 			boolean writable)
 	{
 
-		SqlOpenHelper dbHelper = new SqlOpenHelper(context, "test1.db",
+		SqlOpenHelper dbHelper = new SqlOpenHelper(context, "redantpop.db",
 				factory, 1);
 		dbHelper.addInitSQL("create table users (" + "_id INTEGER PRIMARY KEY,"
 				+ "name varchar(20)," + "pass varchar(20))");
@@ -366,6 +371,10 @@ public class dbUtil
 		dbHelper.addInitSQL("create table pics (" + "_id INTEGER PRIMARY KEY,"
 				+ "picker varchar(20)," + "err_code INTEGER ,"
 				+ "pid varchar(20)," + "local_path varchar(256))");
+		
+//		dbHelper.addInitSQL("create table pids (" + "_id INTEGER PRIMARY KEY,"
+//				+ "picker varchar(20)," + "err_code INTEGER ,"
+//				+ "pid varchar(20))");
 
 		SQLiteDatabase db = dbHelper.OpenDB(writable);
 		return db;
@@ -435,7 +444,37 @@ public class dbUtil
 	// }
 	// return ret;
 	// }
+	public static List<String> get_userlist()
+	{
+		List<String> ret = new ArrayList<String>();
+		SQLiteDatabase db = OpenDB(RedAntApplication.getInstance()
+				.getApplicationContext(), null, false);
+		Cursor cursor = db.query(
+				"users",
+				new String[] { "name" },
+				null, null, null,
+				null, "name desc", null);
+
+		while (cursor.moveToNext())
+		{
+			String user="";
+			try
+			{
+				user = Crypto.decrypt("apexu", cursor.getString(0));
+			}
+			catch (Exception e)
+			{
+				// TODO Auto-generated catch block
+				e.printStackTrace();
+			}
+			ret.add(user);
+
+		}
 
+		CloseCursor(cursor);
+		CloseDB(db);
+		return ret;
+	}
 	public static boolean isTableEmpty(SQLiteDatabase db, String table)
 	{
 		boolean ret = true;

+ 15 - 10
RedAnt Photo/src/com/usai/util/dbgUtil.java

@@ -6,10 +6,10 @@ import android.util.Log;
 
 public class dbgUtil
 {
-	static boolean ENABLE_DEBUG = true;
-	static boolean ENABLE_SQL_DEBUG = true;
-	final int DEBUG_LEVEL_NONE = 8;
-	static int DEBUG_LEVEL = Log.VERBOSE;
+//	static boolean ENABLE_DEBUG = true;
+//	static boolean ENABLE_SQL_DEBUG = true;
+//	final int DEBUG_LEVEL_NONE = 8;
+//	static int DEBUG_LEVEL = Log.VERBOSE;
 
 	// private static boolean m_dbgFlag = true;
 	/*
@@ -23,12 +23,17 @@ public class dbgUtil
 	 * Boolean.parseBoolean(context.getString(R.string.flag_debug)); return
 	 * this; }
 	 */
+	public static void Logd(String tag,String msg)
+	{
+		String pos = getTracePos();
+		Log.d(tag,msg+pos);
+	}
 //	public static void Log(int type, String tag, String msg)
 //	{
-//		if (ENABLE_DEBUG == false)
-//			return;
-//		if (type < DEBUG_LEVEL)
-//			return;
+////		if (ENABLE_DEBUG == false)
+////			return;
+////		if (type < DEBUG_LEVEL)
+////			return;
 //		String pos= getTracePos();
 //		switch (type)
 //		{
@@ -72,8 +77,8 @@ public class dbgUtil
 																	 * TracePos
 																	 */)
 	{
-		if (ENABLE_SQL_DEBUG == false)
-			return;
+//		if (ENABLE_SQL_DEBUG == false)
+//			return;
 
 		// ----------------------debug cursor-----------------------------------
 		Log.d("sql_dbg@dbgCursorInfo", getTracePos() + "Cursor size:	" + cursor.getCount()