summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Android.mk2
-rw-r--r--CleanSpec.mk14
-rw-r--r--api/current.xml1161
-rw-r--r--core/java/android/animation/AnimatableListenerAdapter.java56
-rwxr-xr-xcore/java/android/animation/Animator.java96
-rw-r--r--core/java/android/animation/Keyframe.java19
-rw-r--r--core/java/android/animation/KeyframeSet.java2
-rw-r--r--core/java/android/animation/PropertyAnimator.java113
-rw-r--r--core/java/android/animation/Sequencer.java2
-rw-r--r--core/java/android/app/Activity.java53
-rw-r--r--core/java/android/app/ContextImpl.java16
-rw-r--r--core/java/android/app/ContextualMode.java155
-rw-r--r--core/java/android/app/Dialog.java16
-rw-r--r--core/java/android/app/Service.java10
-rw-r--r--core/java/android/content/ContentProvider.java178
-rw-r--r--core/java/android/content/Context.java34
-rw-r--r--core/java/android/database/sqlite/SQLiteDatabase.java59
-rw-r--r--core/java/android/database/sqlite/SQLiteOpenHelper.java39
-rw-r--r--core/java/android/database/sqlite/SQLiteStatement.java26
-rw-r--r--core/java/android/net/DownloadManager.java2
-rw-r--r--core/java/android/net/NetworkInfo.java126
-rw-r--r--core/java/android/os/Binder.java12
-rw-r--r--core/java/android/os/IPowerManager.aidl1
-rw-r--r--core/java/android/os/StrictMode.java2
-rwxr-xr-xcore/java/android/speech/tts/TextToSpeech.java3
-rw-r--r--core/java/android/view/ActionMode.java151
-rw-r--r--core/java/android/view/MenuInflater.java4
-rw-r--r--core/java/android/view/View.java15
-rw-r--r--core/java/android/view/ViewGroup.java10
-rw-r--r--core/java/android/view/ViewParent.java14
-rw-r--r--core/java/android/view/ViewRoot.java4
-rw-r--r--core/java/android/view/Window.java20
-rw-r--r--core/java/com/android/internal/app/ActionBarImpl.java40
-rw-r--r--core/java/com/android/internal/view/StandaloneActionMode.java123
-rw-r--r--core/java/com/android/internal/widget/ActionBarContextView.java8
-rw-r--r--core/jni/android_database_SQLiteDatabase.cpp76
-rw-r--r--core/jni/android_database_SQLiteStatement.cpp30
-rw-r--r--core/jni/android_net_wifi_Wifi.cpp6
-rw-r--r--core/jni/android_util_Binder.cpp14
-rw-r--r--core/res/res/layout-xlarge/screen_action_bar.xml (renamed from core/res/res/layout/screen_xlarge_action_bar.xml)6
-rw-r--r--core/res/res/layout/screen.xml7
-rw-r--r--core/res/res/layout/screen_custom_title.xml7
-rw-r--r--core/res/res/layout/screen_progress.xml7
-rw-r--r--core/res/res/layout/screen_title.xml6
-rw-r--r--core/res/res/layout/screen_title_icons.xml6
-rwxr-xr-xcore/res/res/values/attrs.xml16
-rw-r--r--core/res/res/values/public.xml5
-rw-r--r--core/res/res/values/themes.xml4
-rw-r--r--core/tests/coretests/src/android/database/DatabaseGeneralTest.java61
-rw-r--r--docs/html/guide/guide_toc.cs3
-rw-r--r--docs/html/guide/publishing/licensing.jd2373
-rw-r--r--docs/html/guide/publishing/preparing.jd31
-rw-r--r--docs/html/guide/publishing/publishing.jd25
-rw-r--r--docs/html/images/licensing_add_library.pngbin0 -> 70285 bytes
-rw-r--r--docs/html/images/licensing_arch.pngbin0 -> 41227 bytes
-rw-r--r--docs/html/images/licensing_device_signin.pngbin0 -> 75152 bytes
-rw-r--r--docs/html/images/licensing_flow.pngbin0 -> 47151 bytes
-rw-r--r--docs/html/images/licensing_gapis_8.pngbin0 -> 84597 bytes
-rw-r--r--docs/html/images/licensing_package.pngbin0 -> 78821 bytes
-rw-r--r--docs/html/images/licensing_public_key.pngbin0 -> 95876 bytes
-rw-r--r--docs/html/images/licensing_test_response.pngbin0 -> 120461 bytes
-rw-r--r--docs/html/resources/faq/commontasks.jd2
-rw-r--r--include/binder/Parcel.h12
-rw-r--r--include/media/AudioEffect.h18
-rw-r--r--include/media/EffectApi.h6
-rw-r--r--include/media/EffectBassBoostApi.h3
-rw-r--r--include/media/EffectEnvironmentalReverbApi.h12
-rw-r--r--include/media/EffectEqualizerApi.h15
-rw-r--r--include/media/EffectPresetReverbApi.h4
-rw-r--r--include/media/EffectVirtualizerApi.h3
-rw-r--r--include/media/EffectVisualizerApi.h3
-rw-r--r--include/media/IEffect.h6
-rw-r--r--include/media/IEffectClient.h6
-rw-r--r--libs/binder/Parcel.cpp10
-rw-r--r--libs/hwui/Android.mk1
-rw-r--r--libs/hwui/FontRenderer.cpp66
-rw-r--r--libs/hwui/FontRenderer.h11
-rw-r--r--libs/hwui/OpenGLRenderer.cpp59
-rw-r--r--libs/hwui/OpenGLRenderer.h6
-rw-r--r--libs/hwui/Program.cpp11
-rw-r--r--libs/hwui/Program.h28
-rw-r--r--libs/hwui/ProgramCache.cpp332
-rw-r--r--libs/hwui/ProgramCache.h155
-rw-r--r--libs/hwui/Vertex.h8
-rw-r--r--libs/hwui/shaders/drawColor.vert11
-rw-r--r--libs/hwui/shaders/drawLinearGradient.vert2
-rw-r--r--libs/rs/rsContext.cpp7
-rw-r--r--location/java/android/location/Country.aidl19
-rwxr-xr-xlocation/java/android/location/Country.java161
-rw-r--r--location/java/android/location/CountryDetector.java152
-rw-r--r--location/java/android/location/CountryListener.java30
-rw-r--r--location/java/android/location/ICountryDetector.aidl44
-rw-r--r--location/java/android/location/ICountryListener.aidl26
-rw-r--r--location/tests/locationtests/src/android/location/CountryTester.java33
-rw-r--r--media/java/android/media/BassBoost.java84
-rw-r--r--media/java/android/media/EnvironmentalReverb.java174
-rw-r--r--media/java/android/media/Equalizer.java136
-rw-r--r--media/java/android/media/MtpClient.java7
-rw-r--r--media/java/android/media/PresetReverb.java87
-rw-r--r--media/java/android/media/Virtualizer.java82
-rw-r--r--media/jni/android_media_MtpClient.cpp63
-rw-r--r--media/jni/audioeffect/android_media_AudioEffect.cpp9
-rw-r--r--media/libeffects/factory/EffectsFactory.c7
-rw-r--r--media/libeffects/lvm/wrapper/Android.mk71
-rw-r--r--media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp36
-rw-r--r--media/libeffects/lvm/wrapper/Bundle/EffectBundle.h47
-rw-r--r--media/libeffects/testlibs/EffectEqualizer.cpp4
-rw-r--r--media/libeffects/testlibs/EffectReverb.c16
-rw-r--r--media/libeffects/testlibs/EffectReverb.h19
-rw-r--r--media/libeffects/visualizer/EffectVisualizer.cpp4
-rw-r--r--media/libmedia/AudioEffect.cpp20
-rw-r--r--media/libmedia/IEffect.cpp14
-rw-r--r--media/libmedia/IEffectClient.cpp12
-rw-r--r--media/libmedia/Visualizer.cpp2
-rw-r--r--media/mtp/MtpClient.cpp40
-rw-r--r--media/mtp/MtpCursor.cpp30
-rw-r--r--media/mtp/MtpCursor.h2
-rw-r--r--media/mtp/MtpDataPacket.cpp44
-rw-r--r--media/mtp/MtpDataPacket.h5
-rw-r--r--media/mtp/MtpDebug.h2
-rw-r--r--media/mtp/MtpDevice.cpp207
-rw-r--r--media/mtp/MtpDevice.h15
-rw-r--r--media/mtp/MtpDeviceInfo.cpp4
-rw-r--r--media/mtp/MtpProperty.cpp6
-rw-r--r--media/tests/CameraBrowser/Android.mk2
-rw-r--r--media/tests/CameraBrowser/AndroidManifest.xml2
-rw-r--r--media/tests/CameraBrowser/res/menu/object_menu.xml2
-rw-r--r--media/tests/CameraBrowser/res/values/strings.xml3
-rw-r--r--media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectBrowser.java45
-rw-r--r--media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectViewer.java141
-rw-r--r--media/tests/mtp/Android.mk61
-rw-r--r--media/tests/mtp/MtpFile.cpp187
-rw-r--r--media/tests/mtp/MtpFile.h57
-rw-r--r--media/tests/mtp/mtp.cpp370
-rw-r--r--policy/src/com/android/internal/policy/impl/PhoneWindow.java92
-rw-r--r--services/audioflinger/AudioFlinger.cpp105
-rw-r--r--services/audioflinger/AudioFlinger.h18
-rw-r--r--services/java/com/android/server/ConnectivityService.java5
-rw-r--r--services/java/com/android/server/CountryDetectorService.java204
-rw-r--r--services/java/com/android/server/DropBoxManagerService.java2
-rw-r--r--services/java/com/android/server/PowerManagerService.java110
-rw-r--r--services/java/com/android/server/SystemServer.java11
-rw-r--r--services/java/com/android/server/WifiService.java1404
-rw-r--r--services/java/com/android/server/WifiWatchdogService.java27
-rw-r--r--services/java/com/android/server/am/ActivityManagerService.java35
-rw-r--r--services/java/com/android/server/connectivity/Tethering.java11
-rwxr-xr-xservices/java/com/android/server/location/ComprehensiveCountryDetector.java359
-rw-r--r--services/java/com/android/server/location/CountryDetectorBase.java72
-rwxr-xr-xservices/java/com/android/server/location/LocationBasedCountryDetector.java235
-rw-r--r--services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java109
-rw-r--r--services/tests/servicestests/src/com/android/server/location/ComprehensiveCountryDetectorTest.java299
-rwxr-xr-xservices/tests/servicestests/src/com/android/server/location/LocationBasedCountryDetectorTest.java324
-rw-r--r--telephony/java/com/android/internal/telephony/CallManager.java348
-rw-r--r--telephony/java/com/android/internal/telephony/cdma/CdmaCall.java3
-rw-r--r--telephony/java/com/android/internal/telephony/gsm/GsmCall.java3
-rw-r--r--telephony/tests/telephonytests/Android.mk2
-rw-r--r--telephony/tests/telephonytests/AndroidManifest.xml7
-rw-r--r--telephony/tests/telephonytests/src/com/android/frameworks/telephonytests/TelephonyMockRilTestRunner.java93
-rw-r--r--telephony/tests/telephonytests/src/com/android/internal/telephony/mockril/MockRilTest.java176
-rw-r--r--test-runner/src/android/test/LoaderTestCase.java101
-rw-r--r--tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java8
-rw-r--r--tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java17
-rw-r--r--tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java48
-rw-r--r--tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java7
-rw-r--r--tests/DumpRenderTree2/AndroidManifest.xml10
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/AbstractResult.java19
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTest.java183
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsExecutor.java (renamed from tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsExecuter.java)39
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsRunnerThread.java304
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/ManagerService.java95
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/Summarizer.java13
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/TestsListActivity.java (renamed from tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsRunner.java)61
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/TestsListPreloaderThread.java121
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/TextResult.java10
-rw-r--r--tests/DumpRenderTree2/src/com/android/dumprendertree2/ui/DirListActivity.java10
-rw-r--r--wifi/java/android/net/wifi/WifiManager.java10
-rw-r--r--wifi/java/android/net/wifi/WifiMonitor.java8
-rw-r--r--wifi/java/android/net/wifi/WifiNative.java2
-rw-r--r--wifi/java/android/net/wifi/WifiStateTracker.java5094
179 files changed, 13827 insertions, 5037 deletions
diff --git a/Android.mk b/Android.mk
index 3afbfd7..696b117 100644
--- a/Android.mk
+++ b/Android.mk
@@ -163,6 +163,8 @@ LOCAL_SRC_FILES += \
core/java/com/android/internal/view/IInputMethodManager.aidl \
core/java/com/android/internal/view/IInputMethodSession.aidl \
core/java/com/android/internal/widget/IRemoteViewsFactory.aidl \
+ location/java/android/location/ICountryDetector.aidl \
+ location/java/android/location/ICountryListener.aidl \
location/java/android/location/IGeocodeProvider.aidl \
location/java/android/location/IGpsStatusListener.aidl \
location/java/android/location/IGpsStatusProvider.aidl \
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 26d8a1b..1efe77c 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -54,7 +54,19 @@ $(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/FrameworkTest_in
$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/android.policy*)
$(call add-clean-step, rm -rf $(TARGET_OUT_JAVA_LIBRARIES)/android.policy.jar)
$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/JAVA_LIBRARIES/framework_intermediates)
-
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/obj/lib/libequalizer.so)
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/obj/lib/libequalizertest.so)
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/obj/lib/libreverb.so)
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/obj/lib/libreverbtest.so)
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/symbols/system/lib/libequalizer.so)
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/symbols/system/lib/libequalizertest.so)
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/symbols/system/lib/libreverb.so)
+$(call add-clean-step, rm -f $(PRODUCT_OUT)/symbols/system/lib/libreverbtest.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libequalizer_intermediates)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libequalizertest_intermediates)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libreverb_intermediates)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/SHARED_LIBRARIES/libreverbtest_intermediates)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/soundfx/)
# ************************************************
# NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
diff --git a/api/current.xml b/api/current.xml
index 96ca9e9..850073e 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -2088,55 +2088,55 @@
visibility="public"
>
</field>
-<field name="actionBarCloseContextDrawable"
+<field name="actionButtonPadding"
type="int"
transient="false"
volatile="false"
- value="16843550"
+ value="16843547"
static="true"
final="true"
deprecated="not deprecated"
visibility="public"
>
</field>
-<field name="actionBarContextBackground"
+<field name="actionButtonStyle"
type="int"
transient="false"
volatile="false"
- value="16843549"
+ value="16843545"
static="true"
final="true"
deprecated="not deprecated"
visibility="public"
>
</field>
-<field name="actionButtonPadding"
+<field name="actionDropDownStyle"
type="int"
transient="false"
volatile="false"
- value="16843547"
+ value="16843544"
static="true"
final="true"
deprecated="not deprecated"
visibility="public"
>
</field>
-<field name="actionButtonStyle"
+<field name="actionModeBackground"
type="int"
transient="false"
volatile="false"
- value="16843545"
+ value="16843549"
static="true"
final="true"
deprecated="not deprecated"
visibility="public"
>
</field>
-<field name="actionDropDownStyle"
+<field name="actionModeCloseDrawable"
type="int"
transient="false"
volatile="false"
- value="16843544"
+ value="16843550"
static="true"
final="true"
deprecated="not deprecated"
@@ -10525,6 +10525,17 @@
visibility="public"
>
</field>
+<field name="windowActionModeOverlay"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16843551"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="windowAnimationStyle"
type="int"
transient="false"
@@ -21241,6 +21252,19 @@
visibility="protected"
>
</method>
+<method name="onStartActionMode"
+ return="android.view.ActionMode"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.view.ActionMode.Callback">
+</parameter>
+</method>
<method name="onStop"
return="void"
abstract="false"
@@ -21836,6 +21860,19 @@
<parameter name="args" type="android.os.Bundle">
</parameter>
</method>
+<method name="startActionMode"
+ return="android.view.ActionMode"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.view.ActionMode.Callback">
+</parameter>
+</method>
<method name="startActivityForResult"
return="void"
abstract="false"
@@ -22117,6 +22154,17 @@
visibility="protected"
>
</field>
+<field name="POP_BACK_STACK_INCLUSIVE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="RESULT_CANCELED"
type="int"
transient="false"
@@ -24546,194 +24594,6 @@
>
</method>
</class>
-<class name="ContextualMode"
- extends="java.lang.Object"
- abstract="true"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<constructor name="ContextualMode"
- type="android.app.ContextualMode"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</constructor>
-<method name="finish"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="getCustomView"
- return="android.view.View"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="getMenu"
- return="android.view.Menu"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="getSubtitle"
- return="java.lang.CharSequence"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="getTitle"
- return="java.lang.CharSequence"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="invalidate"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-<method name="setCustomView"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="view" type="android.view.View">
-</parameter>
-</method>
-<method name="setSubtitle"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="subtitle" type="java.lang.CharSequence">
-</parameter>
-</method>
-<method name="setTitle"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="title" type="java.lang.CharSequence">
-</parameter>
-</method>
-</class>
-<interface name="ContextualMode.Callback"
- abstract="true"
- static="true"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<method name="onContextualItemClicked"
- return="boolean"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="mode" type="android.app.ContextualMode">
-</parameter>
-<parameter name="item" type="android.view.MenuItem">
-</parameter>
-</method>
-<method name="onCreateContextualMode"
- return="boolean"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="mode" type="android.app.ContextualMode">
-</parameter>
-<parameter name="menu" type="android.view.Menu">
-</parameter>
-</method>
-<method name="onDestroyContextualMode"
- return="void"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="mode" type="android.app.ContextualMode">
-</parameter>
-</method>
-<method name="onPrepareContextualMode"
- return="boolean"
- abstract="true"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="mode" type="android.app.ContextualMode">
-</parameter>
-<parameter name="menu" type="android.view.Menu">
-</parameter>
-</method>
-</interface>
<class name="DatePickerDialog"
extends="android.app.AlertDialog"
abstract="false"
@@ -25466,6 +25326,19 @@
visibility="protected"
>
</method>
+<method name="onStartActionMode"
+ return="android.view.ActionMode"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.view.ActionMode.Callback">
+</parameter>
+</method>
<method name="onStop"
return="void"
abstract="false"
@@ -40357,17 +40230,6 @@
visibility="public"
>
</method>
-<method name="finishContextualMode"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
<method name="getApplicationContext"
return="android.content.Context"
abstract="true"
@@ -41082,19 +40944,6 @@
<parameter name="intent" type="android.content.Intent">
</parameter>
</method>
-<method name="startContextualMode"
- return="android.app.ContextualMode"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="callback" type="android.app.ContextualMode.Callback">
-</parameter>
-</method>
<method name="startInstrumentation"
return="boolean"
abstract="true"
@@ -41341,6 +41190,17 @@
visibility="public"
>
</field>
+<field name="DOWNLOAD_SERVICE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;download&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="DROPBOX_SERVICE"
type="java.lang.String"
transient="false"
@@ -63391,6 +63251,17 @@
visibility="public"
>
</method>
+<method name="executeUpdateDelete"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="simpleQueryForLong"
return="long"
abstract="false"
@@ -96902,6 +96773,567 @@
>
</field>
</class>
+<class name="DownloadManager"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="enqueue"
+ return="long"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="request" type="android.net.DownloadManager.Request">
+</parameter>
+</method>
+<method name="openDownloadedFile"
+ return="android.os.ParcelFileDescriptor"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="id" type="long">
+</parameter>
+<exception name="FileNotFoundException" type="java.io.FileNotFoundException">
+</exception>
+</method>
+<method name="query"
+ return="android.database.Cursor"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="query" type="android.net.DownloadManager.Query">
+</parameter>
+</method>
+<method name="remove"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="id" type="long">
+</parameter>
+</method>
+<field name="ACTION_DOWNLOAD_COMPLETE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.intent.action.DOWNLOAD_COMPLETE&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ACTION_NOTIFICATION_CLICKED"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_BYTES_DOWNLOADED_SO_FAR"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;bytes_so_far&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_DESCRIPTION"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;description&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_ERROR_CODE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;error_code&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_ID"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;id&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_LAST_MODIFIED_TIMESTAMP"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;last_modified_timestamp&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_LOCAL_URI"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;local_uri&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_MEDIA_TYPE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;media_type&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_STATUS"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;status&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_TITLE"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;title&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_TOTAL_SIZE_BYTES"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;total_size&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="COLUMN_URI"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;uri&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_DEVICE_NOT_FOUND"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1007"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_FILE_ERROR"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1001"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_HTTP_DATA_ERROR"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1004"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_INSUFFICIENT_SPACE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1006"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_TOO_MANY_REDIRECTS"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1005"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_UNHANDLED_HTTP_CODE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1002"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="ERROR_UNKNOWN"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1000"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="EXTRA_DOWNLOAD_ID"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value="&quot;extra_download_id&quot;"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="STATUS_FAILED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="STATUS_PAUSED"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="4"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="STATUS_PENDING"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="STATUS_RUNNING"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="STATUS_SUCCESSFUL"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="8"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
+<class name="DownloadManager.Query"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="DownloadManager.Query"
+ type="android.net.DownloadManager.Query"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="setFilterById"
+ return="android.net.DownloadManager.Query"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="id" type="long">
+</parameter>
+</method>
+<method name="setFilterByStatus"
+ return="android.net.DownloadManager.Query"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+</class>
+<class name="DownloadManager.Request"
+ extends="java.lang.Object"
+ abstract="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="DownloadManager.Request"
+ type="android.net.DownloadManager.Request"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</constructor>
+<method name="setAllowedNetworkTypes"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<method name="setAllowedOverRoaming"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="allowed" type="boolean">
+</parameter>
+</method>
+<method name="setDescription"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="description" type="java.lang.String">
+</parameter>
+</method>
+<method name="setDestinationUri"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="uri" type="android.net.Uri">
+</parameter>
+</method>
+<method name="setMediaType"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="mediaType" type="java.lang.String">
+</parameter>
+</method>
+<method name="setRequestHeader"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="header" type="java.lang.String">
+</parameter>
+<parameter name="value" type="java.lang.String">
+</parameter>
+</method>
+<method name="setShowNotification"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="flags" type="int">
+</parameter>
+</method>
+<method name="setTitle"
+ return="android.net.DownloadManager.Request"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="title" type="java.lang.String">
+</parameter>
+</method>
+<field name="NETWORK_MOBILE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="NETWORK_WIFI"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="NETWORK_WIMAX"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="4"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="NOTIFICATION_WHEN_RUNNING"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+</class>
<class name="LocalServerSocket"
extends="java.lang.Object"
abstract="false"
@@ -154334,6 +154766,36 @@
>
</method>
</class>
+<class name="LoaderTestCase"
+ extends="android.test.AndroidTestCase"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="LoaderTestCase"
+ type="android.test.LoaderTestCase"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="getLoaderResultSynchronously"
+ return="T"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="loader" type="android.content.Loader&lt;T&gt;">
+</parameter>
+</method>
+</class>
<class name="MoreAsserts"
extends="java.lang.Object"
abstract="false"
@@ -176373,6 +176835,194 @@
>
</field>
</class>
+<class name="ActionMode"
+ extends="java.lang.Object"
+ abstract="true"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="ActionMode"
+ type="android.view.ActionMode"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="finish"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getCustomView"
+ return="android.view.View"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getMenu"
+ return="android.view.Menu"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getSubtitle"
+ return="java.lang.CharSequence"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="getTitle"
+ return="java.lang.CharSequence"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="invalidate"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+<method name="setCustomView"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="view" type="android.view.View">
+</parameter>
+</method>
+<method name="setSubtitle"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="subtitle" type="java.lang.CharSequence">
+</parameter>
+</method>
+<method name="setTitle"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="title" type="java.lang.CharSequence">
+</parameter>
+</method>
+</class>
+<interface name="ActionMode.Callback"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="onActionItemClicked"
+ return="boolean"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="mode" type="android.view.ActionMode">
+</parameter>
+<parameter name="item" type="android.view.MenuItem">
+</parameter>
+</method>
+<method name="onCreateActionMode"
+ return="boolean"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="mode" type="android.view.ActionMode">
+</parameter>
+<parameter name="menu" type="android.view.Menu">
+</parameter>
+</method>
+<method name="onDestroyActionMode"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="mode" type="android.view.ActionMode">
+</parameter>
+</method>
+<method name="onPrepareActionMode"
+ return="boolean"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="mode" type="android.view.ActionMode">
+</parameter>
+<parameter name="menu" type="android.view.Menu">
+</parameter>
+</method>
+</interface>
<interface name="ContextMenu"
abstract="true"
static="false"
@@ -188800,6 +189450,19 @@
visibility="public"
>
</method>
+<method name="startActionMode"
+ return="android.view.ActionMode"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.view.ActionMode.Callback">
+</parameter>
+</method>
<method name="startAnimation"
return="void"
abstract="false"
@@ -191577,6 +192240,21 @@
<parameter name="originalView" type="android.view.View">
</parameter>
</method>
+<method name="startActionModeForChild"
+ return="android.view.ActionMode"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="originalView" type="android.view.View">
+</parameter>
+<parameter name="callback" type="android.view.ActionMode.Callback">
+</parameter>
+</method>
<method name="startLayoutAnimation"
return="void"
abstract="false"
@@ -192267,6 +192945,21 @@
<parameter name="originalView" type="android.view.View">
</parameter>
</method>
+<method name="startActionModeForChild"
+ return="android.view.ActionMode"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="originalView" type="android.view.View">
+</parameter>
+<parameter name="callback" type="android.view.ActionMode.Callback">
+</parameter>
+</method>
</interface>
<class name="ViewStub"
extends="android.view.View"
@@ -193649,6 +194342,17 @@
type="int"
transient="false"
volatile="false"
+ value="8"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_ACTION_MODE_OVERLAY"
+ type="int"
+ transient="false"
+ volatile="false"
value="9"
static="true"
final="true"
@@ -194037,6 +194741,19 @@
visibility="public"
>
</method>
+<method name="onStartActionMode"
+ return="android.view.ActionMode"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="callback" type="android.view.ActionMode.Callback">
+</parameter>
+</method>
<method name="onWindowAttributesChanged"
return="void"
abstract="true"
diff --git a/core/java/android/animation/AnimatableListenerAdapter.java b/core/java/android/animation/AnimatableListenerAdapter.java
new file mode 100644
index 0000000..25a842b
--- /dev/null
+++ b/core/java/android/animation/AnimatableListenerAdapter.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package android.animation;
+
+import android.animation.Animatable.AnimatableListener;
+
+/**
+ * This adapter class provides empty implementations of the methods from {@link AnimatableListener}.
+ * Any custom listener that cares only about a subset of the methods of this listener can
+ * simply subclass this adapter class instead of implementing the interface directly.
+ */
+public abstract class AnimatableListenerAdapter implements AnimatableListener {
+
+ /**
+ * @{inheritdoc}
+ */
+ @Override
+ public void onAnimationCancel(Animatable animation) {
+ }
+
+ /**
+ * @{inheritdoc}
+ */
+ @Override
+ public void onAnimationEnd(Animatable animation) {
+ }
+
+ /**
+ * @{inheritdoc}
+ */
+ @Override
+ public void onAnimationRepeat(Animatable animation) {
+ }
+
+ /**
+ * @{inheritdoc}
+ */
+ @Override
+ public void onAnimationStart(Animatable animation) {
+ }
+
+}
diff --git a/core/java/android/animation/Animator.java b/core/java/android/animation/Animator.java
index 24c3c88..bf3596b 100755
--- a/core/java/android/animation/Animator.java
+++ b/core/java/android/animation/Animator.java
@@ -241,25 +241,6 @@ public class Animator extends Animatable {
}
/**
- * This function is called immediately before processing the first animation
- * frame of an animation. If there is a nonzero <code>startDelay</code>, the
- * function is called after that delay ends.
- * It takes care of the final initialization steps for the
- * animation.
- *
- * <p>Overrides of this method should call the superclass method to ensure
- * that internal mechanisms for the animation are set up correctly.</p>
- */
- void initAnimation() {
- if (mEvaluator == null) {
- mEvaluator = (mValueType == int.class) ? sIntEvaluator :
- (mValueType == double.class) ? sDoubleEvaluator : sFloatEvaluator;
- }
- mPlayingBackwards = false;
- mCurrentIteration = 0;
- }
-
- /**
* A constructor that takes <code>float</code> values.
*
* @param duration The length of the animation, in milliseconds.
@@ -305,6 +286,61 @@ public class Animator extends Animatable {
}
/**
+ * Internal constructor that takes a single <code>float</code> value.
+ * This constructor is called by PropertyAnimator.
+ *
+ * @param duration The length of the animation, in milliseconds.
+ * @param valueFrom The initial value of the property when the animation begins.
+ * @param valueTo The value to which the property will animate.
+ */
+ Animator(long duration, float valueTo) {
+ this(duration, null, valueTo, float.class);
+ }
+
+ /**
+ * Internal constructor that takes a single <code>int</code> value.
+ * This constructor is called by PropertyAnimator.
+ *
+ * @param duration The length of the animation, in milliseconds.
+ * @param valueFrom The initial value of the property when the animation begins.
+ * @param valueTo The value to which the property will animate.
+ */
+ Animator(long duration, int valueTo) {
+ this(duration, null, valueTo, int.class);
+ }
+
+ /**
+ * Internal constructor that takes a single <code>double</code> value.
+ * This constructor is called by PropertyAnimator.
+ *
+ * @param duration The length of the animation, in milliseconds.
+ * @param valueFrom The initial value of the property when the animation begins.
+ * @param valueTo The value to which the property will animate.
+ */
+ Animator(long duration, double valueTo) {
+ this(duration, null, valueTo, double.class);
+ }
+
+ /**
+ * This function is called immediately before processing the first animation
+ * frame of an animation. If there is a nonzero <code>startDelay</code>, the
+ * function is called after that delay ends.
+ * It takes care of the final initialization steps for the
+ * animation.
+ *
+ * <p>Overrides of this method should call the superclass method to ensure
+ * that internal mechanisms for the animation are set up correctly.</p>
+ */
+ void initAnimation() {
+ if (mEvaluator == null) {
+ mEvaluator = (mValueType == int.class) ? sIntEvaluator :
+ (mValueType == double.class) ? sDoubleEvaluator : sFloatEvaluator;
+ }
+ mPlayingBackwards = false;
+ mCurrentIteration = 0;
+ }
+
+ /**
* This custom, static handler handles the timing pulse that is shared by
* all active animations. This approach ensures that the setting of animation
* values will happen on the UI thread and that all animations will share
@@ -454,6 +490,9 @@ public class Animator extends Animatable {
* @return Object The starting value for the animation.
*/
public Object getValueFrom() {
+ if (mKeyframeSet != null) {
+ return mKeyframeSet.mKeyframes.get(0).getValue();
+ }
return mValueFrom;
}
@@ -461,7 +500,12 @@ public class Animator extends Animatable {
* Sets the value that this animation will start from.
*/
public void setValueFrom(Object valueFrom) {
- mValueFrom = valueFrom;
+ if (mKeyframeSet != null) {
+ Keyframe kf = mKeyframeSet.mKeyframes.get(0);
+ kf.setValue(valueFrom);
+ } else {
+ mValueFrom = valueFrom;
+ }
}
/**
@@ -470,6 +514,10 @@ public class Animator extends Animatable {
* @return Object The ending value for the animation.
*/
public Object getValueTo() {
+ if (mKeyframeSet != null) {
+ int numKeyframes = mKeyframeSet.mKeyframes.size();
+ return mKeyframeSet.mKeyframes.get(numKeyframes - 1).getValue();
+ }
return mValueTo;
}
@@ -479,7 +527,13 @@ public class Animator extends Animatable {
* @return Object The ending value for the animation.
*/
public void setValueTo(Object valueTo) {
- mValueTo = valueTo;
+ if (mKeyframeSet != null) {
+ int numKeyframes = mKeyframeSet.mKeyframes.size();
+ Keyframe kf = mKeyframeSet.mKeyframes.get(numKeyframes - 1);
+ kf.setValue(valueTo);
+ } else {
+ mValueTo = valueTo;
+ }
}
/**
diff --git a/core/java/android/animation/Keyframe.java b/core/java/android/animation/Keyframe.java
index b98994a..0f39635 100644
--- a/core/java/android/animation/Keyframe.java
+++ b/core/java/android/animation/Keyframe.java
@@ -142,6 +142,15 @@ public class Keyframe {
}
/**
+ * Sets the value for this Keyframe.
+ *
+ * @param The value for this Keyframe.
+ */
+ public void setValue(Object value) {
+ mValue = value;
+ }
+
+ /**
* Gets the time for this keyframe, as a fraction of the overall animation duration.
*
* @return The time associated with this keyframe, as a fraction of the overall animation
@@ -152,6 +161,16 @@ public class Keyframe {
}
/**
+ * Sets the time for this keyframe, as a fraction of the overall animation duration.
+ *
+ * @param The time associated with this keyframe, as a fraction of the overall animation
+ * duration. This should be a value between 0 and 1.
+ */
+ public void setFraction(float fraction) {
+ mFraction = fraction;
+ }
+
+ /**
* Gets the optional interpolator for this Keyframe. A value of <code>null</code> indicates
* that there is no interpolation, which is the same as linear interpolation.
*
diff --git a/core/java/android/animation/KeyframeSet.java b/core/java/android/animation/KeyframeSet.java
index 59e9708..d144b9c 100644
--- a/core/java/android/animation/KeyframeSet.java
+++ b/core/java/android/animation/KeyframeSet.java
@@ -29,7 +29,7 @@ class KeyframeSet {
private int mNumKeyframes;
- private ArrayList<Keyframe> mKeyframes;
+ ArrayList<Keyframe> mKeyframes;
public KeyframeSet(Keyframe... keyframes) {
mKeyframes = new ArrayList<Keyframe>();
diff --git a/core/java/android/animation/PropertyAnimator.java b/core/java/android/animation/PropertyAnimator.java
index 937dd58..4b4b021 100644
--- a/core/java/android/animation/PropertyAnimator.java
+++ b/core/java/android/animation/PropertyAnimator.java
@@ -160,20 +160,23 @@ public final class PropertyAnimator extends Animator {
* @param prefix "set" or "get", depending on whether we need a setter or getter.
* @return Method the method associated with mPropertyName.
*/
- private Method getPropertyFunction(String prefix) {
+ private Method getPropertyFunction(String prefix, Class valueType) {
// TODO: faster implementation...
Method returnVal = null;
String firstLetter = mPropertyName.substring(0, 1);
String theRest = mPropertyName.substring(1);
firstLetter = firstLetter.toUpperCase();
String setterName = prefix + firstLetter + theRest;
- Class args[] = new Class[1];
- args[0] = mValueType;
+ Class args[] = null;
+ if (valueType != null) {
+ args = new Class[1];
+ args[0] = valueType;
+ }
try {
returnVal = mTarget.getClass().getMethod(setterName, args);
} catch (NoSuchMethodException e) {
Log.e("PropertyAnimator",
- "Couldn't find setter for property " + mPropertyName + ": " + e);
+ "Couldn't find setter/getter for property " + mPropertyName + ": " + e);
}
return returnVal;
}
@@ -203,6 +206,31 @@ public final class PropertyAnimator extends Animator {
}
/**
+ * A constructor that takes a single <code>float</code> value, which is the value that the
+ * target object will animate to. When this constructor
+ * is called, the system expects to find a setter for <code>propertyName</code> on
+ * the target object that takes a value of the same type as the <code>Object</code>s. The
+ * system also expects to find a similar getter function with which to derive the starting
+ * value for the animation.
+ *
+ * @param duration The length of the animation, in milliseconds.
+ * @param target The object whose property is to be animated. This object should
+ * have a public function on it called <code>setName()</code>, where <code>name</code> is
+ * the name of the property passed in as the <code>propertyName</code> parameter.
+ * @param propertyName The name of the property on the <code>target</code> object
+ * that will be animated. Given this name, the constructor will search for a
+ * setter on the target object with the name <code>setPropertyName</code>. For example,
+ * if the constructor is called with <code>propertyName = "foo"</code>, then the
+ * target object should have a setter function with the name <code>setFoo()</code>.
+ * @param valueTo The value to which the property will animate.
+ */
+ public PropertyAnimator(int duration, Object target, String propertyName, float valueTo) {
+ super(duration, valueTo);
+ mTarget = target;
+ mPropertyName = propertyName;
+ }
+
+ /**
* A constructor that takes <code>int</code> values. When this constructor
* is called, the system expects to find a setter for <code>propertyName</code> on
* the target object that takes a <code>int</code> value.
@@ -227,6 +255,31 @@ public final class PropertyAnimator extends Animator {
}
/**
+ * A constructor that takes a single <code>int</code> value, which is the value that the
+ * target object will animate to. When this constructor
+ * is called, the system expects to find a setter for <code>propertyName</code> on
+ * the target object that takes a value of the same type as the <code>Object</code>s. The
+ * system also expects to find a similar getter function with which to derive the starting
+ * value for the animation.
+ *
+ * @param duration The length of the animation, in milliseconds.
+ * @param target The object whose property is to be animated. This object should
+ * have a public function on it called <code>setName()</code>, where <code>name</code> is
+ * the name of the property passed in as the <code>propertyName</code> parameter.
+ * @param propertyName The name of the property on the <code>target</code> object
+ * that will be animated. Given this name, the constructor will search for a
+ * setter on the target object with the name <code>setPropertyName</code>. For example,
+ * if the constructor is called with <code>propertyName = "foo"</code>, then the
+ * target object should have a setter function with the name <code>setFoo()</code>.
+ * @param valueTo The value to which the property will animate.
+ */
+ public PropertyAnimator(int duration, Object target, String propertyName, int valueTo) {
+ super(duration, valueTo);
+ mTarget = target;
+ mPropertyName = propertyName;
+ }
+
+ /**
* A constructor that takes <code>double</code> values. When this constructor
* is called, the system expects to find a setter for <code>propertyName</code> on
* the target object that takes a <code>double</code> value.
@@ -251,6 +304,31 @@ public final class PropertyAnimator extends Animator {
}
/**
+ * A constructor that takes a single <code>double</code> value, which is the value that the
+ * target object will animate to. When this constructor
+ * is called, the system expects to find a setter for <code>propertyName</code> on
+ * the target object that takes a value of the same type as the <code>Object</code>s. The
+ * system also expects to find a similar getter function with which to derive the starting
+ * value for the animation.
+ *
+ * @param duration The length of the animation, in milliseconds.
+ * @param target The object whose property is to be animated. This object should
+ * have a public function on it called <code>setName()</code>, where <code>name</code> is
+ * the name of the property passed in as the <code>propertyName</code> parameter.
+ * @param propertyName The name of the property on the <code>target</code> object
+ * that will be animated. Given this name, the constructor will search for a
+ * setter on the target object with the name <code>setPropertyName</code>. For example,
+ * if the constructor is called with <code>propertyName = "foo"</code>, then the
+ * target object should have a setter function with the name <code>setFoo()</code>.
+ * @param valueTo The value to which the property will animate.
+ */
+ public PropertyAnimator(int duration, Object target, String propertyName, double valueTo) {
+ super(duration, valueTo);
+ mTarget = target;
+ mPropertyName = propertyName;
+ }
+
+ /**
* A constructor that takes <code>Object</code> values. When this constructor
* is called, the system expects to find a setter for <code>propertyName</code> on
* the target object that takes a value of the same type as the <code>Object</code>s.
@@ -275,6 +353,29 @@ public final class PropertyAnimator extends Animator {
}
/**
+ * A constructor that takes a single <code>Object</code> value, which is the value that the
+ * target object will animate to. When this constructor
+ * is called, the system expects to find a setter for <code>propertyName</code> on
+ * the target object that takes a value of the same type as the <code>Object</code>s. The
+ * system also expects to find a similar getter function with which to derive the starting
+ * value for the animation.
+ *
+ * @param duration The length of the animation, in milliseconds.
+ * @param target The object whose property is to be animated. This object should
+ * have a public function on it called <code>setName()</code>, where <code>name</code> is
+ * the name of the property passed in as the <code>propertyName</code> parameter.
+ * @param propertyName The name of the property on the <code>target</code> object
+ * that will be animated. Given this name, the constructor will search for a
+ * setter on the target object with the name <code>setPropertyName</code>. For example,
+ * if the constructor is called with <code>propertyName = "foo"</code>, then the
+ * target object should have a setter function with the name <code>setFoo()</code>.
+ * @param valueTo The value to which the property will animate.
+ */
+ public PropertyAnimator(int duration, Object target, String propertyName, Object valueTo) {
+ this(duration, target, propertyName, null, valueTo);
+ }
+
+ /**
* A constructor that takes <code>Keyframe</code>s. When this constructor
* is called, the system expects to find a setter for <code>propertyName</code> on
* the target object that takes a value of the same type as that returned from
@@ -329,7 +430,7 @@ public final class PropertyAnimator extends Animator {
return;
}
}
- mSetter = getPropertyFunction("set");
+ mSetter = getPropertyFunction("set", mValueType);
if (propertyMap == null) {
propertyMap = new HashMap<String, Method>();
sSetterPropertyMap.put(mTarget, propertyMap);
@@ -352,7 +453,7 @@ public final class PropertyAnimator extends Animator {
return;
}
}
- mGetter = getPropertyFunction("get");
+ mGetter = getPropertyFunction("get", null);
if (propertyMap == null) {
propertyMap = new HashMap<String, Method>();
sGetterPropertyMap.put(mTarget, propertyMap);
diff --git a/core/java/android/animation/Sequencer.java b/core/java/android/animation/Sequencer.java
index 74d81e9..41ca58c 100644
--- a/core/java/android/animation/Sequencer.java
+++ b/core/java/android/animation/Sequencer.java
@@ -692,7 +692,7 @@ public final class Sequencer extends Animatable {
*/
public void after(long delay) {
// setup dummy Animator just to run the clock
- Animator anim = new Animator(delay, 0, 1);
+ Animator anim = new Animator(delay, 0f, 1f);
Node node = new Node(anim);
mNodes.add(node);
Dependency dependency = new Dependency(node, Dependency.AFTER);
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 431f66d..9beaec0 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -16,8 +16,8 @@
package android.app;
-import java.util.ArrayList;
-import java.util.HashMap;
+import com.android.internal.app.ActionBarImpl;
+import com.android.internal.policy.PolicyManager;
import android.content.ComponentCallbacks;
import android.content.ComponentName;
@@ -52,7 +52,9 @@ import android.util.Config;
import android.util.EventLog;
import android.util.Log;
import android.util.SparseArray;
+import android.view.ActionMode;
import android.view.ContextMenu;
+import android.view.ContextMenu.ContextMenuInfo;
import android.view.ContextThemeWrapper;
import android.view.InflateException;
import android.view.KeyEvent;
@@ -62,21 +64,18 @@ import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
+import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
+import android.view.ViewGroup.LayoutParams;
import android.view.ViewManager;
import android.view.Window;
import android.view.WindowManager;
-import android.view.ContextMenu.ContextMenuInfo;
-import android.view.View.OnCreateContextMenuListener;
-import android.view.ViewGroup.LayoutParams;
import android.view.accessibility.AccessibilityEvent;
import android.widget.AdapterView;
import android.widget.FrameLayout;
-import android.widget.LinearLayout;
-import com.android.internal.app.ActionBarImpl;
-import com.android.internal.policy.PolicyManager;
-import com.android.internal.widget.ActionBarView;
+import java.util.ArrayList;
+import java.util.HashMap;
/**
* An activity is a single, focused thing that the user can do. Almost all
@@ -2060,7 +2059,7 @@ public class Activity extends ContextThemeWrapper
* removed. Otherwise, all entries up to but not including that entry
* will be removed
*/
- static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
+ public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
/**
* Pop the top state off the back stack. Returns true if there was one
@@ -4073,6 +4072,25 @@ public class Activity extends ContextThemeWrapper
}
}
+ /**
+ * Start a context mode.
+ *
+ * @param callback Callback that will manage lifecycle events for this context mode
+ * @return The ContextMode that was started, or null if it was canceled
+ *
+ * @see ActionMode
+ */
+ public ActionMode startActionMode(ActionMode.Callback callback) {
+ return mWindow.getDecorView().startActionMode(callback);
+ }
+
+ public ActionMode onStartActionMode(ActionMode.Callback callback) {
+ if (mActionBar != null) {
+ return mActionBar.startActionMode(callback);
+ }
+ return null;
+ }
+
// ------------------ Internal API ------------------
final void setParent(Activity parent) {
@@ -4286,19 +4304,4 @@ public class Activity extends ContextThemeWrapper
}
}
}
-
- @Override
- public ContextualMode startContextualMode(ContextualMode.Callback callback) {
- if (mActionBar == null) {
- return null;
- }
- return mActionBar.startContextualMode(callback);
- }
-
- @Override
- public void finishContextualMode() {
- if (mActionBar != null) {
- mActionBar.finishContextualMode();
- }
- }
}
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 8eded3d..10ebd60 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -62,6 +62,8 @@ import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.hardware.SensorManager;
+import android.location.CountryDetector;
+import android.location.ICountryDetector;
import android.location.ILocationManager;
import android.location.LocationManager;
import android.media.AudioManager;
@@ -168,6 +170,7 @@ class ContextImpl extends Context {
private static ThrottleManager sThrottleManager;
private static WifiManager sWifiManager;
private static LocationManager sLocationManager;
+ private static CountryDetector sCountryDetector;
private static final HashMap<File, SharedPreferencesImpl> sSharedPrefs =
new HashMap<File, SharedPreferencesImpl>();
@@ -954,6 +957,8 @@ class ContextImpl extends Context {
return AccessibilityManager.getInstance(this);
} else if (LOCATION_SERVICE.equals(name)) {
return getLocationManager();
+ } else if (COUNTRY_DETECTOR.equals(name)) {
+ return getCountryDetector();
} else if (SEARCH_SERVICE.equals(name)) {
return getSearchManager();
} else if (SENSOR_SERVICE.equals(name)) {
@@ -1120,6 +1125,17 @@ class ContextImpl extends Context {
return sLocationManager;
}
+ private CountryDetector getCountryDetector() {
+ synchronized (sSync) {
+ if (sCountryDetector == null) {
+ IBinder b = ServiceManager.getService(COUNTRY_DETECTOR);
+ ICountryDetector service = ICountryDetector.Stub.asInterface(b);
+ sCountryDetector = new CountryDetector(service);
+ }
+ }
+ return sCountryDetector;
+ }
+
private SearchManager getSearchManager() {
synchronized (mSync) {
if (mSearchManager == null) {
diff --git a/core/java/android/app/ContextualMode.java b/core/java/android/app/ContextualMode.java
deleted file mode 100644
index 5e4b5df..0000000
--- a/core/java/android/app/ContextualMode.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-package android.app;
-
-import android.content.Context;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-
-/**
- * Represents a contextual mode of the user interface. Contextual modes can be used for
- * modal interactions with content and replace parts of the normal UI until finished.
- * Examples of good contextual modes include selection modes, search, content editing, etc.
- */
-public abstract class ContextualMode {
- /**
- * Set the title of the contextual mode. This method will have no visible effect if
- * a custom view has been set.
- *
- * @param title Title string to set
- *
- * @see #setCustomView(View)
- */
- public abstract void setTitle(CharSequence title);
-
- /**
- * Set the subtitle of the contextual mode. This method will have no visible effect if
- * a custom view has been set.
- *
- * @param subtitle Subtitle string to set
- *
- * @see #setCustomView(View)
- */
- public abstract void setSubtitle(CharSequence subtitle);
-
- /**
- * Set a custom view for this contextual mode. The custom view will take the place of
- * the title and subtitle. Useful for things like search boxes.
- *
- * @param view Custom view to use in place of the title/subtitle.
- *
- * @see #setTitle(CharSequence)
- * @see #setSubtitle(CharSequence)
- */
- public abstract void setCustomView(View view);
-
- /**
- * Invalidate the contextual mode and refresh menu content. The contextual mode's
- * {@link ContextualMode.Callback} will have its
- * {@link Callback#onPrepareContextualMode(ContextualMode, Menu)} method called.
- * If it returns true the menu will be scanned for updated content and any relevant changes
- * will be reflected to the user.
- */
- public abstract void invalidate();
-
- /**
- * Finish and close this context mode. The context mode's {@link ContextualMode.Callback} will
- * have its {@link Callback#onDestroyContextualMode(ContextualMode)} method called.
- */
- public abstract void finish();
-
- /**
- * Returns the menu of actions that this contextual mode presents.
- * @return The contextual mode's menu.
- */
- public abstract Menu getMenu();
-
- /**
- * Returns the current title of this contextual mode.
- * @return Title text
- */
- public abstract CharSequence getTitle();
-
- /**
- * Returns the current subtitle of this contextual mode.
- * @return Subtitle text
- */
- public abstract CharSequence getSubtitle();
-
- /**
- * Returns the current custom view for this contextual mode.
- * @return The current custom view
- */
- public abstract View getCustomView();
-
- /**
- * Callback interface for contextual modes. Supplied to
- * {@link Context#startContextualMode(Callback)}, a Callback
- * configures and handles events raised by a user's interaction with a context mode.
- *
- * <p>A context mode's lifecycle is as follows:
- * <ul>
- * <li>{@link Callback#onCreateContextualMode(ContextualMode, Menu)} once on initial
- * creation</li>
- * <li>{@link Callback#onPrepareContextualMode(ContextualMode, Menu)} after creation
- * and any time the {@link ContextualMode} is invalidated</li>
- * <li>{@link Callback#onContextualItemClicked(ContextualMode, MenuItem)} any time a
- * contextual action button is clicked</li>
- * <li>{@link Callback#onDestroyContextualMode(ContextualMode)} when the context mode
- * is closed</li>
- * </ul>
- */
- public interface Callback {
- /**
- * Called when a contextual mode is first created. The menu supplied will be used to
- * generate action buttons for the contextual mode.
- *
- * @param mode ContextualMode being created
- * @param menu Menu used to populate contextual action buttons
- * @return true if the contextual mode should be created, false if entering this
- * mode should be aborted.
- */
- public boolean onCreateContextualMode(ContextualMode mode, Menu menu);
-
- /**
- * Called to refresh a contextual mode's action menu whenever it is invalidated.
- *
- * @param mode ContextualMode being prepared
- * @param menu Menu used to populate contextual action buttons
- * @return true if the menu or contextual mode was updated, false otherwise.
- */
- public boolean onPrepareContextualMode(ContextualMode mode, Menu menu);
-
- /**
- * Called to report a user click on a contextual action button.
- *
- * @param mode The current ContextualMode
- * @param item The item that was clicked
- * @return true if this callback handled the event, false if the standard MenuItem
- * invocation should continue.
- */
- public boolean onContextualItemClicked(ContextualMode mode, MenuItem item);
-
- /**
- * Called when a contextual mode is about to be exited and destroyed.
- *
- * @param mode The current ContextualMode being destroyed
- */
- public void onDestroyContextualMode(ContextualMode mode);
- }
-} \ No newline at end of file
diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java
index da8c9e5..a9420b4 100644
--- a/core/java/android/app/Dialog.java
+++ b/core/java/android/app/Dialog.java
@@ -18,16 +18,18 @@ package android.app;
import com.android.internal.policy.PolicyManager;
-import android.content.Context;
-import android.content.DialogInterface;
import android.content.ComponentName;
+import android.content.Context;
import android.content.ContextWrapper;
+import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
+import android.view.ContextMenu.ContextMenuInfo;
+import android.view.ActionMode;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
@@ -36,13 +38,12 @@ import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
+import android.view.View.OnCreateContextMenuListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
+import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
-import android.view.ContextMenu.ContextMenuInfo;
-import android.view.View.OnCreateContextMenuListener;
-import android.view.ViewGroup.LayoutParams;
import android.view.accessibility.AccessibilityEvent;
import java.lang.ref.WeakReference;
@@ -832,6 +833,11 @@ public class Dialog implements DialogInterface, Window.Callback,
}
}
+ public ActionMode onStartActionMode(ActionMode.Callback callback) {
+ // TODO Support context modes in dialogs
+ return null;
+ }
+
/**
* @return The activity associated with this dialog, or null if there is no assocaited activity.
*/
diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java
index 697a987..b7a750b 100644
--- a/core/java/android/app/Service.java
+++ b/core/java/android/app/Service.java
@@ -400,7 +400,15 @@ public abstract class Service extends ContextWrapper implements ComponentCallbac
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/ForegroundService.java
* start_compatibility}
- *
+ *
+ * <p class="caution">Note that the system calls this on your
+ * service's main thread. A service's main thread is the same
+ * thread where UI operations place for Activities running in the
+ * same process. You should always avoid stalling the main
+ * thread's event loop. When doing long-running operations,
+ * network calls, or heavy disk I/O, you should kick off a new
+ * thread, or use {@link android.os.AsyncTask}.</p>
+ *
* @param intent The Intent supplied to {@link android.content.Context#startService},
* as given. This may be null if the service is being restarted after
* its process has gone away, and it had previously returned anything
diff --git a/core/java/android/content/ContentProvider.java b/core/java/android/content/ContentProvider.java
index 5fb2aae..40108c3 100644
--- a/core/java/android/content/ContentProvider.java
+++ b/core/java/android/content/ContentProvider.java
@@ -57,6 +57,7 @@ import java.util.ArrayList;
*
* <p>The primary methods that need to be implemented are:
* <ul>
+ * <li>{@link #onCreate} which is called to initialize the provider</li>
* <li>{@link #query} which returns data to the caller</li>
* <li>{@link #insert} which inserts new data into the content provider</li>
* <li>{@link #update} which updates existing data in the content provider</li>
@@ -64,8 +65,15 @@ import java.util.ArrayList;
* <li>{@link #getType} which returns the MIME type of data in the content provider</li>
* </ul></p>
*
- * <p>This class takes care of cross process calls so subclasses don't have to worry about which
- * process a request is coming from.</p>
+ * <p class="caution">Data access methods (such as {@link #insert} and
+ * {@link #update}) may be called from many threads at once, and must be thread-safe.
+ * Other methods (such as {@link #onCreate}) are only called from the application
+ * main thread, and must avoid performing lengthy operations. See the method
+ * descriptions for their expected thread behavior.</p>
+ *
+ * <p>Requests to {@link ContentResolver} are automatically forwarded to the appropriate
+ * ContentProvider instance, so subclasses don't have to worry about the details of
+ * cross-process calls.</p>
*/
public abstract class ContentProvider implements ComponentCallbacks {
/*
@@ -81,6 +89,21 @@ public abstract class ContentProvider implements ComponentCallbacks {
private Transport mTransport = new Transport();
+ /**
+ * Construct a ContentProvider instance. Content providers must be
+ * <a href="{@docRoot}guide/topics/manifest/provider-element.html">declared
+ * in the manifest</a>, accessed with {@link ContentResolver}, and created
+ * automatically by the system, so applications usually do not create
+ * ContentProvider instances directly.
+ *
+ * <p>At construction time, the object is uninitialized, and most fields and
+ * methods are unavailable. Subclasses should initialize themselves in
+ * {@link #onCreate}, not the constructor.
+ *
+ * <p>Content providers are created on the application main thread at
+ * application launch time. The constructor must not perform lengthy
+ * operations, or application startup will be delayed.
+ */
public ContentProvider() {
}
@@ -328,8 +351,8 @@ public abstract class ContentProvider implements ComponentCallbacks {
/**
- * Retrieve the Context this provider is running in. Only available once
- * onCreate(Map icicle) has been called -- this will be null in the
+ * Retrieves the Context this provider is running in. Only available once
+ * {@link #onCreate} has been called -- this will return null in the
* constructor.
*/
public final Context getContext() {
@@ -403,23 +426,59 @@ public abstract class ContentProvider implements ComponentCallbacks {
}
/**
- * Called when the provider is being started.
+ * Implement this to initialize your content provider on startup.
+ * This method is called for all registered content providers on the
+ * application main thread at application launch time. It must not perform
+ * lengthy operations, or application startup will be delayed.
+ *
+ * <p>You should defer nontrivial initialization (such as opening,
+ * upgrading, and scanning databases) until the content provider is used
+ * (via {@link #query}, {@link #insert}, etc). Deferred initialization
+ * keeps application startup fast, avoids unnecessary work if the provider
+ * turns out not to be needed, and stops database errors (such as a full
+ * disk) from halting application launch.
+ *
+ * <p>For SQL databases, {@link android.database.sqlite.SQLiteOpenHelper}
+ * is a helpful utility class that makes it easy to manage databases,
+ * and will automatically defer opening until first use. If you do use
+ * SQLiteOpenHelper, make sure to avoid calling
+ * {@link android.database.sqlite.SQLiteOpenHelper#getReadableDatabase} or
+ * {@link android.database.sqlite.SQLiteOpenHelper#getWritableDatabase}
+ * from this method. (Instead, override
+ * {@link android.database.sqlite.SQLiteOpenHelper#onOpen} to initialize the
+ * database when it is first opened.)
*
* @return true if the provider was successfully loaded, false otherwise
*/
public abstract boolean onCreate();
+ /**
+ * {@inheritDoc}
+ * This method is always called on the application main thread, and must
+ * not perform lengthy operations.
+ *
+ * <p>The default content provider implementation does nothing.
+ * Override this method to take appropriate action.
+ * (Content providers do not usually care about things like screen
+ * orientation, but may want to know about locale changes.)
+ */
public void onConfigurationChanged(Configuration newConfig) {
}
-
+
+ /**
+ * {@inheritDoc}
+ * This method is always called on the application main thread, and must
+ * not perform lengthy operations.
+ *
+ * <p>The default content provider implementation does nothing.
+ * Subclasses may override this method to take appropriate action.
+ */
public void onLowMemory() {
}
/**
- * Receives a query request from a client in a local process, and
- * returns a Cursor. This is called internally by the {@link ContentResolver}.
- * This method can be called from multiple
- * threads, as described in
+ * Implement this to handle query requests from clients.
+ * This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
* Processes and Threads</a>.
* <p>
@@ -476,11 +535,11 @@ public abstract class ContentProvider implements ComponentCallbacks {
String selection, String[] selectionArgs, String sortOrder);
/**
- * Return the MIME type of the data at the given URI. This should start with
+ * Implement this to handle requests for the MIME type of the data at the
+ * given URI. The returned MIME type should start with
* <code>vnd.android.cursor.item</code> for a single record,
* or <code>vnd.android.cursor.dir/</code> for multiple items.
- * This method can be called from multiple
- * threads, as described in
+ * This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
* Processes and Threads</a>.
*
@@ -490,11 +549,10 @@ public abstract class ContentProvider implements ComponentCallbacks {
public abstract String getType(Uri uri);
/**
- * Implement this to insert a new row.
+ * Implement this to handle requests to insert a new row.
* As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
* after inserting.
- * This method can be called from multiple
- * threads, as described in
+ * This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
* Processes and Threads</a>.
* @param uri The content:// URI of the insertion request.
@@ -504,12 +562,12 @@ public abstract class ContentProvider implements ComponentCallbacks {
public abstract Uri insert(Uri uri, ContentValues values);
/**
- * Implement this to insert a set of new rows, or the default implementation will
- * iterate over the values and call {@link #insert} on each of them.
+ * Override this to handle requests to insert a set of new rows, or the
+ * default implementation will iterate over the values and call
+ * {@link #insert} on each of them.
* As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
* after inserting.
- * This method can be called from multiple
- * threads, as described in
+ * This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
* Processes and Threads</a>.
*
@@ -526,13 +584,12 @@ public abstract class ContentProvider implements ComponentCallbacks {
}
/**
- * A request to delete one or more rows. The selection clause is applied when performing
- * the deletion, allowing the operation to affect multiple rows in a
- * directory.
+ * Implement this to handle requests to delete one or more rows.
+ * The implementation should apply the selection clause when performing
+ * deletion, allowing the operation to affect multiple rows in a directory.
* As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyDelete()}
* after deleting.
- * This method can be called from multiple
- * threads, as described in
+ * This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
* Processes and Threads</a>.
*
@@ -549,13 +606,12 @@ public abstract class ContentProvider implements ComponentCallbacks {
public abstract int delete(Uri uri, String selection, String[] selectionArgs);
/**
- * Update a content URI. All rows matching the optionally provided selection
- * will have their columns listed as the keys in the values map with the
- * values of those keys.
+ * Implement this to update one or more rows.
+ * The implementation should update all rows matching the selection
+ * to set the columns according to the provided values map.
* As a courtesy, call {@link ContentResolver#notifyChange(android.net.Uri ,android.database.ContentObserver) notifyChange()}
* after updating.
- * This method can be called from multiple
- * threads, as described in
+ * This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
* Processes and Threads</a>.
*
@@ -570,18 +626,15 @@ public abstract class ContentProvider implements ComponentCallbacks {
String[] selectionArgs);
/**
- * Open a file blob associated with a content URI.
- * This method can be called from multiple
- * threads, as described in
+ * Override this to open a file blob associated with a content URI.
+ * The default implementation always throws {@link FileNotFoundException}.
+ * This method can be called from multiple threads, as described in
* <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
* Processes and Threads</a>.
- *
- * <p>Returns a
- * ParcelFileDescriptor, from which you can obtain a
- * {@link java.io.FileDescriptor} for use with
- * {@link java.io.FileInputStream}, {@link java.io.FileOutputStream}, etc.
- * This can be used to store large data (such as an image) associated with
- * a particular piece of content.
+ *
+ * <p>Returns a ParcelFileDescriptor, which is returned directly to the
+ * caller. This way large data (such as images and documents) can be
+ * returned without copying the content.
*
* <p>The returned ParcelFileDescriptor is owned by the caller, so it is
* their responsibility to close it when done. That is, the implementation
@@ -599,31 +652,35 @@ public abstract class ContentProvider implements ComponentCallbacks {
* no file associated with the given URI or the mode is invalid.
* @throws SecurityException Throws SecurityException if the caller does
* not have permission to access the file.
- *
+ *
* @see #openAssetFile(Uri, String)
* @see #openFileHelper(Uri, String)
- */
+ */
public ParcelFileDescriptor openFile(Uri uri, String mode)
throws FileNotFoundException {
throw new FileNotFoundException("No files supported by provider at "
+ uri);
}
-
+
/**
* This is like {@link #openFile}, but can be implemented by providers
* that need to be able to return sub-sections of files, often assets
- * inside of their .apk. Note that when implementing this your clients
- * must be able to deal with such files, either directly with
- * {@link ContentResolver#openAssetFileDescriptor
- * ContentResolver.openAssetFileDescriptor}, or by using the higher-level
+ * inside of their .apk.
+ * This method can be called from multiple threads, as described in
+ * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
+ * Processes and Threads</a>.
+ *
+ * <p>If you implement this, your clients must be able to deal with such
+ * files, either directly with
+ * {@link ContentResolver#openAssetFileDescriptor}, or by using the higher-level
* {@link ContentResolver#openInputStream ContentResolver.openInputStream}
* or {@link ContentResolver#openOutputStream ContentResolver.openOutputStream}
* methods.
- *
- * <p><em>Note: if you are implementing this to return a full file, you
+ *
+ * <p class="note">If you are implementing this to return a full file, you
* should create the AssetFileDescriptor with
* {@link AssetFileDescriptor#UNKNOWN_LENGTH} to be compatible with
- * applications that can not handle sub-sections of files.</em></p>
+ * applications that can not handle sub-sections of files.</p>
*
* @param uri The URI whose file is to be opened.
* @param mode Access mode for the file. May be "r" for read-only access,
@@ -735,17 +792,20 @@ public abstract class ContentProvider implements ComponentCallbacks {
}
/**
- * Applies each of the {@link ContentProviderOperation} objects and returns an array
- * of their results. Passes through OperationApplicationException, which may be thrown
- * by the call to {@link ContentProviderOperation#apply}.
- * If all the applications succeed then a {@link ContentProviderResult} array with the
- * same number of elements as the operations will be returned. It is implementation-specific
- * how many, if any, operations will have been successfully applied if a call to
- * apply results in a {@link OperationApplicationException}.
+ * Override this to perform a batch of operations, or the default
+ * implementation will {@link ContentProviderOperation#apply} each of the
+ * {@link ContentProviderOperation} objects. If the apply calls all succeed
+ * then a {@link ContentProviderResult} array with the same number of
+ * elements as the operations will be returned. If any of the apply calls
+ * fail, it is up to the implementation how many of the others take effect.
+ * This method can be called from multiple threads, as described in
+ * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals:
+ * Processes and Threads</a>.
+ *
* @param operations the operations to apply
* @return the results of the applications
- * @throws OperationApplicationException thrown if an application fails.
- * See {@link ContentProviderOperation#apply} for more information.
+ * @throws OperationApplicationException thrown if any operation fails.
+ * @see ContentProviderOperation#apply
*/
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index aceeed6..879103e 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -16,7 +16,6 @@
package android.content;
-import android.app.ContextualMode;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
@@ -1381,7 +1380,16 @@ public abstract class Context {
* @see android.location.LocationManager
*/
public static final String LOCATION_SERVICE = "location";
-
+
+ /**
+ * Use with {@link #getSystemService} to retrieve a
+ * {@link android.location.CountryDetector} for detecting the country that
+ * the user is in.
+ *
+ * @hide
+ */
+ public static final String COUNTRY_DETECTOR = "country_detector";
+
/**
* Use with {@link #getSystemService} to retrieve a {@link
* android.app.SearchManager} for handling searches.
@@ -1567,7 +1575,6 @@ public abstract class Context {
* {@link android.net.DownloadManager} for requesting HTTP downloads.
*
* @see #getSystemService
- * @hide (TODO) for now
*/
public static final String DOWNLOAD_SERVICE = "download";
@@ -1983,25 +1990,4 @@ public abstract class Context {
public boolean isRestricted() {
return false;
}
-
- /**
- * Start a contextual mode controlled by <code>callback</code>.
- * The {@link ContextualMode.Callback} will receive lifecycle events for the duration
- * of the contextual mode. There can only be one contextual mode active at a time.
- * Starting a new contextual mode while one is already active will finish the old
- * contextual mode.
- *
- * @param callback Callback handler that will manage this context mode.
- * @return The new contextual mode started by this call, or <code>null</code>
- * if the mode was not started.
- */
- public ContextualMode startContextualMode(ContextualMode.Callback callback) {
- return null;
- }
-
- /**
- * Finish the current contextual mode if present.
- */
- public void finishContextualMode() {
- }
}
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index cf4d07f..623821b 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -67,7 +67,7 @@ import java.util.regex.Pattern;
* is the Unicode Collation Algorithm and not tailored to the current locale.
*/
public class SQLiteDatabase extends SQLiteClosable {
- private static final String TAG = "Database";
+ private static final String TAG = "SQLiteDatabase";
private static final int EVENT_DB_OPERATION = 52000;
private static final int EVENT_DB_CORRUPT = 75004;
@@ -1641,18 +1641,7 @@ public class SQLiteDatabase extends SQLiteClosable {
}
// Run the program and then cleanup
- statement.execute();
-
- long insertedRowId = lastInsertRow();
- if (insertedRowId == -1) {
- Log.e(TAG, "Error inserting " + initialValues + " using " + sql);
- } else {
- if (Config.LOGD && Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "Inserting row " + insertedRowId + " from "
- + initialValues + " using " + sql);
- }
- }
- return insertedRowId;
+ return statement.executeInsert();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
@@ -1689,8 +1678,7 @@ public class SQLiteDatabase extends SQLiteClosable {
DatabaseUtils.bindObjectToProgram(statement, i + 1, whereArgs[i]);
}
}
- statement.execute();
- return lastChangeCount();
+ return statement.executeUpdateDelete();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
@@ -1782,12 +1770,7 @@ public class SQLiteDatabase extends SQLiteClosable {
}
// Run the program and then cleanup
- statement.execute();
- int numChangedRows = lastChangeCount();
- if (Config.LOGD && Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "Updated " + numChangedRows + " using " + values + " and " + sql);
- }
- return numChangedRows;
+ return statement.executeUpdateDelete();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
@@ -1834,13 +1817,18 @@ public class SQLiteDatabase extends SQLiteClosable {
long timeStart = SystemClock.uptimeMillis();
lock();
logTimeStat(mLastSqlStatement, timeStart, GET_LOCK_LOG_PREFIX);
+ SQLiteStatement stmt = null;
try {
closePendingStatements();
- native_execSQL(sql);
+ stmt = compileStatement(sql);
+ stmt.execute();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
} finally {
+ if (stmt != null) {
+ stmt.close();
+ }
unlock();
}
@@ -1914,7 +1902,7 @@ public class SQLiteDatabase extends SQLiteClosable {
DatabaseUtils.bindObjectToProgram(statement, i + 1, bindArgs[i]);
}
}
- statement.execute();
+ statement.executeUpdateDelete();
} catch (SQLiteDatabaseCorruptException e) {
onCorruption();
throw e;
@@ -2025,7 +2013,7 @@ public class SQLiteDatabase extends SQLiteClosable {
}
if (durationMillis >= sQueryLogTimeInMillis) {
samplePercent = 100;
- } else {;
+ } else {
samplePercent = (int) (100 * durationMillis / sQueryLogTimeInMillis) + 1;
if (mRandom.nextInt(100) >= samplePercent) return;
}
@@ -2628,15 +2616,6 @@ public class SQLiteDatabase extends SQLiteClosable {
private native void enableSqlProfiling(String path, short connectionNum);
/**
- * Native call to execute a raw SQL statement. {@link #lock} must be held
- * when calling this method.
- *
- * @param sql The raw SQL string
- * @throws SQLException
- */
- /* package */ native void native_execSQL(String sql) throws SQLException;
-
- /**
* Native call to set the locale. {@link #lock} must be held when calling
* this method.
* @throws SQLException
@@ -2644,20 +2623,6 @@ public class SQLiteDatabase extends SQLiteClosable {
/* package */ native void native_setLocale(String loc, int flags);
/**
- * Returns the row ID of the last row inserted into the database.
- *
- * @return the row ID of the last row inserted into the database.
- */
- /* package */ native long lastInsertRow();
-
- /**
- * Returns the number of changes made in the last statement executed.
- *
- * @return the number of changes made in the last statement executed.
- */
- /* package */ native int lastChangeCount();
-
- /**
* return the SQLITE_DBSTATUS_LOOKASIDE_USED documented here
* http://www.sqlite.org/c3ref/c_dbstatus_lookaside_used.html
* @return int value of SQLITE_DBSTATUS_LOOKASIDE_USED
diff --git a/core/java/android/database/sqlite/SQLiteOpenHelper.java b/core/java/android/database/sqlite/SQLiteOpenHelper.java
index 0f2e872..d8cce21 100644
--- a/core/java/android/database/sqlite/SQLiteOpenHelper.java
+++ b/core/java/android/database/sqlite/SQLiteOpenHelper.java
@@ -24,10 +24,16 @@ import android.util.Log;
/**
* A helper class to manage database creation and version management.
- * You create a subclass implementing {@link #onCreate}, {@link #onUpgrade} and
+ *
+ * <p>You create a subclass implementing {@link #onCreate}, {@link #onUpgrade} and
* optionally {@link #onOpen}, and this class takes care of opening the database
* if it exists, creating it if it does not, and upgrading it as necessary.
* Transactions are used to make sure the database is always in a sensible state.
+ *
+ * <p>This class makes it easy for {@link android.content.ContentProvider}
+ * implementations to defer opening and upgrading the database until first use,
+ * to avoid blocking application startup with long-running database upgrades.
+ *
* <p>For an example, see the NotePadProvider class in the NotePad sample application,
* in the <em>samples/</em> directory of the SDK.</p>
*
@@ -51,8 +57,9 @@ public abstract class SQLiteOpenHelper {
/**
* Create a helper object to create, open, and/or manage a database.
- * The database is not actually created or opened until one of
- * {@link #getWritableDatabase} or {@link #getReadableDatabase} is called.
+ * This method always returns very quickly. The database is not actually
+ * created or opened until one of {@link #getWritableDatabase} or
+ * {@link #getReadableDatabase} is called.
*
* @param context to use to open or create the database
* @param name of the database file, or null for an in-memory database
@@ -96,13 +103,20 @@ public abstract class SQLiteOpenHelper {
/**
* Create and/or open a database that will be used for reading and writing.
- * Once opened successfully, the database is cached, so you can call this
- * method every time you need to write to the database. Make sure to call
- * {@link #close} when you no longer need it.
+ * The first time this is called, the database will be opened and
+ * {@link #onCreate}, {@link #onUpgrade} and/or {@link #onOpen} will be
+ * called.
*
- * <p>Errors such as bad permissions or a full disk may cause this operation
+ * <p>Once opened successfully, the database is cached, so you can
+ * call this method every time you need to write to the database.
+ * (Make sure to call {@link #close} when you no longer need the database.)
+ * Errors such as bad permissions or a full disk may cause this method
* to fail, but future attempts may succeed if the problem is fixed.</p>
*
+ * <p class="caution">Database upgrade may take a long time, you
+ * should not call this method from the application main thread, including
+ * from {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
+ *
* @throws SQLiteException if the database cannot be opened for writing
* @return a read/write database object valid until {@link #close} is called
*/
@@ -183,6 +197,11 @@ public abstract class SQLiteOpenHelper {
* database object will be closed and the read/write object will be returned
* in the future.
*
+ * <p class="caution">Like {@link #getWritableDatabase}, this method may
+ * take a long time to return, so you should not call it from the
+ * application main thread, including from
+ * {@link android.content.ContentProvider#onCreate ContentProvider.onCreate()}.
+ *
* @throws SQLiteException if the database cannot be opened
* @return a database object valid until {@link #getWritableDatabase}
* or {@link #close} is called.
@@ -262,9 +281,9 @@ public abstract class SQLiteOpenHelper {
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
/**
- * Called when the database has been opened.
- * Override method should check {@link SQLiteDatabase#isReadOnly} before
- * updating the database.
+ * Called when the database has been opened. The implementation
+ * should check {@link SQLiteDatabase#isReadOnly} before updating the
+ * database.
*
* @param db The database.
*/
diff --git a/core/java/android/database/sqlite/SQLiteStatement.java b/core/java/android/database/sqlite/SQLiteStatement.java
index b902803..7a683e4 100644
--- a/core/java/android/database/sqlite/SQLiteStatement.java
+++ b/core/java/android/database/sqlite/SQLiteStatement.java
@@ -48,18 +48,31 @@ public class SQLiteStatement extends SQLiteProgram
}
/**
- * Execute this SQL statement, if it is not a query. For example,
- * CREATE TABLE, DELTE, INSERT, etc.
+ * Execute this SQL statement, if it is not a SELECT / INSERT / DELETE / UPDATE, for example
+ * CREATE / DROP table, view, trigger, index etc.
*
* @throws android.database.SQLException If the SQL string is invalid for
* some reason
*/
public void execute() {
+ executeUpdateDelete();
+ }
+
+ /**
+ * Execute this SQL statement, if the the number of rows affected by exection of this SQL
+ * statement is of any importance to the caller - for example, UPDATE / DELETE SQL statements.
+ *
+ * @return the number of rows affected by this SQL statement execution.
+ * @throws android.database.SQLException If the SQL string is invalid for
+ * some reason
+ */
+ public int executeUpdateDelete() {
synchronized(this) {
long timeStart = acquireAndLock(WRITE);
try {
- native_execute();
+ int numChanges = native_execute();
mDatabase.logTimeStat(mSql, timeStart);
+ return numChanges;
} finally {
releaseAndUnlock();
}
@@ -79,9 +92,9 @@ public class SQLiteStatement extends SQLiteProgram
synchronized(this) {
long timeStart = acquireAndLock(WRITE);
try {
- native_execute();
+ long lastInsertedRowId = native_executeInsert();
mDatabase.logTimeStat(mSql, timeStart);
- return (mDatabase.lastChangeCount() > 0) ? mDatabase.lastInsertRow() : -1;
+ return lastInsertedRowId;
} finally {
releaseAndUnlock();
}
@@ -182,7 +195,8 @@ public class SQLiteStatement extends SQLiteProgram
nHandle = mDatabase.mNativeHandle;
}
- private final native void native_execute();
+ private final native int native_execute();
+ private final native long native_executeInsert();
private final native long native_1x1_long();
private final native String native_1x1_string();
}
diff --git a/core/java/android/net/DownloadManager.java b/core/java/android/net/DownloadManager.java
index 455bd36..1d88c18 100644
--- a/core/java/android/net/DownloadManager.java
+++ b/core/java/android/net/DownloadManager.java
@@ -42,8 +42,6 @@ import java.util.Set;
* Instances of this class should be obtained through
* {@link android.content.Context#getSystemService(String)} by passing
* {@link android.content.Context#DOWNLOAD_SERVICE}.
- *
- * @hide
*/
public class DownloadManager {
/**
diff --git a/core/java/android/net/NetworkInfo.java b/core/java/android/net/NetworkInfo.java
index 21f711c..5f5e11c 100644
--- a/core/java/android/net/NetworkInfo.java
+++ b/core/java/android/net/NetworkInfo.java
@@ -97,7 +97,7 @@ public class NetworkInfo implements Parcelable {
stateMap.put(DetailedState.DISCONNECTED, State.DISCONNECTED);
stateMap.put(DetailedState.FAILED, State.DISCONNECTED);
}
-
+
private int mNetworkType;
private int mSubtype;
private String mTypeName;
@@ -144,7 +144,9 @@ public class NetworkInfo implements Parcelable {
* @return the network type
*/
public int getType() {
- return mNetworkType;
+ synchronized (this) {
+ return mNetworkType;
+ }
}
/**
@@ -153,12 +155,16 @@ public class NetworkInfo implements Parcelable {
* @return the network subtype
*/
public int getSubtype() {
- return mSubtype;
+ synchronized (this) {
+ return mSubtype;
+ }
}
void setSubtype(int subtype, String subtypeName) {
- mSubtype = subtype;
- mSubtypeName = subtypeName;
+ synchronized (this) {
+ mSubtype = subtype;
+ mSubtypeName = subtypeName;
+ }
}
/**
@@ -167,7 +173,9 @@ public class NetworkInfo implements Parcelable {
* @return the name of the network type
*/
public String getTypeName() {
- return mTypeName;
+ synchronized (this) {
+ return mTypeName;
+ }
}
/**
@@ -175,7 +183,9 @@ public class NetworkInfo implements Parcelable {
* @return the name of the network subtype
*/
public String getSubtypeName() {
- return mSubtypeName;
+ synchronized (this) {
+ return mSubtypeName;
+ }
}
/**
@@ -188,7 +198,9 @@ public class NetworkInfo implements Parcelable {
* of being established, {@code false} otherwise.
*/
public boolean isConnectedOrConnecting() {
- return mState == State.CONNECTED || mState == State.CONNECTING;
+ synchronized (this) {
+ return mState == State.CONNECTED || mState == State.CONNECTING;
+ }
}
/**
@@ -197,7 +209,9 @@ public class NetworkInfo implements Parcelable {
* @return {@code true} if network connectivity exists, {@code false} otherwise.
*/
public boolean isConnected() {
- return mState == State.CONNECTED;
+ synchronized (this) {
+ return mState == State.CONNECTED;
+ }
}
/**
@@ -213,7 +227,9 @@ public class NetworkInfo implements Parcelable {
* @return {@code true} if the network is available, {@code false} otherwise
*/
public boolean isAvailable() {
- return mIsAvailable;
+ synchronized (this) {
+ return mIsAvailable;
+ }
}
/**
@@ -223,7 +239,9 @@ public class NetworkInfo implements Parcelable {
* @hide
*/
public void setIsAvailable(boolean isAvailable) {
- mIsAvailable = isAvailable;
+ synchronized (this) {
+ mIsAvailable = isAvailable;
+ }
}
/**
@@ -234,7 +252,9 @@ public class NetworkInfo implements Parcelable {
* otherwise.
*/
public boolean isFailover() {
- return mIsFailover;
+ synchronized (this) {
+ return mIsFailover;
+ }
}
/**
@@ -244,7 +264,9 @@ public class NetworkInfo implements Parcelable {
* @hide
*/
public void setFailover(boolean isFailover) {
- mIsFailover = isFailover;
+ synchronized (this) {
+ mIsFailover = isFailover;
+ }
}
/**
@@ -254,11 +276,15 @@ public class NetworkInfo implements Parcelable {
* @return {@code true} if roaming is in effect, {@code false} otherwise.
*/
public boolean isRoaming() {
- return mIsRoaming;
+ synchronized (this) {
+ return mIsRoaming;
+ }
}
void setRoaming(boolean isRoaming) {
- mIsRoaming = isRoaming;
+ synchronized (this) {
+ mIsRoaming = isRoaming;
+ }
}
/**
@@ -266,7 +292,9 @@ public class NetworkInfo implements Parcelable {
* @return the coarse-grained state
*/
public State getState() {
- return mState;
+ synchronized (this) {
+ return mState;
+ }
}
/**
@@ -274,7 +302,9 @@ public class NetworkInfo implements Parcelable {
* @return the fine-grained state
*/
public DetailedState getDetailedState() {
- return mDetailedState;
+ synchronized (this) {
+ return mDetailedState;
+ }
}
/**
@@ -287,10 +317,12 @@ public class NetworkInfo implements Parcelable {
* @hide
*/
public void setDetailedState(DetailedState detailedState, String reason, String extraInfo) {
- this.mDetailedState = detailedState;
- this.mState = stateMap.get(detailedState);
- this.mReason = reason;
- this.mExtraInfo = extraInfo;
+ synchronized (this) {
+ this.mDetailedState = detailedState;
+ this.mState = stateMap.get(detailedState);
+ this.mReason = reason;
+ this.mExtraInfo = extraInfo;
+ }
}
/**
@@ -299,7 +331,9 @@ public class NetworkInfo implements Parcelable {
* @return the reason for failure, or null if not available
*/
public String getReason() {
- return mReason;
+ synchronized (this) {
+ return mReason;
+ }
}
/**
@@ -309,20 +343,24 @@ public class NetworkInfo implements Parcelable {
* @return the extra information, or null if not available
*/
public String getExtraInfo() {
- return mExtraInfo;
+ synchronized (this) {
+ return mExtraInfo;
+ }
}
@Override
public String toString() {
- StringBuilder builder = new StringBuilder("NetworkInfo: ");
- builder.append("type: ").append(getTypeName()).append("[").append(getSubtypeName()).
- append("], state: ").append(mState).append("/").append(mDetailedState).
- append(", reason: ").append(mReason == null ? "(unspecified)" : mReason).
- append(", extra: ").append(mExtraInfo == null ? "(none)" : mExtraInfo).
- append(", roaming: ").append(mIsRoaming).
- append(", failover: ").append(mIsFailover).
- append(", isAvailable: ").append(mIsAvailable);
- return builder.toString();
+ synchronized (this) {
+ StringBuilder builder = new StringBuilder("NetworkInfo: ");
+ builder.append("type: ").append(getTypeName()).append("[").append(getSubtypeName()).
+ append("], state: ").append(mState).append("/").append(mDetailedState).
+ append(", reason: ").append(mReason == null ? "(unspecified)" : mReason).
+ append(", extra: ").append(mExtraInfo == null ? "(none)" : mExtraInfo).
+ append(", roaming: ").append(mIsRoaming).
+ append(", failover: ").append(mIsFailover).
+ append(", isAvailable: ").append(mIsAvailable);
+ return builder.toString();
+ }
}
/**
@@ -338,17 +376,19 @@ public class NetworkInfo implements Parcelable {
* @hide
*/
public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mNetworkType);
- dest.writeInt(mSubtype);
- dest.writeString(mTypeName);
- dest.writeString(mSubtypeName);
- dest.writeString(mState.name());
- dest.writeString(mDetailedState.name());
- dest.writeInt(mIsFailover ? 1 : 0);
- dest.writeInt(mIsAvailable ? 1 : 0);
- dest.writeInt(mIsRoaming ? 1 : 0);
- dest.writeString(mReason);
- dest.writeString(mExtraInfo);
+ synchronized (this) {
+ dest.writeInt(mNetworkType);
+ dest.writeInt(mSubtype);
+ dest.writeString(mTypeName);
+ dest.writeString(mSubtypeName);
+ dest.writeString(mState.name());
+ dest.writeString(mDetailedState.name());
+ dest.writeInt(mIsFailover ? 1 : 0);
+ dest.writeInt(mIsAvailable ? 1 : 0);
+ dest.writeInt(mIsRoaming ? 1 : 0);
+ dest.writeString(mReason);
+ dest.writeString(mExtraInfo);
+ }
}
/**
diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java
index 59b8274..f8260ca 100644
--- a/core/java/android/os/Binder.java
+++ b/core/java/android/os/Binder.java
@@ -226,9 +226,16 @@ public class Binder implements IBinder {
try {
fd.close();
} catch (IOException e) {
+ // swallowed, not propagated back to the caller
}
}
}
+ // Write the StrictMode header.
+ if (reply != null) {
+ reply.writeNoException();
+ } else {
+ StrictMode.clearGatheredViolations();
+ }
return true;
}
return false;
@@ -341,12 +348,15 @@ final class BinderProxy implements IBinder {
public void dump(FileDescriptor fd, String[] args) throws RemoteException {
Parcel data = Parcel.obtain();
+ Parcel reply = Parcel.obtain();
data.writeFileDescriptor(fd);
data.writeStringArray(args);
try {
- transact(DUMP_TRANSACTION, data, null, 0);
+ transact(DUMP_TRANSACTION, data, reply, 0);
+ reply.readException();
} finally {
data.recycle();
+ reply.recycle();
}
}
diff --git a/core/java/android/os/IPowerManager.aidl b/core/java/android/os/IPowerManager.aidl
index dedc347..01cc408 100644
--- a/core/java/android/os/IPowerManager.aidl
+++ b/core/java/android/os/IPowerManager.aidl
@@ -26,6 +26,7 @@ interface IPowerManager
void releaseWakeLock(IBinder lock, int flags);
void userActivity(long when, boolean noChangeLights);
void userActivityWithForce(long when, boolean noChangeLights, boolean force);
+ void clearUserActivityTimeout(long now, long timeout);
void setPokeLock(int pokey, IBinder lock, String tag);
int getSupportedWakeLockFlags();
void setStayOnSetting(int val);
diff --git a/core/java/android/os/StrictMode.java b/core/java/android/os/StrictMode.java
index dc92590..d4b0500 100644
--- a/core/java/android/os/StrictMode.java
+++ b/core/java/android/os/StrictMode.java
@@ -97,7 +97,7 @@ public final class StrictMode {
* via Parcel.writeNoException() (amusingly) where the caller can
* choose how to react.
*/
- private static ThreadLocal<ArrayList<ApplicationErrorReport.CrashInfo>> gatheredViolations =
+ private static final ThreadLocal<ArrayList<ApplicationErrorReport.CrashInfo>> gatheredViolations =
new ThreadLocal<ArrayList<ApplicationErrorReport.CrashInfo>>() {
@Override protected ArrayList<ApplicationErrorReport.CrashInfo> initialValue() {
// Starts null to avoid unnecessary allocations when
diff --git a/core/java/android/speech/tts/TextToSpeech.java b/core/java/android/speech/tts/TextToSpeech.java
index 26c167e..841257f 100755
--- a/core/java/android/speech/tts/TextToSpeech.java
+++ b/core/java/android/speech/tts/TextToSpeech.java
@@ -1065,6 +1065,9 @@ public class TextToSpeech {
if (!mStarted) {
return result;
}
+ if (loc == null) {
+ return result;
+ }
try {
String language = loc.getISO3Language();
String country = loc.getISO3Country();
diff --git a/core/java/android/view/ActionMode.java b/core/java/android/view/ActionMode.java
new file mode 100644
index 0000000..d4f4b93
--- /dev/null
+++ b/core/java/android/view/ActionMode.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package android.view;
+
+
+/**
+ * Represents a contextual mode of the user interface. Action modes can be used for
+ * modal interactions with content and replace parts of the normal UI until finished.
+ * Examples of good action modes include selection modes, search, content editing, etc.
+ */
+public abstract class ActionMode {
+ /**
+ * Set the title of the action mode. This method will have no visible effect if
+ * a custom view has been set.
+ *
+ * @param title Title string to set
+ *
+ * @see #setCustomView(View)
+ */
+ public abstract void setTitle(CharSequence title);
+
+ /**
+ * Set the subtitle of the action mode. This method will have no visible effect if
+ * a custom view has been set.
+ *
+ * @param subtitle Subtitle string to set
+ *
+ * @see #setCustomView(View)
+ */
+ public abstract void setSubtitle(CharSequence subtitle);
+
+ /**
+ * Set a custom view for this action mode. The custom view will take the place of
+ * the title and subtitle. Useful for things like search boxes.
+ *
+ * @param view Custom view to use in place of the title/subtitle.
+ *
+ * @see #setTitle(CharSequence)
+ * @see #setSubtitle(CharSequence)
+ */
+ public abstract void setCustomView(View view);
+
+ /**
+ * Invalidate the action mode and refresh menu content. The mode's
+ * {@link ActionMode.Callback} will have its
+ * {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called.
+ * If it returns true the menu will be scanned for updated content and any relevant changes
+ * will be reflected to the user.
+ */
+ public abstract void invalidate();
+
+ /**
+ * Finish and close this action mode. The action mode's {@link ActionMode.Callback} will
+ * have its {@link Callback#onDestroyActionMode(ActionMode)} method called.
+ */
+ public abstract void finish();
+
+ /**
+ * Returns the menu of actions that this action mode presents.
+ * @return The action mode's menu.
+ */
+ public abstract Menu getMenu();
+
+ /**
+ * Returns the current title of this action mode.
+ * @return Title text
+ */
+ public abstract CharSequence getTitle();
+
+ /**
+ * Returns the current subtitle of this action mode.
+ * @return Subtitle text
+ */
+ public abstract CharSequence getSubtitle();
+
+ /**
+ * Returns the current custom view for this action mode.
+ * @return The current custom view
+ */
+ public abstract View getCustomView();
+
+ /**
+ * Callback interface for action modes. Supplied to
+ * {@link View#startActionMode(Callback)}, a Callback
+ * configures and handles events raised by a user's interaction with an action mode.
+ *
+ * <p>An action mode's lifecycle is as follows:
+ * <ul>
+ * <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial
+ * creation</li>
+ * <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation
+ * and any time the {@link ActionMode} is invalidated</li>
+ * <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a
+ * contextual action button is clicked</li>
+ * <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode
+ * is closed</li>
+ * </ul>
+ */
+ public interface Callback {
+ /**
+ * Called when action mode is first created. The menu supplied will be used to
+ * generate action buttons for the action mode.
+ *
+ * @param mode ActionMode being created
+ * @param menu Menu used to populate action buttons
+ * @return true if the action mode should be created, false if entering this
+ * mode should be aborted.
+ */
+ public boolean onCreateActionMode(ActionMode mode, Menu menu);
+
+ /**
+ * Called to refresh an action mode's action menu whenever it is invalidated.
+ *
+ * @param mode ActionMode being prepared
+ * @param menu Menu used to populate action buttons
+ * @return true if the menu or action mode was updated, false otherwise.
+ */
+ public boolean onPrepareActionMode(ActionMode mode, Menu menu);
+
+ /**
+ * Called to report a user click on an action button.
+ *
+ * @param mode The current ActionMode
+ * @param item The item that was clicked
+ * @return true if this callback handled the event, false if the standard MenuItem
+ * invocation should continue.
+ */
+ public boolean onActionItemClicked(ActionMode mode, MenuItem item);
+
+ /**
+ * Called when an action mode is about to be exited and destroyed.
+ *
+ * @param mode The current ActionMode being destroyed
+ */
+ public void onDestroyActionMode(ActionMode mode);
+ }
+} \ No newline at end of file
diff --git a/core/java/android/view/MenuInflater.java b/core/java/android/view/MenuInflater.java
index 4a966b5..a959e0d 100644
--- a/core/java/android/view/MenuInflater.java
+++ b/core/java/android/view/MenuInflater.java
@@ -350,6 +350,10 @@ public class MenuInflater {
.setShowAsAction(itemShowAsAction);
if (itemListenerMethodName != null) {
+ if (mContext.isRestricted()) {
+ throw new IllegalStateException("The android:onClick attribute cannot "
+ + "be used within a restricted context");
+ }
item.setOnMenuItemClickListener(
new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName));
}
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index b1025c9..363aced 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -16,7 +16,6 @@
package android.view;
-import android.graphics.RectF;
import com.android.internal.R;
import com.android.internal.view.menu.MenuBuilder;
@@ -35,6 +34,7 @@ import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
+import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.Shader;
import android.graphics.drawable.ColorDrawable;
@@ -57,6 +57,7 @@ import android.util.PoolableManager;
import android.util.Pools;
import android.util.SparseArray;
import android.view.ContextMenu.ContextMenuInfo;
+import android.view.View.MeasureSpec;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityEventSource;
import android.view.accessibility.AccessibilityManager;
@@ -2541,6 +2542,18 @@ public class View implements Drawable.Callback, KeyEvent.Callback, Accessibility
}
/**
+ * Start an action mode.
+ *
+ * @param callback Callback that will control the lifecycle of the action mode
+ * @return The new action mode if it is started, null otherwise
+ *
+ * @see ActionMode
+ */
+ public ActionMode startActionMode(ActionMode.Callback callback) {
+ return getParent().startActionModeForChild(this, callback);
+ }
+
+ /**
* Register a callback to be invoked when a key is pressed in this view.
* @param l the key listener to attach to this view
*/
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 3c161ca..a713efc 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -16,7 +16,6 @@
package android.view;
-import android.graphics.Matrix;
import com.android.internal.R;
import android.content.Context;
@@ -24,6 +23,7 @@ import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
+import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
@@ -35,6 +35,7 @@ import android.util.Config;
import android.util.EventLog;
import android.util.Log;
import android.util.SparseArray;
+import android.view.ViewGroup.LayoutParams;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
@@ -474,6 +475,13 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
}
/**
+ * {@inheritDoc}
+ */
+ public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
+ return mParent != null ? mParent.startActionModeForChild(originalView, callback) : null;
+ }
+
+ /**
* Find the nearest view in the specified direction that wants to take
* focus.
*
diff --git a/core/java/android/view/ViewParent.java b/core/java/android/view/ViewParent.java
index b456c5d..d7d4c3f 100644
--- a/core/java/android/view/ViewParent.java
+++ b/core/java/android/view/ViewParent.java
@@ -162,6 +162,20 @@ public interface ViewParent {
public void createContextMenu(ContextMenu menu);
/**
+ * Start an action mode for the specified view.
+ * <p>
+ * In most cases, a subclass does not need to override this. However, if the
+ * subclass is added directly to the window manager (for example,
+ * {@link ViewManager#addView(View, android.view.ViewGroup.LayoutParams)})
+ * then it should override this and start the action mode.
+ *
+ * @param originalView The source view where the action mode was first invoked
+ * @param callback The callback that will handle lifecycle events for the action mode
+ * @return The new action mode if it was started, null otherwise
+ */
+ public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback);
+
+ /**
* This method is called on the parent when a child's drawable state
* has changed.
*
diff --git a/core/java/android/view/ViewRoot.java b/core/java/android/view/ViewRoot.java
index 03cbb8a..877a302 100644
--- a/core/java/android/view/ViewRoot.java
+++ b/core/java/android/view/ViewRoot.java
@@ -2717,6 +2717,10 @@ public final class ViewRoot extends Handler implements ViewParent, View.AttachIn
return false;
}
+ public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
+ return null;
+ }
+
public void createContextMenu(ContextMenu menu) {
}
diff --git a/core/java/android/view/Window.java b/core/java/android/view/Window.java
index be681cc..0d4e84b 100644
--- a/core/java/android/view/Window.java
+++ b/core/java/android/view/Window.java
@@ -56,18 +56,18 @@ public abstract class Window {
public static final int FEATURE_CONTEXT_MENU = 6;
/** Flag for custom title. You cannot combine this feature with other title features. */
public static final int FEATURE_CUSTOM_TITLE = 7;
- /** Flag for asking for an OpenGL enabled window.
- All 2D graphics will be handled by OpenGL ES.
- @hide
- */
- public static final int FEATURE_OPENGL = 8;
/**
* Flag for enabling the Action Bar.
* This is enabled by default for some devices. The Action Bar
* replaces the title bar and provides an alternate location
* for an on-screen menu button on some devices.
*/
- public static final int FEATURE_ACTION_BAR = 9;
+ public static final int FEATURE_ACTION_BAR = 8;
+ /**
+ * Flag for specifying the behavior of action modes when an Action Bar is not present.
+ * If overlay is enabled, the action mode UI will be allowed to cover existing window content.
+ */
+ public static final int FEATURE_ACTION_MODE_OVERLAY = 9;
/** Flag for setting the progress bar's visibility to VISIBLE */
public static final int PROGRESS_VISIBILITY_ON = -1;
/** Flag for setting the progress bar's visibility to GONE */
@@ -299,6 +299,14 @@ public abstract class Window {
* @see android.app.Activity#onSearchRequested()
*/
public boolean onSearchRequested();
+
+ /**
+ * Called when an action mode is being started.
+ *
+ * @param callback Callback to control the lifecycle of this action mode
+ * @return The ActionMode that was started, or null if it was canceled
+ */
+ public ActionMode onStartActionMode(ActionMode.Callback callback);
}
public Window(Context context) {
diff --git a/core/java/com/android/internal/app/ActionBarImpl.java b/core/java/com/android/internal/app/ActionBarImpl.java
index 050f630..e457701 100644
--- a/core/java/com/android/internal/app/ActionBarImpl.java
+++ b/core/java/com/android/internal/app/ActionBarImpl.java
@@ -24,11 +24,11 @@ import com.android.internal.widget.ActionBarView;
import android.app.ActionBar;
import android.app.Activity;
-import android.app.ContextualMode;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.graphics.drawable.Drawable;
import android.os.Handler;
+import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@@ -66,7 +66,7 @@ public class ActionBarImpl extends ActionBar {
private TabImpl mSelectedTab;
private int mTabSwitchMode = TAB_SWITCH_ADD_REMOVE;
- private ContextMode mContextMode;
+ private ActionMode mActionMode;
private static final int CONTEXT_DISPLAY_NORMAL = 0;
private static final int CONTEXT_DISPLAY_SPLIT = 1;
@@ -229,8 +229,10 @@ public class ActionBarImpl extends ActionBar {
return mActionView.getDisplayOptions();
}
- public ContextualMode startContextualMode(ContextualMode.Callback callback) {
- finishContextualMode();
+ public ActionMode startActionMode(ActionMode.Callback callback) {
+ if (mActionMode != null) {
+ mActionMode.finish();
+ }
// Don't wait for the close context mode animation to finish.
if (mClosingContext) {
@@ -239,8 +241,8 @@ public class ActionBarImpl extends ActionBar {
mCloseContext.run();
}
- ContextMode mode = new ContextMode(callback);
- if (callback.onCreateContextualMode(mode, mode.getMenu())) {
+ ActionMode mode = new ActionModeImpl(callback);
+ if (callback.onCreateActionMode(mode, mode.getMenu())) {
mode.invalidate();
mUpperContextView.initForMode(mode);
mAnimatorView.setDisplayedChild(CONTEXT_VIEW);
@@ -248,18 +250,12 @@ public class ActionBarImpl extends ActionBar {
// TODO animate this
mLowerContextView.setVisibility(View.VISIBLE);
}
- mContextMode = mode;
+ mActionMode = mode;
return mode;
}
return null;
}
- public void finishContextualMode() {
- if (mContextMode != null) {
- mContextMode.finish();
- }
- }
-
private void configureTab(Tab tab, int position) {
final TabImpl tabi = (TabImpl) tab;
final boolean isFirstTab = mTabs.isEmpty();
@@ -365,12 +361,12 @@ public class ActionBarImpl extends ActionBar {
/**
* @hide
*/
- public class ContextMode extends ContextualMode implements MenuBuilder.Callback {
- private ContextualMode.Callback mCallback;
+ public class ActionModeImpl extends ActionMode implements MenuBuilder.Callback {
+ private ActionMode.Callback mCallback;
private MenuBuilder mMenu;
private WeakReference<View> mCustomView;
- public ContextMode(ContextualMode.Callback callback) {
+ public ActionModeImpl(ActionMode.Callback callback) {
mCallback = callback;
mMenu = new MenuBuilder(mActionView.getContext());
mMenu.setCallback(this);
@@ -383,12 +379,12 @@ public class ActionBarImpl extends ActionBar {
@Override
public void finish() {
- if (mContextMode != this) {
- // Not the active context mode - no-op
+ if (mActionMode != this) {
+ // Not the active action mode - no-op
return;
}
- mCallback.onDestroyContextualMode(this);
+ mCallback.onDestroyActionMode(this);
mAnimatorView.setDisplayedChild(NORMAL_VIEW);
// Clear out the context mode views after the animation finishes
@@ -399,12 +395,12 @@ public class ActionBarImpl extends ActionBar {
// TODO Animate this
mLowerContextView.setVisibility(View.GONE);
}
- mContextMode = null;
+ mActionMode = null;
}
@Override
public void invalidate() {
- if (mCallback.onPrepareContextualMode(this, mMenu)) {
+ if (mCallback.onPrepareActionMode(this, mMenu)) {
// Refresh content in both context views
}
}
@@ -441,7 +437,7 @@ public class ActionBarImpl extends ActionBar {
}
public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
- return mCallback.onContextualItemClicked(this, item);
+ return mCallback.onActionItemClicked(this, item);
}
public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
diff --git a/core/java/com/android/internal/view/StandaloneActionMode.java b/core/java/com/android/internal/view/StandaloneActionMode.java
new file mode 100644
index 0000000..13eda10
--- /dev/null
+++ b/core/java/com/android/internal/view/StandaloneActionMode.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+package com.android.internal.view;
+
+import com.android.internal.view.menu.MenuBuilder;
+import com.android.internal.view.menu.MenuPopupHelper;
+import com.android.internal.view.menu.SubMenuBuilder;
+import com.android.internal.widget.ActionBarContextView;
+
+import android.content.Context;
+import android.view.ActionMode;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+
+import java.lang.ref.WeakReference;
+
+public class StandaloneActionMode extends ActionMode implements MenuBuilder.Callback {
+ private Context mContext;
+ private ActionBarContextView mContextView;
+ private ActionMode.Callback mCallback;
+ private WeakReference<View> mCustomView;
+ private boolean mFinished;
+
+ private MenuBuilder mMenu;
+
+ public StandaloneActionMode(Context context, ActionBarContextView view,
+ ActionMode.Callback callback) {
+ mContext = context;
+ mContextView = view;
+ mCallback = callback;
+
+ mMenu = new MenuBuilder(context);
+ mMenu.setCallback(this);
+ }
+
+ @Override
+ public void setTitle(CharSequence title) {
+ mContextView.setTitle(title);
+ }
+
+ @Override
+ public void setSubtitle(CharSequence subtitle) {
+ mContextView.setSubtitle(subtitle);
+ }
+
+ @Override
+ public void setCustomView(View view) {
+ mContextView.setCustomView(view);
+ mCustomView = view != null ? new WeakReference<View>(view) : null;
+ }
+
+ @Override
+ public void invalidate() {
+ mCallback.onPrepareActionMode(this, mMenu);
+ }
+
+ @Override
+ public void finish() {
+ if (mFinished) {
+ return;
+ }
+ mFinished = true;
+
+ mCallback.onDestroyActionMode(this);
+ mContextView.setVisibility(View.GONE);
+ }
+
+ @Override
+ public Menu getMenu() {
+ return mMenu;
+ }
+
+ @Override
+ public CharSequence getTitle() {
+ return mContextView.getTitle();
+ }
+
+ @Override
+ public CharSequence getSubtitle() {
+ return mContextView.getSubtitle();
+ }
+
+ @Override
+ public View getCustomView() {
+ return mCustomView != null ? mCustomView.get() : null;
+ }
+
+ public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) {
+ return mCallback.onActionItemClicked(this, item);
+ }
+
+ public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) {
+ }
+
+ public boolean onSubMenuSelected(SubMenuBuilder subMenu) {
+ if (!subMenu.hasVisibleItems()) {
+ return true;
+ }
+
+ new MenuPopupHelper(mContext, subMenu).show();
+ return true;
+ }
+
+ public void onCloseSubMenu(SubMenuBuilder menu) {
+ }
+
+ public void onMenuModeChange(MenuBuilder menu) {
+ }
+}
diff --git a/core/java/com/android/internal/widget/ActionBarContextView.java b/core/java/com/android/internal/widget/ActionBarContextView.java
index 08405a3..0bedc4e 100644
--- a/core/java/com/android/internal/widget/ActionBarContextView.java
+++ b/core/java/com/android/internal/widget/ActionBarContextView.java
@@ -19,11 +19,11 @@ import com.android.internal.R;
import com.android.internal.view.menu.ActionMenuView;
import com.android.internal.view.menu.MenuBuilder;
-import android.app.ContextualMode;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
+import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -70,9 +70,9 @@ public class ActionBarContextView extends ViewGroup {
mItemPadding = a.getDimensionPixelOffset(
com.android.internal.R.styleable.Theme_actionButtonPadding, 0);
setBackgroundDrawable(a.getDrawable(
- com.android.internal.R.styleable.Theme_actionBarContextBackground));
+ com.android.internal.R.styleable.Theme_actionModeBackground));
mCloseDrawable = a.getDrawable(
- com.android.internal.R.styleable.Theme_actionBarCloseContextDrawable);
+ com.android.internal.R.styleable.Theme_actionModeCloseDrawable);
mItemMargin = mItemPadding / 2;
mContentHeight =
@@ -135,7 +135,7 @@ public class ActionBarContextView extends ViewGroup {
}
}
- public void initForMode(final ContextualMode mode) {
+ public void initForMode(final ActionMode mode) {
if (mCloseButton == null) {
mCloseButton = new ImageButton(getContext());
mCloseButton.setImageDrawable(mCloseDrawable);
diff --git a/core/jni/android_database_SQLiteDatabase.cpp b/core/jni/android_database_SQLiteDatabase.cpp
index 290b532..003bbc1 100644
--- a/core/jni/android_database_SQLiteDatabase.cpp
+++ b/core/jni/android_database_SQLiteDatabase.cpp
@@ -15,7 +15,7 @@
*/
#undef LOG_TAG
-#define LOG_TAG "Database"
+#define LOG_TAG "SqliteDatabaseCpp"
#include <utils/Log.h>
#include <utils/String8.h>
@@ -245,77 +245,6 @@ static void dbclose(JNIEnv* env, jobject object)
}
}
-/* public native void native_execSQL(String sql); */
-static void native_execSQL(JNIEnv* env, jobject object, jstring sqlString)
-{
- int err;
- int stepErr;
- sqlite3_stmt * statement = NULL;
- sqlite3 * handle = (sqlite3 *)env->GetIntField(object, offset_db_handle);
- jchar const * sql = env->GetStringChars(sqlString, NULL);
- jsize sqlLen = env->GetStringLength(sqlString);
-
- if (sql == NULL || sqlLen == 0) {
- jniThrowException(env, "java/lang/IllegalArgumentException",
- "You must supply an SQL string");
- return;
- }
-
- err = sqlite3_prepare16_v2(handle, sql, sqlLen * 2, &statement, NULL);
-
- env->ReleaseStringChars(sqlString, sql);
-
- if (err != SQLITE_OK) {
- char const * sql8 = env->GetStringUTFChars(sqlString, NULL);
- LOGE("Failure %d (%s) on %p when preparing '%s'.\n", err, sqlite3_errmsg(handle),
- handle, sql8);
- throw_sqlite3_exception(env, handle, sql8);
- env->ReleaseStringUTFChars(sqlString, sql8);
- return;
- }
-
- stepErr = sqlite3_step(statement);
- err = sqlite3_finalize(statement);
-
- if (stepErr != SQLITE_DONE) {
- if (stepErr == SQLITE_ROW) {
- throw_sqlite3_exception(env,
- "Queries cannot be performed using execSQL(), use query() instead.");
- } else {
- char const * sql8 = env->GetStringUTFChars(sqlString, NULL);
- LOGE("Failure %d (%s) on %p when executing '%s'\n", err, sqlite3_errmsg(handle),
- handle, sql8);
- throw_sqlite3_exception(env, handle, sql8);
- env->ReleaseStringUTFChars(sqlString, sql8);
-
- }
- } else
-#ifndef DB_LOG_STATEMENTS
- IF_LOGV()
-#endif
- {
- char const * sql8 = env->GetStringUTFChars(sqlString, NULL);
- LOGV("Success on %p when executing '%s'\n", handle, sql8);
- env->ReleaseStringUTFChars(sqlString, sql8);
- }
-}
-
-/* native long lastInsertRow(); */
-static jlong lastInsertRow(JNIEnv* env, jobject object)
-{
- sqlite3 * handle = (sqlite3 *)env->GetIntField(object, offset_db_handle);
-
- return sqlite3_last_insert_rowid(handle);
-}
-
-/* native int lastChangeCount(); */
-static jint lastChangeCount(JNIEnv* env, jobject object)
-{
- sqlite3 * handle = (sqlite3 *)env->GetIntField(object, offset_db_handle);
-
- return sqlite3_changes(handle);
-}
-
/* native int native_getDbLookaside(); */
static jint native_getDbLookaside(JNIEnv* env, jobject object)
{
@@ -522,9 +451,6 @@ static JNINativeMethod sMethods[] =
{"dbclose", "()V", (void *)dbclose},
{"enableSqlTracing", "(Ljava/lang/String;S)V", (void *)enableSqlTracing},
{"enableSqlProfiling", "(Ljava/lang/String;S)V", (void *)enableSqlProfiling},
- {"native_execSQL", "(Ljava/lang/String;)V", (void *)native_execSQL},
- {"lastInsertRow", "()J", (void *)lastInsertRow},
- {"lastChangeCount", "()I", (void *)lastChangeCount},
{"native_setLocale", "(Ljava/lang/String;I)V", (void *)native_setLocale},
{"native_getDbLookaside", "()I", (void *)native_getDbLookaside},
{"releaseMemory", "()I", (void *)native_releaseMemory},
diff --git a/core/jni/android_database_SQLiteStatement.cpp b/core/jni/android_database_SQLiteStatement.cpp
index 0341e0b..2212d9a 100644
--- a/core/jni/android_database_SQLiteStatement.cpp
+++ b/core/jni/android_database_SQLiteStatement.cpp
@@ -16,7 +16,7 @@
*/
#undef LOG_TAG
-#define LOG_TAG "Cursor"
+#define LOG_TAG "SQLiteStatementCpp"
#include <jni.h>
#include <JNIHelp.h>
@@ -48,24 +48,40 @@ static jfieldID gStatementField;
(sqlite3 *)env->GetIntField(object, gHandleField)
-static void native_execute(JNIEnv* env, jobject object)
+static jint native_execute(JNIEnv* env, jobject object)
{
int err;
sqlite3 * handle = GET_HANDLE(env, object);
sqlite3_stmt * statement = GET_STATEMENT(env, object);
+ int numChanges = -1;
// Execute the statement
err = sqlite3_step(statement);
- // Throw an exception if an error occured
+ // Throw an exception if an error occurred
if (err == SQLITE_ROW) {
- LOGV("Queries cannot be performed using execute(). use SQLiteDatabase.query() instead.");
+ throw_sqlite3_exception(env,
+ "Queries can be performed using SQLiteDatabase query or rawQuery methods only.");
} else if (err != SQLITE_DONE) {
throw_sqlite3_exception_errcode(env, err, sqlite3_errmsg(handle));
+ } else {
+ numChanges = sqlite3_changes(handle);
}
- // Reset the statment so it's ready to use again
+ // Reset the statement so it's ready to use again
sqlite3_reset(statement);
+ return numChanges;
+}
+
+static jlong native_executeInsert(JNIEnv* env, jobject object)
+{
+ sqlite3 * handle = GET_HANDLE(env, object);
+ jint numChanges = native_execute(env, object);
+ if (numChanges > 0) {
+ return sqlite3_last_insert_rowid(handle);
+ } else {
+ return -1;
+ }
}
static jlong native_1x1_long(JNIEnv* env, jobject object)
@@ -117,11 +133,11 @@ static jstring native_1x1_string(JNIEnv* env, jobject object)
return value;
}
-
static JNINativeMethod sMethods[] =
{
/* name, signature, funcPtr */
- {"native_execute", "()V", (void *)native_execute},
+ {"native_execute", "()I", (void *)native_execute},
+ {"native_executeInsert", "()J", (void *)native_executeInsert},
{"native_1x1_long", "()J", (void *)native_1x1_long},
{"native_1x1_string", "()Ljava/lang/String;", (void *)native_1x1_string},
};
diff --git a/core/jni/android_net_wifi_Wifi.cpp b/core/jni/android_net_wifi_Wifi.cpp
index 7392442..aec537d 100644
--- a/core/jni/android_net_wifi_Wifi.cpp
+++ b/core/jni/android_net_wifi_Wifi.cpp
@@ -98,6 +98,11 @@ static jstring doStringCommand(JNIEnv *env, const char *cmd)
}
}
+static jboolean android_net_wifi_isDriverLoaded(JNIEnv* env, jobject clazz)
+{
+ return (jboolean)(::is_wifi_driver_loaded() == 1);
+}
+
static jboolean android_net_wifi_loadDriver(JNIEnv* env, jobject clazz)
{
return (jboolean)(::wifi_load_driver() == 0);
@@ -524,6 +529,7 @@ static JNINativeMethod gWifiMethods[] = {
/* name, signature, funcPtr */
{ "loadDriver", "()Z", (void *)android_net_wifi_loadDriver },
+ { "isDriverLoaded", "()Z", (void *)android_net_wifi_isDriverLoaded},
{ "unloadDriver", "()Z", (void *)android_net_wifi_unloadDriver },
{ "startSupplicant", "()Z", (void *)android_net_wifi_startSupplicant },
{ "stopSupplicant", "()Z", (void *)android_net_wifi_stopSupplicant },
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 040b324..5c4e4fd 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -1566,15 +1566,15 @@ static void android_os_Parcel_enforceInterface(JNIEnv* env, jobject clazz, jstri
if (parcel != NULL) {
const jchar* str = env->GetStringCritical(name, 0);
if (str) {
- const int32_t old_strict_policy =
- IPCThreadState::self()->getStrictModePolicy();
- int32_t strict_policy;
- bool isValid = parcel->enforceInterface(
+ IPCThreadState* threadState = IPCThreadState::self();
+ const int32_t oldPolicy = threadState->getStrictModePolicy();
+ const bool isValid = parcel->enforceInterface(
String16(str, env->GetStringLength(name)),
- &strict_policy);
+ threadState);
env->ReleaseStringCritical(name, str);
if (isValid) {
- if (old_strict_policy != strict_policy) {
+ const int32_t newPolicy = threadState->getStrictModePolicy();
+ if (oldPolicy != newPolicy) {
// Need to keep the Java-level thread-local strict
// mode policy in sync for the libcore
// enforcements, which involves an upcall back
@@ -1582,7 +1582,7 @@ static void android_os_Parcel_enforceInterface(JNIEnv* env, jobject clazz, jstri
// Parcel.enforceInterface signature, as it's
// pseudo-public, and used via AIDL
// auto-generation...)
- set_dalvik_blockguard_policy(env, strict_policy);
+ set_dalvik_blockguard_policy(env, newPolicy);
}
return; // everything was correct -> return silently
}
diff --git a/core/res/res/layout/screen_xlarge_action_bar.xml b/core/res/res/layout-xlarge/screen_action_bar.xml
index c51ca13..41ce8e4 100644
--- a/core/res/res/layout/screen_xlarge_action_bar.xml
+++ b/core/res/res/layout-xlarge/screen_action_bar.xml
@@ -4,9 +4,9 @@
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.
@@ -37,7 +37,7 @@ This is an optimized layout for a screen with the Action Bar enabled.
android:layout_height="wrap_content" />
</ViewAnimator>
<FrameLayout android:id="@android:id/content"
- android:layout_width="match_parent"
+ android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
diff --git a/core/res/res/layout/screen.xml b/core/res/res/layout/screen.xml
index dfa9731..0269bf1 100644
--- a/core/res/res/layout/screen.xml
+++ b/core/res/res/layout/screen.xml
@@ -25,6 +25,13 @@ This is the basic layout for a screen, with all of its features enabled.
android:layout_width="match_parent"
android:layout_height="match_parent"
>
+ <!-- Popout bar for action modes -->
+ <com.android.internal.widget.ActionBarContextView
+ android:id="@+id/action_mode_bar"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:visibility="gone" />
+
<!-- Title bar -->
<RelativeLayout android:id="@android:id/title_container"
style="?android:attr/windowTitleBackgroundStyle"
diff --git a/core/res/res/layout/screen_custom_title.xml b/core/res/res/layout/screen_custom_title.xml
index 34c9de0..fe06ddd 100644
--- a/core/res/res/layout/screen_custom_title.xml
+++ b/core/res/res/layout/screen_custom_title.xml
@@ -21,6 +21,13 @@ This is an custom layout for a screen.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
+ <!-- Popout bar for action modes -->
+ <com.android.internal.widget.ActionBarContextView
+ android:id="@+id/action_mode_bar"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:visibility="gone" />
+
<FrameLayout android:id="@android:id/title_container"
android:layout_width="match_parent"
android:layout_height="?android:attr/windowTitleSize"
diff --git a/core/res/res/layout/screen_progress.xml b/core/res/res/layout/screen_progress.xml
index 6e694c1..9669533 100644
--- a/core/res/res/layout/screen_progress.xml
+++ b/core/res/res/layout/screen_progress.xml
@@ -26,6 +26,13 @@ This is the basic layout for a screen, with all of its features enabled.
android:layout_width="match_parent"
android:layout_height="match_parent"
>
+ <!-- Popout bar for action modes -->
+ <com.android.internal.widget.ActionBarContextView
+ android:id="@+id/action_mode_bar"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:visibility="gone" />
+
<RelativeLayout android:id="@android:id/title_container"
style="?android:attr/windowTitleBackgroundStyle"
android:layout_width="match_parent"
diff --git a/core/res/res/layout/screen_title.xml b/core/res/res/layout/screen_title.xml
index 39ea131..26597af 100644
--- a/core/res/res/layout/screen_title.xml
+++ b/core/res/res/layout/screen_title.xml
@@ -22,6 +22,12 @@ enabled.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
+ <!-- Popout bar for action modes -->
+ <com.android.internal.widget.ActionBarContextView
+ android:id="@+id/action_mode_bar"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:visibility="gone" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="?android:attr/windowTitleSize"
diff --git a/core/res/res/layout/screen_title_icons.xml b/core/res/res/layout/screen_title_icons.xml
index 62a0228..c8cf334 100644
--- a/core/res/res/layout/screen_title_icons.xml
+++ b/core/res/res/layout/screen_title_icons.xml
@@ -23,6 +23,12 @@ This is the basic layout for a screen, with all of its features enabled.
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
+ <!-- Popout bar for action modes -->
+ <com.android.internal.widget.ActionBarContextView
+ android:id="@+id/action_mode_bar"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:visibility="gone" />
<RelativeLayout android:id="@android:id/title_container"
style="?android:attr/windowTitleBackgroundStyle"
android:layout_width="match_parent"
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 4edd964..d1024fe 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -251,6 +251,10 @@
<!-- Reference to a style for the Action Bar -->
<attr name="windowActionBarStyle" format="reference" />
+ <!-- Flag indicating whether action modes should overlay window content
+ when there is not reserved space for their UI (such as an Action Bar). -->
+ <attr name="windowActionModeOverlay" format="boolean" />
+
<!-- Defines the default soft input state that this window would
like when it is displayed. -->
<attr name="windowSoftInputMode">
@@ -444,8 +448,15 @@
<eat-comment />
<!-- Default amount of padding to use between action buttons. -->
<attr name="actionButtonPadding" format="dimension" />
- <attr name="actionBarContextBackground" format="reference" />
- <attr name="actionBarCloseContextDrawable" format="reference" />
+
+ <!-- =================== -->
+ <!-- Action mode styles -->
+ <!-- =================== -->
+ <eat-comment />
+ <!-- Background drawable to use for action mode UI -->
+ <attr name="actionModeBackground" format="reference" />
+ <!-- Drawable to use for the close action mode button -->
+ <attr name="actionModeCloseDrawable" format="reference" />
<!-- =================== -->
<!-- Preference styles -->
@@ -987,6 +998,7 @@
<attr name="backgroundDimAmount" />
<attr name="windowActionBar" />
<attr name="windowActionBarStyle" />
+ <attr name="windowActionModeOverlay" />
</declare-styleable>
<!-- The set of attributes that describe a AlertDialog's theme. -->
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 34dd46c..f1ff3a3 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -1306,8 +1306,9 @@
<public type="attr" name="showAsAction" />
<public type="attr" name="actionButtonPadding" />
<public type="attr" name="previewImage" />
- <public type="attr" name="actionBarContextBackground" />
- <public type="attr" name="actionBarCloseContextDrawable" />
+ <public type="attr" name="actionModeBackground" />
+ <public type="attr" name="actionModeCloseDrawable" />
+ <public type="attr" name="windowActionModeOverlay" />
<public type="id" name="home" />
diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml
index bce0e02..998480d 100644
--- a/core/res/res/values/themes.xml
+++ b/core/res/res/values/themes.xml
@@ -206,8 +206,8 @@
<!-- Action bar styles -->
<item name="actionButtonPadding">12dip</item>
- <item name="actionBarContextBackground">@android:drawable/action_bar_context_background</item>
- <item name="actionBarCloseContextDrawable">@android:drawable/ic_menu_close_clear_cancel</item>
+ <item name="actionModeBackground">@android:drawable/action_bar_context_background</item>
+ <item name="actionModeCloseDrawable">@android:drawable/ic_menu_close_clear_cancel</item>
</style>
<!-- Variant of the default (dark) theme with no title bar -->
diff --git a/core/tests/coretests/src/android/database/DatabaseGeneralTest.java b/core/tests/coretests/src/android/database/DatabaseGeneralTest.java
index e33421a..cd38bf0 100644
--- a/core/tests/coretests/src/android/database/DatabaseGeneralTest.java
+++ b/core/tests/coretests/src/android/database/DatabaseGeneralTest.java
@@ -21,6 +21,7 @@ import static android.database.DatabaseUtils.InsertHelper.TABLE_INFO_PRAGMA_DEFA
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
+import android.database.sqlite.SQLiteException;
import android.os.Handler;
import android.os.Parcel;
import android.test.AndroidTestCase;
@@ -384,54 +385,28 @@ public class DatabaseGeneralTest extends AndroidTestCase implements PerformanceT
@MediumTest
public void testSchemaChange2() throws Exception {
- SQLiteDatabase db1 = mDatabase;
- SQLiteDatabase db2 = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile, null);
- Cursor cursor;
-
- db1.execSQL("CREATE TABLE db1 (_id INTEGER PRIMARY KEY, data TEXT);");
-
- cursor = db1.query("db1", null, null, null, null, null, null);
- assertNotNull("Cursor is null", cursor);
+ mDatabase.execSQL("CREATE TABLE db1 (_id INTEGER PRIMARY KEY, data TEXT);");
+ Cursor cursor = mDatabase.query("db1", null, null, null, null, null, null);
+ assertNotNull(cursor);
assertEquals(0, cursor.getCount());
- cursor.deactivate();
- // this cause exception because we're still using sqlite_prepate16 and not
- // sqlite_prepare16_v2. The v2 variant added the ability to check the
- // schema version and handle the case when the schema has changed
- // Marco Nelissen claim it was 2x slower to compile SQL statements so
- // I reverted back to the v1 variant.
- /* db2.execSQL("CREATE TABLE db2 (_id INTEGER PRIMARY KEY, data TEXT);");
-
- cursor = db1.query("db1", null, null, null, null, null, null);
- assertNotNull("Cursor is null", cursor);
- assertEquals(0, cursor.count());
- cursor.deactivate();
- */
+ cursor.close();
}
@MediumTest
public void testSchemaChange3() throws Exception {
- SQLiteDatabase db1 = mDatabase;
- SQLiteDatabase db2 = SQLiteDatabase.openOrCreateDatabase(mDatabaseFile, null);
- Cursor cursor;
-
-
- db1.execSQL("CREATE TABLE db1 (_id INTEGER PRIMARY KEY, data TEXT);");
- db1.execSQL("INSERT INTO db1 (data) VALUES ('test');");
-
- cursor = db1.query("db1", null, null, null, null, null, null);
- // this cause exception because we're still using sqlite_prepate16 and not
- // sqlite_prepare16_v2. The v2 variant added the ability to check the
- // schema version and handle the case when the schema has changed
- // Marco Nelissen claim it was 2x slower to compile SQL statements so
- // I reverted back to the v1 variant.
- /* db2.execSQL("CREATE TABLE db2 (_id INTEGER PRIMARY KEY, data TEXT);");
-
- assertNotNull("Cursor is null", cursor);
- assertEquals(1, cursor.count());
- assertTrue(cursor.first());
- assertEquals("test", cursor.getString(cursor.getColumnIndexOrThrow("data")));
- cursor.deactivate();
- */
+ mDatabase.execSQL("CREATE TABLE db1 (_id INTEGER PRIMARY KEY, data TEXT);");
+ mDatabase.execSQL("INSERT INTO db1 (data) VALUES ('test');");
+ mDatabase.execSQL("ALTER TABLE db1 ADD COLUMN blah int;");
+ Cursor c = null;
+ try {
+ c = mDatabase.rawQuery("select blah from db1", null);
+ } catch (SQLiteException e) {
+ fail("unexpected exception: " + e.getMessage());
+ } finally {
+ if (c != null) {
+ c.close();
+ }
+ }
}
private class ChangeObserver extends ContentObserver {
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index 19f0f1d..d0318cf 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -371,6 +371,9 @@
<span class="zh-CN" style="display:none">应用程序版本控制</span>
<span class="zh-TW" style="display:none">應用程式版本設定</span>
</a></li>
+ <li><a href="<?cs var:toroot ?>guide/publishing/licensing.html">
+ <span class="en">Licensing Your Applications</span>
+ </a> <span class="new">new!</span></li>
<li><a href="<?cs var:toroot ?>guide/publishing/preparing.html">
<span class="en">Preparing to Publish</span>
<span class="de" style="display:none">Vorbereitung auf die Veröffentlichung</span>
diff --git a/docs/html/guide/publishing/licensing.jd b/docs/html/guide/publishing/licensing.jd
new file mode 100644
index 0000000..e3b9135
--- /dev/null
+++ b/docs/html/guide/publishing/licensing.jd
@@ -0,0 +1,2373 @@
+page.title=Licensing Your Applications
+@jd:body
+
+<div id="qv-wrapper">
+<div id="qv">
+
+ <h2>Market Licensing quickview: </h2>
+ <ul>
+ <li>Licensing lets you protect your application on any device that includes Android Market.</li>
+ <li>Your app maintains control of how it enforces its licensing status. </li>
+ <li>Adding licensing to an app is straightforward, using the library available through the SDK.</li>
+ <li>The service is free and is available to all developers who publish on Android Market. </li>
+ </ul>
+
+ <h2>In this document</h2>
+ <ol>
+ <li><a href="#account">Setting Up A Publisher Account</a></li>
+ <li><a href="#dev-setup">Setting Up the Development Environment</a></li>
+ <li><a href="#app-integration">Integrating the LVL with Your Application</a>
+ <ol>
+ <li><a href="#add-library">Including the LVL</a></li>
+ <li><a href="#manifest-permission">Adding the licensing permission</a></li>
+ <li><a href="#impl-Policy">Implementing a Policy</a></li>
+ <li><a href="#impl-Obfuscator">Implementing an Obfuscator</a></li>
+ <li><a href="#impl-lc">Checking the license</a></li>
+ <li><a href="#impl-DeviceLimiter">Implementing a DeviceLimiter</a></li>
+ </ol></li>
+ <li><a href="#test-env">Setting Up the Test Environment</a>
+ <ol>
+ <li><a href="#test-response">Test responses</a></li>
+ <li><a href="#test-acct-setup">Test accounts</a></li>
+ <li><a href="#acct-signin">Signing in on a device or emulator</a></li>
+ </ol></li>
+ <li><a href="#app-obfuscation">Obfuscating Your Application</a></li>
+ <li><a href="#app-publishing">Publishing a Licensed Application</a></li>
+ <li><a href="#support">Where to Get Support</a></li>
+ </ol>
+
+ <h2>Appendix</h2>
+ <ol>
+ <li><a href="#lvl-summary">Summary of LVL Classes and Interfaces</a></li>
+ <li><a href="#server-response-codes">Server Response Codes</a></li>
+ <li><a href="#extras">Server Response Extras</a></li>
+ </ol>
+
+</div>
+</div>
+
+<p>Android Market offers a licensing service that lets you enforce licensing
+policies for paid applications that you publish through Android Market. With
+Android Market Licensing, your applications can query Android Market at run time to
+obtain their licensing status for the current user, then allow or disallow
+further use as appropriate. </p>
+
+<p>Using the service, you can apply a flexible licensing policy on an
+application-by-application basis &mdash; each application can enforce licensing
+in the way most appropriate for it. If necessary, an application can apply custom
+constraints based on the licensing status obtained from Android Market.
+For example, an application can check the licensing status and then apply custom
+constraints that allow the user to run it unlicensed for a specific number
+of times, or for a specific validity period. An application can also restrict use of the
+application to a specific device, in addition to any other constraints. </p>
+
+<p>The licensing service is a secure means of controlling access to your
+applications. When an application checks the licensing status, the Market server
+signs the licensing status response using a key pair that is uniquely associated
+with the publisher account. Your application stores the public key in its
+compiled <code>.apk</code> file and uses it to verify the licensing status
+response.</p>
+
+<p>Any application that you publish through Android Market can use the Android
+Market Licensing service. No special account or registration is needed.
+Additionally, because the service uses no dedicated framework APIs, you can add
+licensing to any legacy application that uses a minimum API level of 3 or
+higher.</p>
+
+<p>To help you add licensing to your application, the Android SDK provides
+library sources that you can include in your application project. The
+License Verification Library (LVL) handles all of
+the licensing-related communication with the Android Market client and the
+licensing service. With the LVL integrated, your application can determine its
+licensing status for the current user by simply calling a library checker method
+and implementing a callback that receives the status.</p>
+
+<p>This document explains how the licensing service works and how to add it to
+your application. </p>
+
+
+<h2 id="overview">Overview</h2>
+
+<p>Android Market Licensing is a network-based service that lets an application
+on an Android-powered device query a trusted licensing server, to determine
+whether the application is licensed to the current device user. After receiving
+the server response, the application can then allow or disallow further use of
+the application as needed. In the service, the role of the licensing server is
+to provide the license status for the current user; the application itself is
+responsible for querying the server and conditionally granting access to the
+application. </p>
+
+<h4>Application, Android Market client, and server</h4>
+
+<p>The licensing service is based on the capability of the Android Market server
+to determine whether a given user is licensed to use a given application. The
+server considers a user licensed if the user is recorded to have purchased the
+application, or if the application is available for free. To properly identify
+the user and determine the license status, the server requires information about
+the application and user &mdash; the application and the Android Market client
+work together to assemble the information and pass it to the server. </p>
+
+<p>In the licensing service, an application does not query the licensing server
+directly, but instead calls the Android Market client over remote IPC to
+initiate a license request. In the license request:</p>
+
+<ul>
+<li>The application provides its package name and a nonce that is later used to
+validate any response from the server, as well as a callback over which the
+response can be returned asynchronously.</li>
+<li>The Android Market client, which has greater permissions than the
+application, collects the necessary information about the user and the device,
+such as the device's primary Google account username, IMSI, and other
+information. It then sends the license check request to the server on behalf of
+the application.</li>
+<li>The server evaluates the request using all available information, attempting
+to establish the user's identity to a sufficient level of confidence. The server
+then checks the user identity against purchase records for the application and
+returns a license response, which the Android Market client returns to the
+application over the IPC callback.</li>
+</ul>
+
+<p>Notice that during a license check, the application does not manage any
+network connections or use any licensing related APIs in the Android platform.
+</p>
+
+<div class="figure" style="width:469px">
+<img src="{@docRoot}images/licensing_arch.png" alt=""/>
+<p class="img-caption"><strong>Figure 1.</strong> Your application initiates a
+license check through the LVL and the Android Market
+client, which handles communication with the Market server.</p>
+</div>
+
+<h4>License responses secured through public key cryptography</h4>
+
+<p>To ensure the integrity of each license query, the server signs the license
+response data using an RSA key pair that is shared exclusively between the
+server and the application publisher.</p>
+
+<p>The licensing service generates a single licensing key pair for each
+publisher account and exposes the public key in the account's profile page. The
+publisher copies the public key and embeds it in the application source code,
+then compiles and publishes the <code>.apk.</code> The server retains the
+private key internally and uses it to sign license responses for applications
+published on that account. </p>
+
+<p>When the application receives a signed response, it uses the embedded public
+key to verify the data. The use of public key cryptography in the licensing
+service makes it possible for the application to detect responses that have been
+tampered with or are spoofed.</p>
+
+<h4>Use of licensing in your application</h4>
+
+<p>To use licensing in your application, add code to the application to
+initiate a license check request and handle the response when it is received.
+You can choose when, and how often, you want your application to check its
+license and you have full control over how it handles the response, verifies the
+signed response data, and enforces access controls. </p>
+
+<p>To simplify the process of adding support for licensing, download and
+integrate the Licensing Verification Library, described below. Integration is
+straightforward.</p>
+
+<p>When you are finished integrating the LVL, use a test environment
+provided by the publisher site to test your application's handling of server
+responses. </p>
+
+<p>Finally, publish the application <code>.apk</code> on Market using the
+normal process. If you previously used the copy-protection provided by Android
+Market, you can remove it from applications that use licensing. </p>
+
+<h4>Licensing Verification Library simplifies implementation</h4>
+
+<p>The Android SDK includes a License Verification Library (LVL) that you can
+download and use as the basis for your application's licensing implementation.
+The LVL greatly simplifies the process of adding licensing to your application
+and helps ensure a more secure, robust implementation for your application. The
+LVL provides internal classes that handle most of the standard operations of a
+license query, such as contacting Android Market to initiate a license request
+and decrypting and validating the responses. It also exposes key interfaces that
+let you easily plug in your custom code for defining licensing policy and
+managing access as needed by your application. The key LVL interfaces are: </p>
+
+<ul>
+<li>Policy &mdash; your implementation determines whether to allow access to the
+application, based on the license response received from the server and any
+other data available (such as from a backend server associated with your
+application). The implementation can evaluate the various fields of the license
+response and apply other constraints, if needed. The implementation also lets
+you manage the handling of license checks that result in errors, such as network
+errors.</li>
+<li>LicenseCheckerCallback &mdash; your implementation manages access to the
+application, based on the result of the Policy's handling of the license
+response. Your implementation can manage access in any way needed, including
+displaying the license result in the UI or directing the user to purchase the
+application (if not currently licensed). </li>
+</ul>
+
+<p>To help you get started with a Policy, the LVL provides two fully complete
+Policy implementations that you can use without modification or adapt to your
+needs:</p>
+
+<ul>
+<li><a href="#ServerManagedPolicy">ServerManagedPolicy</a> is a flexible Policy
+that uses settings provided by the licensing server to manage response caching
+and access to the application while the device is offline (such as when the
+user is on on an airplane). For most applications, the use of
+ServerManagedPolicy is highly recommended. </li>
+<li><a href="#StrictPolicy">StrictPolicy</a> is a restrictive Policy that
+does not cache any response data and allows the application access <em>only</em>
+when the server returns a licensed response.</li>
+</ul>
+
+<p>The LVL is available as a downloadable component of the Android SDK. The
+component includes both the LVL itself and an example application that shows how
+the library should be integrated with your application and how your application
+should manage response data, UI interaction, and error conditions. </p>
+
+<p>The LVL sources are provided as an Android <em>library project</em>, which
+means that you can maintain a single set of library sources and share them
+across multiple applications. A full test environment is also available through
+the SDK, so you can develop and test the licensing implementation in your
+applications before publishing them, even if you don't have access to a
+physical device.</p>
+
+<h4>Requirements and limitations</h4>
+
+<p>Android Market Licensing is designed to let you apply license controls to
+applications that you publish through Android Market and that users download
+from Market. The service is not designed to let you control access to
+applications that are not published through Android Market or that are run
+on devices that do not offer the Android Market client. </p>
+
+<p>Here are some points to keep in mind as you implement licensing in your
+application: </p>
+
+<ul>
+<li>Only paid applications published through Market can use the
+service. </li>
+<li>An application can use the service only if the Android Market client is
+installed on its host device and the device is running Android 1.5 (API level 3)
+or higher.</li>
+<li>To complete a license check, the licensing server must be accessible over
+the network. You can implement license caching behaviors to manage access when
+there is no network connectivity. </li>
+<li>The security of your application's licensing controls ultimately relies on
+the design of your implementation itself. The service provides the building
+blocks that let you securely check licensing, but the actual enforcement and
+handling of the license are factors in your control. By following the best
+practices in this document, you can help ensure that your implementation will be
+secure.</li>
+<li>Adding licensing to an application does not affect the way the application
+functions when run on a device that does not offer Android Market.</li>
+<li>Licensing is currently for paid apps only, since free apps are considered
+licensed for all users. If your application is already published as free,
+you won't be able to upload a new version that uses licensing.</li>
+</ul>
+
+<h4>Replacement for copy protection</h4>
+
+<p>Android Market Licensing is a flexible, secure mechanism for controlling
+access to your applications. It effectively replaces the copy-protection
+mechanism and gives you wider distribution potential for your applications. </p>
+
+<ul>
+<li>A limitation of copy protection is that applications using it can be
+installed only on compatible devices that provide a secure internal storage
+environment. For example, a copy-protected application cannot be downloaded
+from Market to a device that provides root access, and the application
+cannot be installed to a device's SD card. </li>
+<li>With Android Market licensing, you can move to a license-based model in
+which access is not bound to the characteristics of the host device, but to your
+publisher account on Android Market and the licensing policy that you define.
+Your application can be installed and controlled on any compatible device on
+any storage, including SD card.</li>
+</ul>
+
+<p>Although no license mechanism can completely prevent all unauthorized use,
+the licensing service lets you control access for most types of normal usage,
+across all compatible devices, locked or unlocked, that run Android 1.5 or
+higher version of the platform.</p>
+
+<p>The sections below describe how to add Android Market licensing to your
+applications. </p>
+
+<h2 id="account">Setting Up a Publisher Account</h2>
+
+<p>Android Market licensing lets you manage access to applications that
+users have downloaded from Android Market. To use licensing in an application,
+you need to have a publisher account on Android Market so that you can
+publish the application to users. </p>
+
+<p>If you don't already have a publisher account, you need to register for one
+using your Google account and agree to the terms of service. Once you are
+registered, you can upload applications at your convenience and begin debugging
+and testing your licensing implementation. For more information about publishing
+on Android Market, see <a
+href="{@docRoot}guide/publishing/publishing.html">Publishing Your
+Applications</a></p>
+
+<p>To register as an Android Market developer and set up your publisher account,
+visit the Android Market publisher site:</p>
+
+<p style="margin-left:2em;"><a
+href="http://market.android.com/publish">http://market.android.com/publish</a>
+</p>
+
+<p>If you already have a publisher account on Android Market, use your existing
+account to set up licensing. You <em>do not</em> need to register for a new
+account to support licensing (and doing so is not recommended, especially if you
+are adding licensing support to applications that you have already published).
+In all cases, if you have published applications, you manage licensing for those
+applications through the account on which the applications are published. </p>
+
+<p>Once your publisher account is set up, use the account to:</p>
+
+<ul>
+<li>Obtain a public key for licensing</li>
+<li>Debug and test an application's licensing implementation, prior to
+publishing the application</li>
+<li>Publish the applications to which you have added licensing support</li>
+</ul>
+
+<h4>Administrative settings for licensing</h4>
+
+<p>Once you are signed into your publisher account, you can manage several
+administrative controls for Android Market licensing. The controls are available
+in the Edit Profile page, in the "Licensing" panel, shown below. The controls
+let you: </p>
+
+<ul>
+<li>Set up multiple "test accounts", identified by email address. The licensing
+server allows users signed into test accounts on a device or emulator to send
+license checks and receive static test reponses.</li>
+<li>Obtain the account's public key for licensing. When you are implementing
+licensing in an application, you must copy the public key string into the
+application.</li>
+<li>Configure static test responses that the server sends, when it receives a
+license check for an application uploaded to the publisher account, from a user
+signed in to the publisher account or a test account.</li>
+</ul>
+
+<div style="margin-bottom:2em;">
+
+<img src="{@docRoot}images/licensing_public_key.png" style="text-align:left;margin-bottom:0;" />
+<div style="margin:0 2em;padding:0"><strong>Figure 2.</strong> The Licensing
+panel of your account's Edit Profile page lets you manage administrative
+settings for licensing.</div>
+</div>
+
+<p>For more information about how to work with test accounts and static test
+responses, see <a href="#test-env">Setting Up a Testing Environment</a>, below.
+
+<h2 id="dev-setup">Setting Up the Development Environment</h2>
+
+<p>Once you've set up your publisher account on Android Market, the next step is
+to set up your development environment for licensing. </p>
+
+<p>Setting up your environment for licensing involves these tasks:</p>
+
+<ol>
+<li><a href="#download-sdk">Downloading the latest SDK</a>, if you haven't already done so </li>
+<li><a href="#runtime-setup">Setting up the runtime environment</a> for development</a></li>
+<li><a href="#download-lvl">Downloading the Market Licensing component</a> into your SDK </li>
+<li><a href="#lvl-setup">Setting up the Licensing Verification Library</a></li>
+<li><a href="#add-library">Including the LVL library project in your application</a></li>
+</ol>
+
+<p>The sections below describe these tasks. When you are done with setup,
+you can begin <a href="#app-integration">integrating the LVL into your applications</a>.</p>
+
+<p>To get started, you need to set up a proper runtime environment on which
+you can run, debug and test your application's implementation of license
+checking and enforcement. </p>
+
+
+<h3 id="download-sdk">Downloading the latest SDK</h3>
+
+<div class="sidebox-wrapper">
+<div class="sidebox">
+<h2>Licensing sample application</h2>
+
+<p>To work with Android Market licensing, you need a functioning Android
+application to which you can add licensing support. </p>
+
+<p style="margin-top:.5em;">If you are new to Android
+and don't yet have a functioning application, the LVL component includes a sample
+application that you can set up as a new application project. The sample provides
+a complete, working example of how licensing works. For more information, see <a
+href="#download-lvl">Downloading the LVL</a>.</p>
+
+</div>
+</div>
+
+<p>If you haven't done so, you need to download the Android SDK before you can
+develop Android applications. The SDK provides the tools that you need to build
+and debug Android applications, including applications that use Android Market
+licensing. For complete information, including installation intructions, see
+the <a href="{@docRoot}sdk/index.html">Android SDK</a>. </p>
+
+<p>If you have already installed the SDK, make sure to update the
+SDK tools and ADT Plugin to the latest versions. You can update the SDK tools
+using the Android SDK and AVD Manager and ADT through <strong>Help</strong> &gt;
+<strong>Software Updates...</strong> in Eclipse. </p>
+
+<p>After you've installed the latest SDK and tools, set up your development
+environment as described below. </p>
+
+
+<h3 id="runtime-setup">Setting up the runtime environment</h3>
+
+<p>As described earlier, applications check licensing status not by contacting
+the licensing server directly, but by binding to a service provided by the
+Android Market application and initiating a license check request. The Android
+Market service then handles the direct communication with the licensing server
+and finally routes the response back to your application. To debug and test
+licensing in your application, you need to set up a runtime environment that
+includes the necessary Android Market service, so that your application is able
+to send license check requests to the licensing server. </p>
+
+<p>There are two types of runtime environment that you can use: </p>
+
+<ul>
+<li>An Android-powered device that includes the Android Market application, or</li>
+<li>An Android emulator running the Google APIs Add-on, API level 8 (release 2)
+or higher</li>
+</ul>
+
+<p>The sections below provide more information. </p>
+
+<h4 id="runtime-device">Running on a device</h4>
+
+<p>You can use an Android-powered device as the runtime environment for
+debugging and testing licensing on your application.</p>
+
+<p>The device you use must:</p>
+
+<ul>
+<li>Run a standard version of the Android 1.5 or later (API level
+3 or higher) platform, <em>and</em> </li>
+<li>Run a system image on which the Android Market client application
+is preinstalled. </li>
+</ul>
+
+<p>If Android Market is not preinstalled in the system image, your application won't
+be able to communicate with the Android Market licensing server. </p>
+
+<p>For general information about how to set up a device for use in developing
+Android applications, see <a
+href="{@docRoot}guide/developing/device.html">Developing on a Device</a>.</p>
+
+<h4 id="runtime-emulator">Running on an Android emulator</h4>
+
+<p>You can also use an Android emulator as your runtime
+environment for debugging and testing licensing.</p>
+
+<p>Because the standard Android platforms provided in the Android SDK <em>do
+not</em> include Android Market, you need to download the Google APIs Add-On
+platform, API Level 8 (or higher), from the SDK repository. After downloading
+the add-on, you need to create an AVD configuration that uses that system image.
+</p>
+
+<p>The Google APIs Add-On does not include the full Android Market client.
+However, it does provide: </p>
+
+<ul>
+<li>An Android Market background service that implements the
+<code>ILicensingService</code> remote interface, so that your application can
+send license checks over the network to the licensing server. </li>
+<li>A set of underlying account services that let you add an a Google account on
+the AVD and sign in using your publisher account or test account credentials.
+Signing in using your publisher or test account enables you to debug and test
+your application without having publish it. For more information see <a
+href="#acct-signin">Signing in to an authorized account</a>, below.</li>
+</ul>
+
+<p>Several versions of the add-on are available in the SDK repository, but only
+<strong>Google APIs Add-On, API 8 (release 2) or higher</strong> version of the
+add-on includes the necessary Android Market services. This means that you
+cannot use Google APIs Add-On API 7 or lower as a runtime environment for
+developing licensing on an emulator.</p>
+
+<div style="margin-bottom:2em;">
+
+<img src="{@docRoot}images/licensing_gapis_8.png" style="text-align:left;margin-bottom:0;" />
+<div style="margin:0 2em;padding:0"><strong>Figure 3.</strong> Google APIs
+Add-On, API 8 (release 2) or higher lets you debug and test your licensing
+implemention in an emulator.</div>
+</div>
+
+<p>To set up an emulator for adding licensing to an application, follow
+these steps: </p>
+
+<ol>
+ <li>Launch the Android SDK and AVD Manager. </li>
+ <li>In the <strong>Available Packages</strong> panel, select and download the
+SDK component "Google APIs (Google Inc.) - API Level 8" (or higher) from the SDK
+repository, as shown in the figure above.
+ <p>When the download is complete, use the Android SDK and AVD Manager to
+create a new AVD based on that component, described next.</p></li>
+ <li>In the <strong>Virtual
+Devices</strong> panel of the Android SDK and AVD Manager, click
+<strong>New</strong> and set the configuration details for the new AVD. </li>
+ <li>In the dialog that appears, assign a descriptive name to the AVD and then
+use the "Target" menu to choose the "Google APIs (Google Inc.) - API Level 8" as
+the system image to run on the new AVD. Set the other configuration details as
+needed and then click <strong>Create AVD</strong> to finish. The SDK tools
+create the new AVD configuration, which then appears in the list of available
+Android Virtual Devices.</li>
+</ol>
+
+<p>If you are not familiar with AVDs or how to use them, see <a
+href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</p>
+
+<h4 id="project-update">Updating your project configuration</h4>
+
+<p>After you set up a runtime environment that meets the requirements described
+above &mdash; either on an actual device or on an emulator &mdash; make sure to
+update your application project or build scripts as needed, so that your compiled
+<code>.apk</code> files that use licensing are deployed into that environment.
+In particular, if you are developing in Eclipse, make sure that you set up a
+Run/Debug Configuration that targets the appropriate device or AVD. </p>
+
+<p>You do not need to make any changes to your application's
+build configuration, provided that the project is already configured to compile
+against a standard Android 1.5 (API level 3) or higher library. For example:
+
+<ul>
+<li>If you have an existing application that is compiled against
+the Android 1.5 library, you do not need to make any changes to your
+build configuration to support licensing. The build target meets the minimum
+requirements for licensing, so you would continue building
+against the same version of the Android platform.</li>
+
+<li>Similarly, if you are building against Android 1.5 (API level 3) but
+are using an emulator running the Google APIs Add-On API 8 as the application's
+runtime environment, there is no need to change your application's build
+configuration. </li>
+</ul>
+
+<p>In general, adding licensing to an application should have no impact
+whatsoever on the application's build configuration.</p>
+
+
+<h3 id="download-lvl">Downloading the LVL</h3>
+
+<p>The License Verification Library (LVL) is a collection of helper classes that
+greatly simplify the work that you need to do to add licensing to your
+application. In all cases, we recommend that you download the LVL and use it as
+the basis for the licensing implementation in your application.</p>
+
+<p>The LVL is available as a downloadable component of the Android SDK. The
+component includes: </p>
+
+<ul>
+<li>The LVL sources, stored inside an Android library project. </li>
+<li>An example application called "sample" that depends on the LVL library
+project. The example illustrates how an application uses the library helper
+classes to check and enforce licensing.</li>
+</ul>
+
+<p>To download the LVL component into your development environment, use the
+Android SDK and AVD Manager. Launch the Android SDK and AVD Manager and then
+select the "Market Licensing" component, as shown in the figure below.
+Accept the terms and click <strong>Install Selected</strong> to begin the download. </p>
+
+<div style="margin-bottom:2em;">
+
+<img src="{@docRoot}images/licensing_package.png" style="text-align:left;margin-bottom:0;" />
+<div style="margin:0 2em;padding:0"><strong>Figure 4.</strong> The Market
+Licensing package contains the LVL and the LVL sample application. </div>
+</div>
+
+<p>When the download is complete, the Android SDK and AVD Manager installs both
+the LVL library project and the example application into these directories: </p>
+
+<p style="margin-left:2em"><code>&lt;<em>sdk</em>&gt;/marketlicensing/library/</code>
+&nbsp;&nbsp;(the LVL library project)<br />
+<code>&lt;<em>sdk</em>&gt;/marketlicensing/sample/</code>&nbsp;&nbsp;(the example
+application)</p>
+
+<p>If you aren't familiar with how to download components into your SDK, see the
+<a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>
+document. </p>
+
+
+<h3 id="lvl-setup">Setting Up the Licensing Verification Library</h3>
+
+<p>After downloading the LVL to your computer, you need to set it up in your
+development environment, either as an Android library project or by
+copying (or importing) the library sources directly into your existing
+application package. In general, using the LVL as a library project is recommended,
+since it lets you reuse your licensing code across multiple applications and
+maintain it more easily over time. Note that the LVL is not designed to be
+compiled separately and added to an application as a static .jar file. </p>
+
+<h4>Moving the library sources out location</h4>
+
+<p>Because you will be customizing the LVL sources to some extent, you should
+make sure to <em>move or copy</em> the library sources (the entire
+directory at <code>&lt;<em>sdk</em>&gt;/marketlicensing/library/</code>)
+to a working directory outside of the SDK. You can then add the sources
+in the working location to your source-code management system, rather
+than those in the SDK.</p>
+
+<p>Moving the library sources is important is because, when you later update the
+Market licensing package, the SDK installs the new files to the same location as
+the older files. Moving your working library files to a safe location ensures
+that they won't be inadvertently overwritten when you download a new version of
+the LVL.</p>
+
+<h4>Creating the LVL as a library project</h4>
+
+<div class="sidebox-wrapper">
+<div class="sidebox">
+<h2>Working with library projects</h2>
+
+<p>The LVL is provided as an Android library project, which means that you can
+share its code and resources across multiple applications. </p>
+
+<p style="margin-top:.5em;">If you aren't familiar with library projects or how
+to use them, read more in <a
+href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing in
+Eclipse with ADT</a> or <a
+href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in
+Other IDEs</a>, as appropriate for your environment.</p>
+
+</div>
+</div>
+
+<p>The recommended way of using the LVL is setting it up as a new Android
+<em>library project</em>. A library project is a type of development project
+that holds shared Android source code and resources. Other Android application
+projects can reference the library project and, at build time, include its
+compiled sources in their <code>.apk</code> files. In the context of licensing, this means
+that you can do most of your licensing development once, in a library project,
+then include the library sources in your various application projects. In this
+way, you can easily maintain a uniform implementation of licensing across all of
+your projects and maintain it centrally. </p>
+
+<p>The LVL is provided as a configured library project &mdash; once you have
+downloaded it, you can start using it right away. </p>
+
+<p>If you are working in Eclipse with ADT, you need to add the LVL to your
+workspace as a new development project, in the same way as you would a new
+application project. </p>
+
+<ol>
+<li>Use the New Project Wizard to create a new
+project from existing sources. Select the LVL's <code>library</code> directory
+(the directory containing the library's AndroidManifest.xml file) as the project
+root.</li>
+<li>When you are creating the library project, you can select any application
+name, package, and set other fields as needed. </li>
+<li>For the library's build target, select Android 1.5 (API level 3) or higher.</li>
+</ol>
+
+<p> When created, the project is
+predefined as a library project in its <code>default.properties</code> file, so
+no further configuration is needed. </p>
+
+<p>For more information about how to create an application project or work with
+library projects in Eclipse, see <a
+href="{@docRoot}guide/developing/eclipse-adt.html#CreatingAProject">Developing
+in Eclipse with ADT</a>.</p>
+
+<h4>Copying the LVL sources to your application</h4>
+
+<p>As an alternative to adding the LVL as a library project, you can copy the
+library sources directly into your application. To do so, copy (or import) the
+directory
+<code>&lt;<em>sdk</em>&gt;/extras/marketlicensing/library/src/com</code> into
+your application's <code>src/</code> directory.</p>
+
+<p>If you add the LVL sources directly to your application, you can skip the
+next section and start working with the library, as described in <a
+href="#app-integration"></a>.</p>
+
+
+<h3 id="add-library">Including the LVL library project sources in your
+application</h3>
+
+<p>If you want to use the LVL sources as a library project, you need to add a
+reference to the LVL library project in your project properties. This tells
+build tools to include the LVL library project sources in your application at
+compile time. The process for adding a reference to a library project varies,
+based on your development environment, as described below.</p>
+
+<p> If you are developing in Eclipse with ADT, you should already have added the
+library project to your workspace, as described in the previous section. If you
+haven't done that already, do it now before continuing. </p>
+
+<p>Next, open the application's project properties window, as shown below.
+Select the "Android" properties group and click <strong>Add</strong>, then
+choose the LVL library project (com_android_vending_licensing) and click
+<strong>OK</strong>. For more information, see
+<a href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing
+in Eclipse with ADT</a></p>
+
+<div style="margin-bottom:2em;">
+
+<img src="{@docRoot}images/licensing_add_library.png" style="text-align:left;margin-bottom:0;" />
+<div style="margin:0 2em;padding:0"><strong>Figure 5.</strong> If you are
+working in Eclipse with ADT, you can add the LVL library project to your
+application from the application's project properties.</div>
+</div>
+
+<p>If you are developing using the SDK command-line tools, navigate to the
+directory containing your application project and open the
+<code>default.properties</code> file. Add a line to the file that specifies the
+<code>android.library.reference.&lt;n&gt;</code> key and the path to the
+library. For example: </p>
+
+<pre>android.library.reference.1=path/to/library_project</pre>
+
+<p>Alternatively, you can use this command to update the project
+properties, including the reference to the library project:</p>
+
+<pre class="no-pretty-print" style="color:black">android update lib-project
+--target <em>&lt;target_ID&gt;</em> \
+--path <em>path/to/my/app_project</em> \
+--library <em>path/to/my/library_project</em>
+</pre>
+
+<p>For more information about working with library projects, see <a
+href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing
+in Eclipse with ADT</a> or <a
+href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in
+Other IDEs</a>, as appropriate for your environment.</p>
+
+
+<h2 id="app-integration">Integrating the LVL with Your Application</h2>
+
+<p>Once you've followed the steps above to set up a publisher account and
+development environment, you are ready to begin integrating the LVL with your
+application. </p>
+
+<p>Integrating the LVL with your application code involves these tasks:</p>
+
+<ol>
+<li><a href="#manifest-permission">Adding the licensing permission</a> your application's manifest.</li>
+<li><a href="#impl-Policy">Implementing a Policy</a> &mdash; you can choose one of the full implementations provided in the LVL or create your own.</li>
+<li><a href="#impl-Obfuscator">Implementing an Obfuscator</a>, if your Policy will cache any license response data. </li>
+<li><a href="#impl-lc">Adding code to check the license</a> in your application's main Activity</li>
+<li><a href="#impl-DeviceLimiter">Implementing a DeviceLimiter</a> (optional and not recommended for most applications)</li>
+</ol>
+
+<p>The sections below describe these tasks. When you are done with the
+integration, you should be able to compile your application successfully and you
+can begin testing, as described in <a href="#test-env">Setting Up the Test
+Environment</a>.</p>
+
+<p>For an overview of the full set of source files included in the LVL, see <a
+href="#lvl-summary">Summary of LVL Classes and Interfaces</a>.</p>
+
+
+<h3 id="manifest-permission">Adding the licensing permission to your
+AndroidManifest.xml</h3>
+
+<p>To use the Android Market application for sending a license check to the
+server, your application must request the proper permission,
+<code>com.android.vending.CHECK_LICENSE</code>. If your application does
+not declare the licensing permission but attempts to initiate a license check,
+the LVL throws a security exception.</p>
+
+<p>To request the licensing permission in your application, declare a <a
+href="{@docRoot}guide/topics/manifest/uses-permission-element.html"><code>&lt;uses-permission&gt;</code></a>
+element as a child of <code>&lt;manifest&gt;</code>, as follows: </p>
+
+<p style="margin-left:2em;"><code>&lt;uses-permission
+android:name="com.android.vending.CHECK_LICENSE"&gt;</code></p>
+
+<p>For example, here's how the LVL sample application declares the permission:
+</p>
+
+<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
+
+&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" ..."&gt;
+ ...
+ &lt;!-- Devices &gt;= 3 have version of Android Market that supports licensing. --&gt;
+ &lt;uses-sdk android:minSdkVersion="3" /&gt;
+ &lt;!-- Required permission to check licensing. --&gt;
+ &lt;uses-permission android:name="com.android.vending.CHECK_LICENSE" /&gt;
+ ...
+&lt;/manifest&gt;
+</pre>
+
+<p class="note"><strong>Note:</strong> Currently, you cannot declare the
+<code>CHECK_LICENSE</code> permission in the LVL's manifest, because the SDK
+Tools will not merge it into the manifests of dependent applications. Instead,
+you must declare the permission in the manifest of each dependent application.
+</p>
+
+
+<h3 id="impl-Policy">Implementing a Policy</h3>
+
+<div class="sidebox-wrapper">
+<div class="sidebox">
+<h2>ServerManagedPolicy</h2>
+
+<p>The LVL includes a complete Policy implementation called ServerManagedPolicy
+that makes use of license-management settings provided by the Android Market
+server. </p>
+
+<p style="margin-top:.5em;">Use of ServerManagedPolicy as the basis for your
+Policy is strongly recommended. For more information, see <a
+href="#ServerManagedPolicy">ServerManagedPolicy</a> section, below.</p>
+
+</div>
+</div>
+
+<p>Android Market licensing service does not itself determine whether a
+given user with a given license should be granted access to your application.
+Rather, that responsibility is left to a Policy implementation that you provide
+in your application.</p>
+
+<p>Policy is an interface declared by the LVL that is designed to hold your
+application's logic for allowing or disallowing user access, based on the result
+of a license check. To use the LVL, your application <em>must</em> provide an
+implementation of Policy. </p>
+
+<p>The Policy interface declares two methods, <code>allowAccess()</code> and
+<code>processServerResponse()</code>, which are called by a LicenseChecker
+instance when processing a response from the license server. It also declares an
+enum called <code>LicenseResponse</code>, which specifies the license response
+value passed in calls to <code>processServerResponse()</code>. </p>
+
+<ul>
+<li><code>processServerResponse()</code> lets you preprocess the raw response
+data received from the licensing server, prior to determining whether to grant
+access.
+
+<p>A typical implementation would extract some or all fields from the license
+response and store the data locally to a persistent store, such as through
+{@link android.content.SharedPreferences} storage, to ensure that the data is
+accessible across application invocations and device power cycles. For example,
+a Policy would maintain the timestamp of last successful license check, the
+retry count, the license validity period, and similar information in a
+persistent store, rather than resetting the values each time the application is
+launched.</p>
+
+<p>When storing response data locally, the Policy must ensure that the data is
+obfuscated (see <a href="#impl-Obfuscator">Implementing an Obfuscator</a>,
+below).</p></li>
+
+<li><code>allowAccess()</code> determines whether to grant the user access to
+your application, based on any available license response data (from the
+licensing server or from cache) or other application-specific information. For
+example, your implementation of <code>allowAccess()</code> could take into
+account additional criteria, such as usage or other data retrieved from a
+backend server. In all cases, an implementation of <code>allowAccess()</code>
+should only return <code>true</code> if there user is licensed to use the
+application, as determined by the licensing server, or if there is a transient
+network or system problem that prevents the license check from completing. In
+such cases, your implementation can maintain a count of retry responses and
+provisionally allow access until the next license check is complete.</li>
+
+</ul>
+
+<p>To simplify the process of adding licensing to your application and to
+provide an illustration of how a Policy should be designed, the LVL includes
+two full Policy implementations that you can use without modification:</p>
+
+<ul>
+<li><a href="#ServerManagedPolicy">ServerManagedPolicy</a>, a flexible Policy
+that uses server-provided settings and cached responses to manage access across
+varied network conditions, and</li>
+<li><a href="#StrictPolicy">StrictPolicy</a>, which does not cache any response
+data and allows access <em>only</em> if the server returns a licensed
+response.</li>
+</ul>
+
+<p>For most applications, the use of ServerManagedPolicy is highly
+recommended. ServerManagedPolicy is the LVL default and is integrated with
+the LVL sample application.</p>
+
+
+<h4 id="custom-policies">Guidelines for custom policies</h4>
+
+<p>In your licensing implementation, you can use one of the complete policies
+provided in the LVL (ServerManagedPolicy or StrictPolicy) or you can create a
+custom Policy. For any type of custom policy, there are several important design
+points to understand and account for in your implementation.</p>
+
+<p>The licensing server applies general request limits to guard against overuse
+of resources that could result in denial of service. When an application exceeds
+the request limit, the licensing server returns a 503 response, which gets
+passed through to your application as a general server error. This means that no
+license response will be available to the user until the limit is reset, which
+can affect the user for an indefinite period.</p>
+
+<p>If you are designing a custom Policy, we recommend that the Policy:
+<ol>
+<!-- <li>Limits the number of points at which your app calls for a license check
+to the minimum. </li> -->
+<li>Caches (and properly obfuscates) the most recent successful license response
+in local persistent storage.</li>
+<li>Returns the cached response for all license checks, for as long as the
+cached response is valid, rather than making a request to the licensing server.
+Setting the response validity accrording to the server-provided <code>VT</code>
+extra is highly recommended. See <a href="#extras">Server Response Extras</a>
+for more information.</li>
+<li>Uses an exponential backoff period if retrying any requests the result in
+errors. However, because the Android Market client automatically retries failed
+requests, the Policy does not need to do so, in most cases.</li>
+<li>Provides for a "grace period" that allows the user to access your
+application for a limited time or number of uses, while a license check is being
+retried. The grace period benefits the user by allowing access until the next
+license check can be completed successfully and it benefits you by placing a
+hard limit on access to your application when there is no valid license response
+available.</li>
+</ol>
+
+<p>Designing your Policy according to the guidelines listed above is critical,
+because it ensures the best possible experience for users while giving you
+effective control over your application even in error conditions. </p>
+
+<p>Note that any Policy can use settings provided by the licensing server to
+help manage validity and caching, retry grace period, and more. Extracting the
+server-provided settings is straightforward and making use of them is highly
+recommended. See the ServerManagedPolicy implementation for an example of how to
+extract and use the extras. For a list of server settings and information about
+how to use them, see <a href="#extras">Server Response Extras</a> in the
+Appendix of this document.</p>
+
+<h4 id="ServerManagedPolicy">ServerManagedPolicy</h4>
+
+<div class="sidebox-wrapper">
+<div class="sidebox">
+<h2>Server Response Extras</h2>
+
+<p>For certain types of licensing responses, the licensing server appends extra
+settings to the responses, to help the application manage licensing effectively.
+</p>
+
+<p style="margin-top:.5em;">See <a href="#extras">Server Response Extras</a> for
+a list of settings and <code>ServerManagedPolicy.java</code> for information
+about how a Policy can usethe extras.</p>
+
+</div>
+</div>
+
+<p>The LVL includes a full and recommended implementation of the Policy
+interface called ServerManagedPolicy. The implementation is integrated with the
+LVL classes and serves as the default Policy in the library. </p>
+
+<p>ServerManagedPolicy provides all of the handling for license and retry
+responses. It caches all of the response data locally in a
+{@link android.content.SharedPreferences} file, obfuscating it with the
+application's Obfuscator implementation. This ensures that the license response
+data is secure and persists across device power cycles. ServerManagedPolicy
+provides concrete implementations of the interface methods
+<code>processServerResponse()</code> and <code>allowAccess()</code> and also
+includes a set of supporting methods and types for managing license
+responses.</p>
+
+<p>Importantly, a key feature of ServerMangedPolicy is its use of
+server-provided settings as the basis for managing licensing across an
+application's refund period and through varying network and error conditions.
+When an application contacts the Android Market server for a license check, the
+server appends several settings as key-value pairs in the license response
+extras field. For example, the server provides recommended values for the
+application's license validity period, retry grace period, and maximum allowable
+retry count, among others. ServerManagedPolicy extracts the values from the
+license response in its <code>processServerResponse()</code> method and checks
+them in its <code>allowAccess()</code> method. For a list of the server-provided
+settings used by ServerManagedPolicy, see <a href="#extras">Server Response
+Extras</a> in the Appendix of this document.</p>
+
+<p>For convenience, best performance, and the benefit of using license settings
+from the Android Market server, <strong>using ServerManagedPolicy as your
+licensing Policy is strongly recommended</strong>. </p>
+
+<p>If you are concerned about the security of license response data that is
+stored locally in SharedPreferences, you can use a stronger obfuscation
+algorithm or design a stricter Policy that does not store license data. The LVL
+includes an example of such a Policy &mdash; see <a
+href="#StrictPolicy">StrictPolicy</a> for more information.</p>
+
+<p>To use ServerManagedPolicy, simply import it to your Activity, create an
+instance, and pass a reference to the instance when constructing your
+LicenseChecker. See <a href="#lc-lcc">Instantiate LicenseChecker and
+LicenseCheckerCallback</a> for more information. </p>
+
+<h4 id="StrictPolicy">StrictPolicy</h4>
+
+<p>The LVL includes an alternative full implementation of the Policy interface
+called StrictPolicy. The StrictPolicy implementation provides a more restrictive
+Policy than ServerManagedPolicy, in that it does not allow the user to access
+the application unless a license response is received from the server at the
+time of access that indicates that the user is licensed.</p>
+
+<p>The principal feature of StrictPolicy is that it does not store <em>any</em>
+license response data locally, in a persistent store. Because no data is stored,
+retry requests are not tracked and cached responses can not be used to fulfill
+license checks. The Policy allows access only if:</p>
+
+<ul>
+<li>The license response is received from the licensing server, and </li>
+<li>The license response indicates that the user is licensed to access the
+application. </li>
+</ul>
+
+<p>Using StrictPolicy is appropriate if your primary concern is to ensure that,
+in all possible cases, no user will be allowed to access the application unless
+the user is confirmed to be licensed at the time of use. Additionally, the
+Policy offers slightly more security than ServerManagedPolicy &mdash; since
+there is no data cached locally, there is no way a malicious user could tamper
+with the cached data and obtain access to the application.</p>
+
+<p>At the same time, this Policy presents a challenge for normal users, since it
+means that they won't be able to access the application when there is no network
+(cell or wi-fi) connection available. Another side-effect is that your
+application will send more license check requests to the server, since using a
+cached response is not possible. Depending on network conditions, this might
+prove challenging for users also.</p>
+
+<p>Overall, this policy represents a tradeoff of some degree of user convenience
+for absolute security and control over access. Consider the tradeoff carefully
+before using this Policy.</p>
+
+<p>To use StrictPolicy, simply import it to your Activity, create an instance,
+and pass a reference to it when constructing your LicenseChecker. See
+<a href="#lc-lcc">Instantiate LicenseChecker and LicenseCheckerCallback</a>
+for more information. </p>
+
+<h3 id="impl-Obfuscator">Implementing an Obfuscator</h3>
+
+<div class="sidebox-wrapper">
+<div class="sidebox">
+<h2>AESObfuscator</h2>
+
+<p>The LVL includes a full Obfuscator implementation in the
+<code>AESObfuscator.java</code> file. The Obfuscator uses AES encryption to
+obfuscate/unobfuscate data. If you are using a Policy (such as
+ServerManagedPolicy) that caches license response data, using AESObfuscator as
+basis for your Obfuscator implementation is highly recommended. </p>
+
+</div>
+</div>
+
+<p>A typical Policy implementation needs to save the license response data for
+an application to a persistent store, so that it is accessible across
+application invocations and device power cycles. For example, a Policy would
+maintain the timestamp of the last successful license check, the retry count,
+the license validity period, and similar information in a persistent store,
+rather than resetting the values each time the application is launched. The
+default Policy included in the LVL, ServerManagedPolicy, stores license response
+data in a {@link android.content.SharedPreferences} instance, to ensure that the
+data is persistent. </p>
+
+<p>Because the Policy will use stored license response data to determine whether
+to allow or disallow access to the application, it <em>must</em> ensure that any
+stored data is secure and can not be reused or manipulated by a root user on a
+device. Specifically, the Policy must always obfuscate the data before storing
+it, using a key that is unique for the application and device. Obfuscating using
+a key that is both application-specific and device-specific is critical, because
+it prevents the obfuscated data from being shared among applications and
+devices.</p>
+
+<p>The LVL assists the application with storing its license response data in a
+secure, persistent manner. First, it provides an <code>Obfuscator</code>
+interface that lets your application supply the obfuscation algorithm of its
+choice for stored data. Building on that, the LVL provides the helper class
+<code>PreferenceObfuscator</code>, which handles most of the work of calling the
+application's Obfuscator class and reading and writing the obfuscated data in a
+SharedPreferences instance. </p>
+
+<p>The LVL provides a full Obfuscator implementation called
+<code>AESObfuscator</code> that uses AES encryption to obfuscate data. You can
+use <code>AESObfuscator</code> in your application without modification or you
+can adapt it to your needs. For more information, see the next section.</p>
+
+<p>Alternatively, you can write a custom Obfuscator based on your own code
+or use an obfuscator program such as ProGuard for additional security.</p>
+
+<h4 id="AESObfuscator">AESObfuscator</h4>
+
+<p>The LVL includes a full and recommended implementation of the Obfuscator
+interface called AESObfuscator. The implementation is integrated with the
+LVL sample application and serves as the default Obfuscator in the library. </p>
+
+<p>AESObfuscator provides secure obfuscation of data by using AES to
+encrypt and decrypt the data as it is written to or read from storage.
+The Obfuscator seeds the encryption using three data fields provided
+by the application: </p>
+
+<ol>
+<li>A salt &mdash; an array of random bytes to use for each (un)obfuscation. </li>
+<li>An application identifier string, typically the package name of the application.</li>
+<li>A device identifier string, derived from as many device-specific sources
+as possible, so as to make it as unique.</li>
+</ol>
+
+<p>To use AESObfuscator, first import it to your Activity. Declare a private
+static final array to hold the salt bytes and initialize it to 20 randomly
+generated bytes.</p>
+
+<pre> ...
+ // Generate 20 random bytes, and put them here.
+ private static final byte[] SALT = new byte[] {
+ -46, 65, 30, -128, -103, -57, 74, -64, 51, 88, -95,
+ -45, 77, -117, -36, -113, -11, 32, -64, 89
+ };
+ ...
+</pre>
+
+<p>Next, declare a variable to hold a device identifier and generate a value for
+it in any way needed. For example, the sample application included in the LVL
+queries the system settings for the
+<code>android.Settings.Secure.ANDROID_ID</code>, which is unique to each device.
+</p>
+
+<p>Note that, depending on the APIs you use to derive device-specific
+information, your application might need to request additional permissions in
+order to secure device-specific information. For example, if you query the
+TelephonyManager to obtain the device IMEI or related data, your application
+will also need to request the <code>android.permission.READ_PHONE_STATE</code>
+permission in its manifest. Before requesting permissions in this way, consider
+how doing so might affect your application or its filtering of your application
+on Android Market (since some permissions can cause the SDK build tools to add
+the associated <code>&lt;uses-feature&gt;</code>).</p>
+
+<p>Finally, construct an instance of AESObfuscator, passing the salt,
+application identifier, and device identifier. You can construct the instance
+directly, while constructing your Policy and LicenseChecker. For example:</p>
+
+<pre> ...
+ // Construct the LicenseChecker with a Policy.
+ mChecker = new LicenseChecker(
+ this, new ServerManagedPolicy(this,
+ new AESObfuscator(SALT, getPackageName(), deviceId)),
+ BASE64_PUBLIC_KEY // Your public licensing key.
+ );
+ ...
+</pre>
+
+<p>For a complete example, see MainActivity in the LVL sample application.</p>
+
+
+<h3 id="impl-lc">Checking the license from your application's main Activity</h3>
+
+<p>Once you've implemented a Policy for managing access to your application, the
+next step is to add a license check to your application, which initiates a query
+to the licensing server if needed and manages access to the application based on
+the license response. All of the work of adding the license check and handling
+the response takes place in your main {@link android.app.Activity} source file.
+</p>
+
+<p>To add the license check and handle the response, you must:</p>
+
+<ol>
+ <li><a href="#imports">Add imports</a></li>
+ <li><a href="#lc-impl">Implement LicenseCheckerCallback</a> as a private inner class</li>
+ <li><a href="#thread-handler">Create a Handler</a> for posting from LicenseCheckerCallback to the UI thread</li>
+ <li><a href="#lc-lcc">Instantiate LicenseChecker</a> and LicenseCheckerCallback</li>
+ <li><a href="#check-access">Call checkAccess()</a> to initiate the license check</li>
+ <li><a href="#account-key">Embed your public key</a> for licensing</li>
+ <li><a href="#handler-cleanup">Call your LicenseChecker's onDestroy() method</a> to close IPC connections.</li>
+</ol>
+
+<p>The sections below describe these tasks. </p>
+
+<h4 id="lc-overview">Overview of license check and response</h4>
+
+<div class="sidebox-wrapper">
+<div class="sidebox">
+<h2>Example: MainActivity</h2>
+
+<p>The sample application included with the LVL provides a full example of how
+to initiate a license check and handle the result, in the
+<code>MainActivity.java</code> file.</p>
+
+</div>
+</div>
+
+<p>In most cases, you should add the license check to your application's main
+{@link android.app.Activity}, in the <code>onCreate()</code> method. This
+ensures that when the user launches your application directly, the license check
+will be invoked immediately. In some cases, you can add license checks in other
+locations as well. For example, if your application includes multiple Activity
+components that other applications can start by {@link android.content.Intent},
+you could add license checks in those Activities.</p>
+
+<p>A license check consists of two main actions: </p>
+
+<ul>
+<li>A call to a method to initiate the license check &mdash; in the LVL, this is
+a call to the <code>checkAccess()</code> method of a LicenseChecker object that
+you construct.</li>
+<li>A callback that returns the result of the license check. In the LVL, this is
+a <code>LicenseCheckerCallback</code> interface that you implement. The
+interface declares two methods, <code>allow()</code> and
+<code>dontAllow()</code>, which are invoked by the library based on to the
+result of the license check. You implement those two methods with whatever logic
+you need, to allow or disallow the user access to your application. Note that
+these methods do not determine <em>whether</em> to allow access &mdash; that
+determination is the responsibility of your Policy implementation. Rather, these
+methods simply provide the application behaviors for <em>how</em> to allow and
+disallow access (and handle application errors).</li>
+</ul>
+
+<div style="margin-bottom:2em;">
+
+<img src="{@docRoot}images/licensing_flow.png" style="text-align:left;margin-bottom:0;margin-left:3em;" />
+<div style="margin:.5em 0 1.5em 2em;padding:0"><strong>Figure 6.</strong> Overview of a
+typical license check interaction.</div>
+</div>
+
+<p>The diagram above illustrates how a typical license check takes place: </p>
+
+<ol>
+<li>Code in the application's main Activity instantiates LicenseCheckerCallback
+and LicenseChecker objects. When constructing LicenseChecker, the code passes in
+{@link android.content.Context}, a Policy implementation to use, and the
+publisher account's public key for licensing as parameters. </li>
+<li>The code then calls the <code>checkAccess()</code> method on the
+LicenseChecker object. The method implementation calls the Policy to determine
+whether there is a valid license response cached locally, in
+{@link android.content.SharedPreferences}.
+<ul>
+<li>If so, the <code>checkAccess()</code> implementation calls
+<code>allow()</code>.</li>
+<li>Otherwise, the LicenseChecker initiates a license check request that is sent
+to the licensing server.</li>
+</ul>
+</li>
+<li>When a response is received, LicenseChecker creates a LicenseValidator that
+verifies the signed license data and extracts the fields of the response, then
+passes them to your Policy for further evaluation.
+ <ul>
+ <li>If the license is valid, the Policy caches the response in
+SharedPreferences and notifies the validator, which then calls the
+<code>allow()</code> method on the LicenseCheckerCallback object. </li>
+ <li>If the license not valid, the Policy notifies the validator, which calls
+the <code>dontAllow()</code> method on LicenseCheckerCallback. </li>
+ </ul>
+</li>
+<li>In case of a recoverable local or server error, such as when the network is
+not available to send the request, LicenseChecker passes a RETRY response to
+your Policy's <code>processServerResponse()</code> method. </li>
+<li>In case of a application error, such as when the application attempts to
+check the license of an invalid package name, LicenseChecker passes an error
+response to the LicenseCheckerCallback's <code>applicationError()</code>
+method. </li>
+</ol>
+
+<p>Note that, in addition to initiating the license check and handling the
+result, which are described in the sections below, your application also needs
+to provide a <a href="#impl-Policy">Policy implementation</a> and, if the Policy
+stores response data (such as ServerManagedPolicy), an <a
+href="#impl-Obfuscator">Obfuscator</a> implementation. </p>
+
+
+<h4 id="imports">Add imports</h4>
+
+<p>First, open the class file of the application's main Activity and import
+LicenseChecker and LicenseCheckerCallback from the LVL package.</p>
+
+<pre> import com.android.vending.licensing.LicenseChecker;
+ import com.android.vending.licensing.LicenseCheckerCallback;</pre>
+
+<p>If you are using the default Policy implementation provided with the LVL,
+ServerManagedPolicy, import it also, together with the AESObfuscator. If you are
+using a custom Policy or Obfuscator, import those instead. </p>
+
+<pre> import com.android.vending.licensing.ServerManagedPolicy;
+ import com.android.vending.licensing.AESObfuscator;</pre>
+
+<h4 id="lc-impl">Implement LicenseCheckerCallback as a private inner class</h4>
+
+<p>LicenseCheckerCallback is an interface provided by the LVL for handling
+result of a license check. To support licensing using the LVL, you must
+implement LicenseCheckerCallback and
+its methods to allow or disallow access to the application.</p>
+
+<p>The result of a license check is always a call to one of the
+LicenseCheckerCallback methods, made based on the validation of the response
+payload, the server response code itself, and any additional processing provided
+by your Policy. Your application can implement the methods in any way needed. In
+general, it's best to keep the methods simple, limiting them to managing UI
+state and application access. If you want to add further processing of license
+responses, such as by contacting a backend server or applying custom constraints,
+you should consider incorporating that code into your Policy, rather than
+putting it in the LicenseCheckerCallback methods. </p>
+
+<p>In most cases, you should declare your implementation of
+LicenseCheckerCallback as a private class inside your application's main
+Activity class. </p>
+
+<p>Implement the <code>allow()</code> and <code>dontAllow()</code> methods as
+needed. To start with, you can use simple result-handling behaviors in the
+methods, such as displaying the license result in a dialog. This helps you get
+your application running sooner and can assist with debugging. Later, after you
+have determined the exact behaviors you want, you can add more complex handling.
+</p>
+
+<p>Some suggestions for handling unlicensed responses in
+<code>dontAllow()</code> include: </p>
+
+<ul>
+<li>Display a "Try again" dialog to the user, including a button to initiate a
+new license check. </li>
+<li>Display a "Purchase this application" dialog, including a button that
+deep-links the user to the application's details page on Market, from which the
+use can purchase the application. For more information on how to set up such
+links, see <a
+href="{@docRoot}guide/publishing/publishing.html#marketintent">Using Intents to
+Launch the Market Application on a Device</a>. </li>
+<li>Display a Toast notification that indicates that the features of the
+application are limited because it is not licensed. </li>
+</ul>
+
+<p>The example below shows how the LVL sample application implements
+LicenseCheckerCallback, with methods that display the license check result in a
+dialog. </p>
+
+<pre> private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
+ public void allow() {
+ if (isFinishing()) {
+ // Don't update UI if Activity is finishing.
+ return;
+ }
+ // Should allow user access.
+ displayResult(getString(R.string.allow));
+ }
+
+ public void dontAllow() {
+ if (isFinishing()) {
+ // Don't update UI if Activity is finishing.
+ return;
+ }
+ displayResult(getString(R.string.dont_allow));
+ // Should not allow access. An app can handle as needed,
+ // typically by informing the user that the app is not licensed
+ // and then shutting down the app or limiting the user to a
+ // restricted set of features.
+ // In this example, we show a dialog that takes the user to Market.
+ showDialog(0);
+ }
+ }
+</pre>
+
+<p>Additionally, you should implement the <code>applicationError()</code>
+method, which the LVL calls to let your application handle errors that are not
+retryable. For a list of such errors, see <a
+href="#server-response-codes">Server Response Codes</a> in the Appendix of this
+document. You can implement the method in any way needed. In most cases, the
+method should log the error code and call <code>dontAllow()</code>.</p>
+
+<h4 id="thread-handler">Create a Handler for posting from LicenseCheckerCallback
+to the UI thread</h4>
+
+<p>During a license check, the LVL passes the request to the Android Market
+application, which handles communication with the licensing server. The LVL
+passes the request over asynchronous IPC (using {@link android.os.Binder}) so
+the actual processing and network communication do not take place on a thread
+managed by your application. Similarly, when the Android Market application
+receives the result, it invokes a callback method over IPC, which in turn
+executes in an IPC thread pool in your application's process.</p>
+
+<p>The LicenseChecker class manages your application's IPC communication with
+the Android Market application, including the call that sends the request and
+the callback that receives the response. LicenseChecker also tracks open license
+requests and manages their timeouts. </p>
+
+<p>So that it can handle timeouts properly and also process incoming responses
+without affecting your application's UI thread, LicenseChecker spawns a
+background thread at instantiation. In the thread it does all processing of
+license check results, whether the result is a response received from the server
+or a timeout error. At the conclusion of processing, the LVL calls your
+LicenseCheckerCallback methods from the background thread. </p>
+
+<p>To your application, this means that:</p>
+
+<ol>
+<li>Your LicenseCheckerCallback methods will be invoked, in many cases, from a
+background thread.</li>
+<li>Those methods won't be able to update state or invoke any processing in the
+UI thread, unless you create a Handler in the UI thread and have your callback
+methods post to the Handler.</li>
+</ol>
+
+<p>If you want your LicenseCheckerCallback methods to update the UI thread,
+instantiate a {@link android.os.Handler} in the main Activity's
+{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method,
+as shown below. In this example, the LVL sample application's
+LicenseCheckerCallback methods (see above) call <code>displayResult()</code> to
+update the UI thread through the Handler's
+{@link android.os.Handler#post(java.lang.Runnable) post()} method.</p>
+
+<pre>private Handler mHandler;
+
+ &#64;Override
+ public void onCreate(Bundle savedInstanceState) {
+ ...
+ mHandler = new Handler();
+ }
+</pre>
+
+<p>Then, in your LicenseCheckerCallback methods, you can use Handler methods to
+post Runnable or Message objects to the Handler. Here's how the sample
+application included in the LVL posts a Runnable to a Handler in the UI thread
+to display the license status.</p>
+
+<pre> private void displayResult(final String result) {
+ mHandler.post(new Runnable() {
+ public void run() {
+ mStatusText.setText(result);
+ setProgressBarIndeterminateVisibility(false);
+ mCheckLicenseButton.setEnabled(true);
+ }
+ });
+ }
+</pre>
+
+<h4 id="lc-lcc">Instantiate LicenseChecker and LicenseCheckerCallback</h4>
+
+<p>In the main Activity's
+{@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method,
+create private instances of LicenseCheckerCallback and LicenseChecker. You must
+instantiate LicenseCheckerCallback first, because you need to pass a reference
+to that instance when you call the contructor for LicenseChecker. </p>
+
+<p>When you instantiate LicenseChecker, you need to pass in these parameters:</p>
+
+<ul>
+<li>The application {@link android.content.Context}</li>
+<li>A reference to the Policy implementation to use for the license check. In
+most cases, you would use the default Policy implementation provided by the LVL,
+ServerManagedPolicy. </li>
+<li>The String variable holding your publisher account's public key for
+licensing. </li>
+</ul>
+
+<p>If you are using ServerManagedPolicy, you won't need to access the class
+directly, so you can instantiate it directly in the LicenseChecker constructor,
+as shown in the example below. Note that you need to pass a reference to a new
+Obfuscator instance when you construct ServerManagedPolicy.</p>
+
+<p>The example below shows the instantiation of LicenseChecker and
+LicenseCheckerCallback from the <code>onCreate()</code> method of an Activity
+class. </p>
+
+<pre>public class MainActivity extends Activity {
+ ...
+ private LicenseCheckerCallback mLicenseCheckerCallback;
+ private LicenseChecker mChecker;
+
+ &#64;Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ ...
+ // Construct the LicenseCheckerCallback. The library calls this when done.
+ mLicenseCheckerCallback = new MyLicenseCheckerCallback();
+
+ // Construct the LicenseChecker with a Policy.
+ mChecker = new LicenseChecker(
+ this, new ServerManagedPolicy(this,
+ new AESObfuscator(SALT, getPackageName(), deviceId)),
+ BASE64_PUBLIC_KEY // Your public licensing key.
+ );
+ ...
+ }
+}
+</pre>
+
+
+<p>Note that LicenseChecker calls the LicenseCheckerCallback methods from the UI
+thread <em>only</em> if there is valid license response cached locally. If the
+license check is sent to the server, the callbacks always originate from the
+background thread, even for network errors. </p>
+
+
+<h4 id="check-access">Call checkAccess() to initiate the license check</h4>
+
+<p>In your main Activity, add a call to the <code>checkAccess()</code> method of the
+LicenseChecker instance. In the call, pass a reference to your
+LicenseCheckerCallback instance as a parameter. If you need to handle any
+special UI effects or state management before the call, you might find it useful
+to call <code>checkAccess()</code> from a wrapper method. For example, the LVL
+sample application calls <code>checkAccess()</code> from a
+<code>doCheck()</code> wrapper method:</p>
+
+<pre> &#64;Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ ...
+ // Call a wrapper method that initiates the license check
+ doCheck();
+ ...
+ }
+ ...
+ private void doCheck() {
+ mCheckLicenseButton.setEnabled(false);
+ setProgressBarIndeterminateVisibility(true);
+ mStatusText.setText(R.string.checking_license);
+ mChecker.checkAccess(mLicenseCheckerCallback);
+ }
+</pre>
+
+
+<h4 id="account-key">Embed your public key for licensing</h4>
+
+<p>For each publisher account, the Android Market service automatically
+generates a 2048-bit RSA public/private key pair that is used exlusively for
+licensing. The key pair is uniquely associated with the publisher account and is
+shared across all applications that are published through the account. Although
+associated with a publisher account, the key pair is <em>not</em> the same as
+the key that you use to sign your applications (or derived from it).</p>
+
+<p>The Android Market publisher site exposes the public key for licensing to any
+developer signed in to the publisher account, but it keeps the private key
+hidden from all users in a secure location. When an application requests a
+license check for an application published in your account, the licensing server
+signs the license response using the private key of your account's key pair.
+When the LVL receives the response, it uses the public key provided by the
+application to verify the signature of the license response. </p>
+
+<p>To add licensing to an application, you must obtain your publisher account's
+public key for licensing and copy it into your application. Here's how to find
+your account's public key for licensing:</p>
+
+<ol>
+<li>Go to the Android Market <a
+href="http://market.android.com/publish">publisher site</a> and sign in.
+Make sure that you sign in to the account from which the application you are
+licensing is published (or will be published). </li>
+<li>In the account home page, locate the "Edit profile" link and click it. </li>
+<li>In the Edit Profile page, locate the "Licensing" pane, shown below. Your
+public key for licensing is given in the "Public key" text box. </p>
+</ol>
+
+<p>To add the public key to your application, simply copy/paste the key string
+from the text box into your application as the value of the String variable
+<code>BASE64_PUBLIC_KEY</code>. When you are copying, make sure that you have
+selected the entire key string, without omitting any characters. </p>
+
+<p>Here's an example from the LVL sample application:</p>
+
+<pre> public class MainActivity extends Activity {
+ private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG ... "; //truncated for this example
+ ...
+ }
+</pre>
+
+<h4 id="handler-cleanup">Call your LicenseChecker's onDestroy() method
+to close IPC connections</h4>
+
+<p>Finally, to let the LVL clean up before your application
+{@link android.content.Context} changes, add a call to the LicenseChecker's
+<code>onDestroy()</code> method from your Activity's
+{@link android.app.Activity#onDestroy()} implementation. The call causes the
+LicenseChecker to properly close any open IPC connection to the Android Market
+application's ILicensingService and removes any local references to the service
+and handler.</p>
+
+<p>Failing to add the call the LicenseChecker's <code>onDestroy()</code> method
+can lead to problems over the lifecycle of your application. For example, if the
+user changes screen orientation while a license check is active, the application
+{@link android.content.Context} is destroyed. If your application does not
+properly close the LicenseChecker's IPC connection, your application will crash
+when the response is received. Similarly, if the user exits your application
+while a license check is in progress, your application will crash when the
+response is received, unless your application has properly called the
+LicenseChecker's <code>onDestroy()</code> method to disconnect from the service.
+</p>
+
+<p>Here's an example from the sample application included in the LVL, where
+<code>mChecker</code> is the LicenseChecker instance:</p>
+
+<pre> &#64;Override
+ protected void onDestroy() {
+ super.onDestroy();
+ mChecker.onDestroy();
+ ...
+ }
+</pre>
+
+<p>If you are extending or modifying LicenseChecker, you might also need to call
+the LicenseChecker's <code>finishCheck()</code> method, to clean up any open IPC
+connections.</p>
+
+<h3 id="impl-DeviceLimiter">Implementing a DeviceLimiter</h3>
+
+<p>In some cases, you might want your Policy to limit the number of actual
+devices that are permitted to use a single license. This would prevent a user
+from moving a licensed application onto a number of devices and using the
+application on those devices under the same account ID. It would also prevent a
+user from "sharing" the application by providing the account information
+associated with the license to other individuals, who could then sign in to that
+account on their devices and access the license to the application. </p>
+
+<p>The LVL supports per-device licensing by providing a
+<code>DeviceLimiter</code> interface, which declares a single method,
+<code>allowDeviceAccess()</code>. When a LicenseValidator is handling a response
+from the licensing server, it calls <code>allowDeviceAccess()</code>, passing a
+user ID string extracted from the response.</p>
+
+<p>If you do not want to support device limitation, <strong>no work is
+required</strong> &mdash; the LicenseChecker class automatically uses a default
+implementation called NullDeviceLimiter. As the name suggests, NullDeviceLimiter
+is a "no-op" class whose <code>allowDeviceAccess()</code> method simply returns
+a LICENSED response for all users and devices. </p>
+
+<div style="border-left:4px solid #FFCF00;margin:1em;padding: 0 0 0 .5em">
+<p><strong>Caution:</strong> Per-device licensing is <em>not recommended for
+most applications</em> because:</p>
+<ul>
+<li>It requires that you provide a backend server to manage a users and devices
+mapping, and </li>
+<li>It could inadvertently result in a user being denied access to an
+application that they have legitimately purchased on another device.</li>
+</ul>
+</div>
+
+
+<h2 id="test-env">Setting Up the Testing Environment</h2>
+
+<p>The Android Market publisher site provides configuration tools that let you
+and others test licensing on your application before it is published. As you are
+implementing licensing, you can make use of the publisher site tools to test
+your application's Policy and handling of different licensing responses and
+error conditions.</p>
+
+<p>The main components of the test environment for licensing include: </p>
+
+<ul>
+<li>A "Test response" configuration in your publisher account that lets you
+control the licensing response returned, when the server processes a license
+check for an uploaded application from the publisher account or a test
+account.</li>
+<li>An optional set of test accounts that will receive the configured test
+response when checking the license of an application that you have uploaded
+(regardless whether the application is published or not).</li>
+<li>A runtime environment for the application that includes the Android Market
+application or Google APIs Add-On, on which the user is signed in to the
+publisher account or one of the test accounts.
+</ul>
+
+<p>Setting up the test environment properly involves:</p>
+
+<ol>
+<li><a href="#test-response">Setting static test responses</a> that are returned by the licensing server.</li>
+<li><a href="#test-acct-setup">Setting up test accounts</a> as needed.</li>
+<li><a href="#acct-signin">Signing in</a> properly to an emulator or device, before initiating a license check test.</li>
+</ol>
+
+<p>The sections below provide more information.</p>
+
+
+<h3 id="test-response">Setting test responses for license checks</h3>
+
+<p>Android Market provides a configuration setting in your publisher account
+that lets you override the normal processing of a license check for an
+application you have uploaded and return a specified response code. The setting
+is for testing only and applies <em>only</em> to license checks for applications
+that you have uploaded. For other users (users not signed in to test accounts),
+the server always processes license checks according to normal rules. </p>
+
+<p>To set a test response for your account, sign in to your publisher account
+and click "Edit Profile". In the Edit Profile page, locate the Test Response
+menu in the Licensing panel, shown below. You can select from the full set of
+valid server response codes to control the response or condition you want to
+test in your application.</p>
+
+<p>In general, you should make sure to test your application's licensing
+implementation with every response code available in the Test Response" menu.
+For a description of the codes, see <a href="#server-response-codes">Server
+Response Codes</a>, below.</p>
+
+<div style="margin-bottom:2em;" id="licensing_test_response">
+
+<img src="{@docRoot}images/licensing_test_response.png" style="text-align:left;margin-bottom:0;" />
+<div style="margin:0 2em;padding:0"><strong>Figure 7.</strong> The Licensing
+panel of your account's Edit Profile page, showing the Test Accounts field and the
+Test Response menu.</div>
+</div>
+
+<p>Note that the test response that you configure applies account-wide &mdash;
+that is, it applies not to a single application, but to <em>all</em>
+applications associated with the publisher account. If you are testing multiple
+applications at once, changing the test response will affect all of those
+applications on their next license check.</p>
+
+<p>Finally, before you can successfully send these test responses to your
+application, you must sign in to the device or emulator on which the application
+is installed, and from which it is querying the server. Specifically, you must
+sign using either your publisher account or one of the test accounts that you
+have set up. For more information about test accounts, see the next section.</p>
+
+<p>See <a href="#server-response-codes">Server Response Codes</a> for a list of
+test responses available and their meanings. </p>
+
+
+<h3 id="test-acct-setup">Setting up test accounts</h3>
+
+<p>In some cases, you might want to let multiple teams of developers test
+licensing on applications that will ultimately be published through your
+publisher account, but without giving them access to your publisher account's
+sign-in credentials. To meet that need, the Android Market publisher site lets
+you set up one or more optional <em>test accounts</em> &mdash; accounts that are
+authorized to query the licensing server and receive static test responses from
+your publisher account.</p>
+
+<p>Test accounts are standard Google accounts that you register on your
+publisher account, such that they will receive the test response for
+applications that you have uploaded. Developers can then sign in to their
+devices or emulators using the test account credentials and initiate license
+checks from installed applications. When the licensing server receives a license
+check from a user of a test account, it returns the static test response
+configured for the publisher account. </p>
+
+<p>Necessarily, there are limitations on the access and permissions given to
+users signed in through test accounts, including:</p>
+
+<ul>
+<li>Test account users can query the licensing server only for applications that
+are already uploaded to the publisher account. </li>
+<li>Test account users do not have permission to upload applications to your
+publisher account.</li>
+<li>Test account users do not have permission to set the publisher account's
+static test response.</li>
+</ul>
+
+<p>The table below summarizes the differences in capabilities, between the
+publisher account, a test account, and any other account.</p>
+
+<p class="table-caption" id="acct-types-table"><strong>Table 1.</strong>
+Differences in account types for testing licensing.</p>
+
+<table>
+<tr>
+<th>Account Type</th>
+<th>Can check license before upload?</th>
+<th>Can receive test response?</th>
+<th>Can set test response?</th>
+</tr>
+
+<tr>
+<td>Publisher account</td>
+<td>Yes</td>
+<td>Yes</td>
+<td>Yes</td>
+</tr>
+
+<tr>
+<td>Test account</td>
+<td>No</td>
+<td>Yes</td>
+<td>No</td>
+</tr>
+
+<tr>
+<td>Other</td>
+<td>No</td>
+<td>No</td>
+<td>No</td>
+</tr>
+</table>
+
+<h4 id="reg-test-acct">Registering test accounts on the publisher account</h4>
+
+<p>To get started, you need to register each test account in your publisher
+account. As shown in <a href="#licensing_test_response">Figure 7</a>, above, you
+register test accounts in the Licensing panel of your publisher account's Edit
+Profile page. Simply enter the accounts as a comma-delimited list and click
+<strong>Save</strong> to save your profile changes.</p>
+
+<p>You can use any Google account as a test account. If you want to own and
+control the test accounts, you can create the accounts yourself and distribute
+the credentials to your developers or testers.</p>
+
+<h4 id="test-app-upload">Handling application upload and distribution for test
+account users</h4>
+
+<p>As mentioned above, users of test accounts can only receive static test
+responses for applications that are uploaded to the publisher account. Since
+those users do not have permission to upload applications, as the publisher you
+will need to work with those users to collect apps for upload and distribute
+uploaded apps for testing. You can handle collection and distribution in any way
+that is convenient. </p>
+
+<p>Once an application is uploaded and becomes known to the licensing server,
+developers and testers can continue modify the application in their local
+development environment, without having to upload new versions. You only need to
+upload a new version if the local application increments the
+<code>versionCode</code> attribute in the manifest file. </p>
+
+<h4 id="test-key">Distributing your public key to test account users</h4>
+
+<p>The licensing server handles static test responses in the normal way,
+including signing the license response data, adding extras parameters, and so
+on. To support developers who are implementing licensing using test accounts,
+rather than having access to the publisher account, you will need to distribute
+your public key to them. Developers without access to the publisher site do not
+have access to your public key, and without the key they won't be able to
+verify license responses. </p>
+
+<p>Note that if you decide to generate a new licensing key pair for your account
+for some reason, you need to notify all users of test accounts. For
+testers, you can embed the new key in the application package and distribute it
+to users. For developers, you will need to distribute the new key to them
+directly. </p>
+
+
+<h3 id="acct-signin">Signing in to an authorized account in the runtime
+environment</h3>
+
+<p>The licensing service is designed to determine whether a given user is
+licensed to use a given application &mdash; during a license check, the Android
+Market application gathers the user ID from the primary account on the system
+and sends it to the server, together with the package name of the application
+and other information. However, if there is no user information available, the
+license check cannot succeed, so the Android Market application terminates the
+request and returns an error to the application. </p>
+
+<p>During testing, to ensure that your application can successfully query the
+licensing server, you must make sure that you sign in to an account <em>on the
+device or emulator</em> using:</p>
+
+<ul>
+<li>The credentials of a publisher account, or</li>
+<li>The credentials of a test account that is registered with a publisher
+account</li>
+</ul>
+
+
+<div class="sidebox-wrapper">
+<div class="sidebox">
+<h2>Signing in to a Google account on an emulator</h2>
+
+<p>If you are testing licensing on an emulator, you need to sign in to a Google
+account on the emulator. If you do not see an option to create a new Google
+account, the problem might be that your AVD is running a standard Android system
+image, rather than the Google APIs Add-On, API 8 (release 2) or higher. </p>
+
+<p style="margin-top:.5em;">For more information, see <a
+href="#runtime-setup">Setting up the runtime environment</a>, above.</p>
+
+</div>
+</div>
+
+<p>Signing in using a publisher account offers the advantage of letting your
+applications receive static test responses even before the applications are
+uploaded to the publisher site.</p>
+
+<p>If you are part of a larger organization or are working with external groups
+on applications that will be published through your site, you will more likely
+want to distribute test accounts instead, then use those to sign in during
+testing. </p>
+
+<p>To sign in on a device or emulator, follow the steps below. The preferred
+approach is to sign in as the primary account &mdash; however, if there are
+other accounts already in use on the device or emulator, you can create an
+additional account and sign in to it using the publisher or test account
+credentials. </p>
+
+<ol>
+<li>Open Settings &gt; Accounts &amp; sync</li>
+<li>Select <strong>Add Account</strong> and choose to add a "Google" account.
+</li>
+<li>Select <strong>Next</strong> and then <strong>Sign in</strong>.</li>
+<li>Enter the username and password of either the publisher account or a test
+account that is registered in the publisher account.</li>
+<li>Select <strong>Sign in</strong>. The system signs you in to the new
+account.</li>
+</ol>
+
+<p>Once you are signed in, you can begin testing licensing in your application
+(if you have completed the LVL integration steps above). When your application
+initiates a license check, it will receive a response containing the static test
+response configured on the publisher account. </p>
+
+<p>Note that, if you are using an emulator, you will need to sign in to the
+publisher account or test account each time you wipe data when restarting the
+emulator.</p>
+
+<div style="margin:2em 1em 1em 1em;">
+
+<img src="{@docRoot}images/licensing_device_signin.png" style="text-align:left;" />
+<div style="margin:.25em 1.25em;padding:0"><strong>Figure 8.</strong> Example of
+setting up a Google account on a device or emulator.</div>
+</div>
+
+<h2 id="app-obfuscation">Obfuscating Your Application</h2>
+
+<p>To ensure the security of your application, particularly for a paid
+application that uses licensing and/or custom constraints and protections, it's
+very important to obfuscate your application code. Properly obfuscating your
+code makes it more difficult for a malicious user to decompile the application's
+bytecode, modify it &mdash; such as by removing the license check &mdash;
+and then recompile it.</p>
+
+<p>Several obfuscator programs are available for Android applications, including
+<a href="http://proguard.sourceforge.net/">ProGuard</a>, which also offers
+code-optimization features. The use of ProGuard or a similar program to obfuscate
+your code is <em>strongly recommended</em> for all applications that use Android
+Market Licensing. </p>
+
+<h2 id="app-publishing">Publishing a Licensed Application</h2>
+
+<p>When you are finished testing your license implementation, you are ready to
+publish the application on Android Market. Follow the normal steps to <a
+href="{@docRoot}guide/publishing/preparing.html">prepare</a>, <a
+href="{@docRoot}guide/publishing/app-signing.html">sign</a>, and then <a
+href="{@docRoot}guide/publishing/publishing.html">publish the application</a>.
+</p>
+
+<h4>Removing Copy Protection</h4>
+
+<p>After uploading your licensed application, remember to remove copy protection
+from the application, if it is currently used. To check and remove copy
+protection, sign in to the publisher site and go the application's upload
+details page. In the Publishing options section, make sure that the Copy
+Protection radio button selection is "Off".</p>
+
+<h4>Considerations for Free Apps</h4>
+
+<p>Licensing is currently supported only for paid applications. If you already
+published your application as free, you won't be able to upload an updated
+version that includes licensing (that is, an application that uses the same
+package name and that includes the <a href="#manifest-permission">licensing
+permission</a>). Here are some points to keep in mind:</p>
+
+<ul>
+<li>If you want to offer a free version of your application that provides a
+reduced feature set (or that offers the full feature set for trial period), the
+free version of your application must not include the licensing permission and
+must use a different package name than the paid version of the app.</li>
+<li>If you want to offer a paid version of your free application that uses
+licensing, you can do so under a new package name.</li>
+</ul>
+
+<h2 id="support">Where to Get Support</h2>
+
+<p>If you have questions or encounter problems while implementing or deploying
+publishing in your applications, please use the support resources listed in the
+table below. By directing your queries to the correct forum, you can get the
+support you need more quickly. </p>
+
+<p class="table-caption"><strong>Table 2.</strong> Developer support resources
+for Android Market Licensing Service.</p>
+
+<table>
+
+<tr>
+<th>Support Type</th>
+<th>Resource</th>
+<th>Range of Topics</th>
+</tr>
+<tr>
+<td rowspan="2">Development and testing issues</td>
+<td>Google Groups: <a
+href="http://groups.google.com/group/android-developers">android-developers</a>
+</td>
+<td rowspan="2">LVL download and integration, library projects, Policy
+questions, user experience ideas, handling of responses, Obfuscator, IPC, test
+environment setup</td>
+</tr>
+<tr>
+<td>Stack Overflow: <a
+href="http://stackoverflow.com/questions/tagged/android">http://stackoverflow.com/questions/tagged/android</a></td>
+</tr>
+<tr>
+<td rowspan="2">Accounts, publishing, and deployment issues</td>
+<td><a href="http://www.google.com/support/forum/p/Android+Market">Android
+Market Help Forum</a></td>
+<td rowspan="2">Publisher accounts, licensing key pair, test accounts, server
+responses, test responses, application deployment and results</td>
+</tr>
+<tr>
+<td><a
+href="http://market.android.com/support/bin/answer.py?answer=186113">Market
+Licensing Support FAQ</a></td>
+</tr>
+<tr>
+<td>LVL issue tracker</td>
+<td><a href="http://code.google.com/p/marketlicensing/issues/">Marketlicensing
+project issue tracker</a></td>
+<td>Bug and issue reports related specifically to the LVL source code classes
+and interface implementations</td>
+</tr>
+
+</table>
+
+<p>For general information about how to post to the groups listed above, see <a
+href="{@docRoot}resources/community-groups.html">Developer Forums</a> document
+in the Resources tab.</p>
+
+<h2 id="lvl-summary">Summary of LVL Classes and Interfaces</h2>
+
+<p>The table below lists all of the source files in the License Verification
+Library (LVL) available through the Android SDK. All of the files are part of
+the <code>com.android.vending.licensing</code> package.</p>
+
+<p class="table-caption"><strong>Table A-1.</strong> Summary of LVL library
+classes and interfaces.</p>
+
+<div style="width:99%">
+<table width="100%">
+
+<tr>
+<th width="15%">Category</th>
+<th width="20%">Name</th>
+<th width="100%">Description</th>
+</tr>
+
+<tr>
+<td rowspan="2">License check and result</td>
+<td>LicenseChecker</td>
+<td>Class that you instantiate (or subclass) to initiate a license check.</td>
+</tr>
+<tr>
+<td><em>LicenseCheckerCallback</em></td>
+<td>Interface that you implement to handle result of the license check.</td>
+</tr>
+
+<tr>
+<td rowspan="3" width="15%">Policy</td>
+<td width="20%"><em>Policy</em></td>
+<td width="100%">Interface that you implement to determine whether to allow
+access to the application, based on the license response. </td>
+</tr>
+<tr>
+<td>ServerManagedPolicy</td>
+<td width="100%">Default Policy implementation. Uses settings provided by the
+licensing server to manage local storage of license data, license validity,
+retry.</td>
+</tr>
+<tr>
+<td>StrictPolicy</td>
+<td>Alternative Policy implementation. Enforces licensing based on a direct
+license response from the server only. No caching or request retry.</td>
+</tr>
+
+<tr>
+<td rowspan="2" width="15%">Data obfuscation <br><em>(optional)</em></td>
+<td width="20%"><em>Obfuscator</em></td>
+<td width="100%">Interface that you implement if you are using a Policy (such as
+ServerManagedPolicy) that caches license response data in a persistent store.
+Applies an obfuscation algorithm to encode and decode data being written or
+read.</td>
+</tr>
+<tr>
+<td>AESObfuscator</td>
+<td>Default Obfuscator implementation that uses AES encryption/decryption
+algorithm to obfuscate/unobfuscate data.</td>
+</tr>
+
+<tr>
+<td rowspan="2" width="15%">Device limitation<br><em>(optional)</em></td>
+<td width="20%"><em>DeviceLimiter</em></td>
+<td width="100%">Interface that you implement if you want to restrict use of an
+application to a specific device. Called from LicenseValidator. Implementing
+DeviceLimiter is not recommended for most applications because it requires a
+backend server and may cause the user to lose access to licensed applications,
+unless designed with care.</td>
+</tr>
+<tr>
+<td>NullDeviceLimiter</td>
+<td>Default DeviceLimiter implementation that is a no-op (allows access to all
+devices).</td>
+</tr>
+
+<tr>
+<td rowspan="6" width="15%">Library core, no integration needed</td>
+<td width="20%">ResponseData</td>
+<td width="100%">Class that holds the fields of a license response.</td>
+</tr>
+<tr>
+<td>LicenseValidator</td>
+<td>Class that decrypts and verifies a response received from the licensing
+server.</td>
+</tr>
+<tr>
+<td>ValidationException</td>
+<td>Class that indicates errors that occur when validating the integrity of data
+managed by an Obfuscator.</td>
+</tr>
+<tr>
+<td>PreferenceObfuscator</td>
+<td>Utility class that writes/reads obfuscated data to the system's
+{@link android.content.SharedPreferences} store.</td>
+</tr>
+<tr>
+<td><em>ILicensingService</em></td>
+<td>One-way IPC interface over which a license check request is passed to the
+Android Market client.</td>
+</tr>
+<tr>
+<td><em>ILicenseResultListener</em></td>
+<td>One-way IPC callback implementation over which the application receives an
+asynchronous response from the licensing server.</td>
+</tr>
+
+</table>
+</div>
+
+
+<h2 id="server-response-codes">Server Response Codes</h2>
+
+<p>The table below lists all of the license response codes supported by the
+licensing server. In general, an application should handle all of these response
+codes. By default, the LicenseValidator class in the LVL provides all of the
+necessary handling of these response codes for you. </p>
+
+<p class="table-caption"><strong>Table A-2.</strong> Summary of response codes
+returned by the Android Market server in a license response.</p>
+
+<table>
+
+<tr>
+<th>Response Code</th>
+<th>Description</th>
+<th>Signed?</th>
+<th>Extras</th>
+<th>Comments</th>
+</tr>
+<tr>
+<td>LICENSED</td>
+<td>The application is licensed to the user. The user has purchased the
+application or the application is free.</td>
+<td>Yes</td>
+<td><code>VT</code>,&nbsp;<code>GT</code>, <code>GR</code></td>
+<td><em>Allow access according to Policy constraints.</em></td>
+</tr>
+<tr>
+<td>LICENSED_OLD_KEY</td>
+<td>The application is licensed to the user, but there is an updated application
+version available that is signed with a different key. </td>
+<td>Yes </td>
+<td><code>VT</code>, <code>GT</code>, <code>GR</code>, <code>UT</code></td>
+<td><em>Optionally allow access according to Policy constraints.</em>
+<p style="margin-top:.5em;">Can indicate that the key pair used by the installed
+application version is invalid or compromised. The application can allow access
+if needed or inform the user that an upgrade is available and limit further use
+until upgrade.</p>
+</td>
+</tr>
+<tr>
+<td>NOT_LICENSED</td>
+<td>The application is not licensed to the user.</td>
+<td>No</td>
+<td></td>
+<td><em>Do not allow access.</em></td>
+</tr>
+<tr>
+<td>ERROR_CONTACTING_SERVER</td>
+<td>Local error &mdash; the Android Market application was not able to reach the
+licensing server, possibly because of network availability problems. </td>
+<td>No</td>
+<td></td>
+<td><em>Retry the license check according to Policy retry limits.</em></td>
+</tr>
+<tr>
+<td>ERROR_SERVER_FAILURE</td>
+<td>Server error &mdash; the server could not load the publisher account's key
+pair for licensing.</td>
+<td>No</td>
+<td></td>
+<td><em>Retry the license check according to Policy retry limits.</em>
+</td>
+</tr>
+<tr>
+<td>ERROR_INVALID_PACKAGE_NAME</td>
+<td>Local error &mdash; the application requested a license check for a package
+that is not installed on the device. </td>
+<td>No </td>
+<td></td>
+<td><em>Do not retry the license check.</em>
+<p style="margin-top:.5em;">Typically caused by a developement error.</p>
+</td>
+</tr>
+<tr>
+<td>ERROR_NON_MATCHING_UID</td>
+<td>Local error &mdash; the application requested a license check for a package
+whose UID (package, user ID pair) does not match that of the requesting
+application. </td>
+<td>No </td>
+<td></td>
+<td><em>Do not retry the license check.</em>
+<p style="margin-top:.5em;">Typically caused by a developement error.</p>
+</td>
+</tr>
+<tr>
+<td>ERROR_NOT_MARKET_MANAGED</td>
+<td>Server error &mdash; the application (package name) was not recognized by
+Android Market. </td>
+<td>No</td>
+<td></td>
+<td><em>Do not retry the license check.</em>
+<p style="margin-top:.5em;">Can indicate that the application was not published
+through Android Market or that there is an development error in the licensing
+implementation.</p>
+</td>
+</tr>
+
+</table>
+
+
+<h2 id="extras">Server Response Extras</h2>
+
+<p>The licensing server includes several settings in certain types of license
+responses, to assist the application and its Policy in managing access to the
+application across the 24-hour refund period and other conditions. Specifically,
+the server provides recommended values for the application's license validity
+period, retry grace period, maximum allowable retry count, and other settings.
+The server appends the settings as key-value pairs in the license response
+"extras" field. </p>
+
+<p>Any Policy implementation can extract the extras settings from the license
+response and use them as needed. The LVL default Policy implementation, <a
+href="#ServerManagedPolicy">ServerManagedPolicy</a>, serves as a working
+implementation and an illustration of how to obtain, store, and use the
+settings. </p>
+
+<p class="table-caption"><strong>Table A-3.</strong> Summary of
+license-management settings supplied by the Android Market server in a license
+response.</p>
+
+<table>
+<tr>
+<th>Extra</th><th>Description</th>
+</tr>
+
+<tr>
+ <td>VT</td>
+ <td>License validity timestamp. Specifies the date/time at which the current
+(cached) license response expires and must be rechecked on the licensing server.
+ </td>
+</tr>
+<tr>
+ <td>GT</td>
+ <td>Grace period timestamp. Specifies the end of the period during which a
+Policy may allow access to the application, even though the response status is
+RETRY. <p>The value is managed by the server, however a typical value would be 5
+or more days.</p></td>
+</tr>
+<tr>
+ <td>GR</td>
+ <td>Maximum retries count. Specifies how many consecutive RETRY license checks
+the Policy should allow, before denying the user access to the application.
+<p>The value is managed by the server, however a typical value would be "10" or
+higher.</p></td>
+</tr>
+<tr>
+ <td>UT</td>
+ <td>Update timestamp. Specifies the day/time when the most recent update to
+this application was uploaded and published. <p>The server returns this extra
+only for LICENSED_OLD_KEYS responses, to allow the Policy to determine how much
+time has elapsed since an update was published with new licensing keys before
+denying the user access to the application. </p></td>
+</tr>
+
+</table>
+
+<p>The sections below provide more information about the server-provided
+settings and how to use them. </p>
+
+<h4>License validity period</h4>
+
+<p>The Android Market licensing server sets a license validity period for all
+downloaded applications. The period expresses the interval of time over which an
+application's license status should be considered as unchanging and cacheable by
+a licensing Policy in the application. The licensing server includes the
+validity period in its response to all license checks, appending an
+end-of-validity timestamp to the response as an extra under the key "VT". A
+Policy can extract the VT key value and use it to conditionally allow access to
+the application without rechecking the license, until the validity period
+expires. </p>
+
+<p>The license validity signals to a licensing Policy when it must recheck the
+licensing status with the licensing server. It is <em>not</em> intended to imply
+whether an application is actually licensed for use. That is, when an
+application's license validity period expires, this does not mean that the
+application is no longer licensed for use &mdash; rather, it indicates only that
+the Policy must recheck the licensing status with the server. It follows that,
+as long as the license validity period is not expired, it is acceptable for the
+Policy to cache the initial license status locally and return the cached license
+status instead of sending a new license check to the server.</p>
+
+<p>The licensing server manages the validity period as a means of helping the
+application properly enforce licensing across the refund period offered by
+Android Market for paid applications. It sets the validity period based on
+whether the application was purchased and, if so, how long ago. Specifically,
+the server sets a validity period as follows:</p>
+
+<ul>
+<li>For a paid application, the server sets the initial license validity period
+so that the license reponse remains valid for as long as the application is
+refundable. A licensing Policy in the application may cache the
+result of the initial license check and does not need to recheck the license
+until the validity period has expired.</li>
+<li>When an application is no longer refundable, the server
+sets a longer validity period &mdash; typically a number of days. </li>
+<li>For a free application, the server sets the validity period to a very high
+value (<code>long.MAX_VALUE</code>). This ensures that, provided the Policy has
+cached the validity timestamp locally, it will not need to recheck the
+license status of the application in the future.</li>
+</ul>
+
+<p>The ServerManagedPolicy implementation uses the extracted timestamp
+(<code>mValidityTimestamp</code>) as a primary condition for determining whether
+to recheck the license status with the server before allowing the user access to
+the application. </p>
+
+<h4>Retry period and maximum retry count</h4>
+
+<p>In some cases, system or network conditions can prevent an application's
+license check from reaching the licensing server, or prevent the server's
+response from reaching the Android Market client application. For example, the
+user might launch an application when there is no cell network or data
+connection available &mdash; such as when on an airplane &mdash; or when the
+network connection is unstable or the cell signal is weak. </p>
+
+<p>When network problems prevent or interrupt a license check, the Android
+Market client notifies the application by returning a "RETRY" response code to
+the Policy's <code>processServerResponse()</code> method. In the case of system
+problems, such as when the application is unable to bind with Android Market's
+ILicensingService implementation, the LicenseChecker library itself calls the
+Policy <code>processServerResonse()</code> method with a "RETRY" response code.
+</p>
+
+<p>In general, the RETRY response code is a signal to the application that an
+error has occurred that has prevented a license check from completing.
+
+<p>The Android Market server helps an application to manage licensing under
+error conditions by setting a retry "grace period" and a recommended maximum
+retries count. The server includes these values in all license check responses,
+appending them as extras under the keys "GT" and "GR". </p>
+
+<p>The application Policy can extract the GT and GR extras and use them to
+conditionally allow access to the application, as follows:</p>
+
+<ul>
+<li>For a license check that results in a RETRY response, the Policy should
+cache the RETRY response code and increment a count of RETRY responses.</li>
+<li>The Policy should allow the user to access the application, provided that
+either the retry grace period is still active or the maximum retries count has
+not been reached.</li>
+</ul>
+
+<p>The ServerManagedPolicy uses the server-supplied GT and GR values as
+described above. The example below shows the conditional handling of the retry
+responses in the <code>allow()</code> method. The count of RETRY responses is
+maintained in the <code>processServerResponse()</code> method, not shown. </p>
+
+
+<pre> public boolean allowAccess() {
+ long ts = System.currentTimeMillis();
+ if (mLastResponse == LicenseResponse.LICENSED) {
+ // Check if the LICENSED response occurred within the validity timeout.
+ if (ts &lt;= mValidityTimestamp) {
+ // Cached LICENSED response is still valid.
+ return true;
+ }
+ } else if (mLastResponse == LicenseResponse.RETRY &amp;&amp;
+ ts &lt; mLastResponseTime + MILLIS_PER_MINUTE) {
+ // Only allow access if we are within the retry period or we haven't used up our
+ // max retries.
+ return (ts &lt;= mRetryUntil || mRetryCount &lt;= mMaxRetries);
+ }
+ return false;
+ }</pre>
+
diff --git a/docs/html/guide/publishing/preparing.jd b/docs/html/guide/publishing/preparing.jd
index c1c6351..442c12a 100644
--- a/docs/html/guide/publishing/preparing.jd
+++ b/docs/html/guide/publishing/preparing.jd
@@ -39,13 +39,14 @@ Applications</a> document. </p>
<ol>
<li>Test your application extensively on an actual device </li>
<li>Consider adding an End User License Agreement in your application</li>
+<li>Consider adding licensing support</li>
<li>Specify an icon and label in the application's manifest</li>
<li>Turn off logging and debugging and clean up data/files</li>
</ol>
<p>Before you do the final compile of your application:</p>
-<ol start="5">
+<ol start="6">
<li>Version your application</li>
<li>Obtain a suitable cryptographic key</li>
<li>Register for a Maps API Key, if your application is using MapView elements</li>
@@ -53,7 +54,7 @@ Applications</a> document. </p>
<p><em>Compile your application...</em></p>
<p>After compiling your application:</p>
-<ol start="8">
+<ol start="9">
<li>Sign your application</li>
<li>Test your compiled application</li>
</ol>
@@ -101,7 +102,19 @@ application</h3>
<p>To protect your person, organization, and intellectual property, you may want
to provide an End User License Agreement (EULA) with your application.
-<h3 id="iconlabel">3. Specify an icon and label in the application's manifest</h3>
+<h3 id="eula">3. Consider adding support for Android Market Licensing</h3>
+
+<p>If you are publishing a paid application through Android Market, consider
+adding support for Android Market Licensing. Licensing lets you control access
+to your application based on whether the current user has purchased it.
+Using Android Market Licensing is optional.
+
+<p>For complete information about Android Market Licensing Service and how to
+use it in your application, see <a
+href="{@docRoot}guide/publishing/licensing.html">Licensing Your
+Applications</a>.</p>
+
+<h3 id="iconlabel">4. Specify an icon and label in the application's manifest</h3>
<p>The icon and label that you specify in an application's manifest are
important because they are displayed to users as your application's icon and
@@ -116,7 +129,7 @@ display the icon and label to users. </p>
<p>As regards the design of your icon, you should try to make it match as much
as possible the style used by the built-in Android applications.</p>
-<h3 id="logging">4. Turn off logging and debugging and clean up data/files</h3>
+<h3 id="logging">5. Turn off logging and debugging and clean up data/files</h3>
<p>For release, you should make sure that debug facilities are turned off and
that debug and other unnecessary data/files are removed from your application
@@ -133,7 +146,7 @@ code.</li>
<h2 id="finalcompile">Before you do the final compile of your application</h2>
-<h3 id="versionapp">5. Version your application</h3>
+<h3 id="versionapp">6. Version your application</h3>
<p>Before you compile your application, you must make sure that you have defined
a version number for your application, specifying an appropriate value for both
@@ -152,7 +165,7 @@ element in the application's manifest file, using appropriate values. </p>
application, see <a href="{@docRoot}guide/publishing/versioning.html">Versioning
Your Applications</a>.</p>
-<h3 id="cryptokey">6. Obtain a suitable cryptographic key</h3>
+<h3 id="cryptokey">7. Obtain a suitable cryptographic key</h3>
<p>If you have read and followed all of the preparation steps up to this point,
your application is compiled and ready for signing. Inside the .apk, the
@@ -173,7 +186,7 @@ elements.</li>
<li>Sign your application for release, later in the preparation process</li>
</ul>
-<h3 id="mapsApiKey">7. Register for a Maps API Key, if your application is using
+<h3 id="mapsApiKey">8. Register for a Maps API Key, if your application is using
MapView elements</h3>
<div class="sidebox-wrapper">
@@ -231,7 +244,7 @@ you can compile your application for release.</p>
<h2 id="post-compile">After compiling your application</h2>
-<h3 id="signapp">8. Sign your application</h3>
+<h3 id="signapp">9. Sign your application</h3>
<p>Sign your application using your private key and then
align it with the {@code zipalign} tool. Signing your application
@@ -239,7 +252,7 @@ correctly is critically important. Please see
<a href="{@docRoot}guide/publishing/app-signing.html">Signing Your
Applications</a> for complete information. </p>
-<h3 id="testapp">9. Test your compiled and signed application</h3>
+<h3 id="testapp">10. Test your compiled and signed application</h3>
<p>Before you release your compiled application, you should thoroughly test it
on the target mobile device (and target network, if possible). In particular,
diff --git a/docs/html/guide/publishing/publishing.jd b/docs/html/guide/publishing/publishing.jd
index 0c087ef..9b470c8 100644
--- a/docs/html/guide/publishing/publishing.jd
+++ b/docs/html/guide/publishing/publishing.jd
@@ -18,7 +18,8 @@ page.title=Publishing Your Applications
<ol>
<li><a href="#overview">Publishing on Android Market</a>
<ol>
- <li><a href="#marketupgrade">Publishing Updates on Android Market</a>
+ <li><a href="#marketupgrade">Publishing Updates on Android Market</a></li>
+ <li><a href="#marketLicensing">Using Android Market Licensing Service</a></li>
<li><a href="#marketintent">Using Intents to Launch the Market Application</a></li>
</ol></li>
<!--
@@ -30,6 +31,7 @@ page.title=Publishing Your Applications
<h2>See also</h2>
<ol>
+<li><a href="{@docRoot}guide/publishing/licensing.html">Licensing Your Applications</a></li>
<li><a href="{@docRoot}guide/publishing/preparing.html">Preparing to Publish</a></li>
</ol>
@@ -59,7 +61,7 @@ the .apk. Your application is now ready for publishing. </p>
<p>The sections below provide information about publishing your Android
application to mobile device users.</p>
-<h2 id="market">Publishing on Android Market</h2>
+<h2 id="overview">Publishing on Android Market</h2>
<p>Android Market is a hosted service that makes it easy for users to find and
download Android applications to their Android-powered devices, and makes it
@@ -121,7 +123,26 @@ certificate do <em>not</em> match those of the existing version, Market will
consider it a new application and will not offer it to users as an update.</p>
+<h3 id="marketLicensing">Using Android Market Licensing Service</h3>
+<p>Android Market offers a licensing service that lets you enforce licensing
+policies for paid applications that you publish through Android Market. With
+Android Market Licensing, your applications can query Android Market at run time
+to obtain their licensing status for the current user, then allow or disallow
+further use as appropriate. Using the service, you can apply a flexible
+licensing policy on an application-by-application basis &mdash; each
+application can enforce its licensing status in the way most appropriate
+for it. </p>
+
+<p>Any application that you publish through Android Market can use the Android
+Market Licensing Service. The service uses no dedicated framework APIs, you can
+add licensing to any legacy application that uses a minimum API level of 3 or
+higher.</p>
+
+<p>For complete information about Android Market Licensing Service and how to
+use it in your application, see <a
+href="{@docRoot}guide/publishing/licensing.html">Licensing Your
+Applications</a>.</p>
<h3 id="marketintent">Using Intents to Launch the Market Application on
diff --git a/docs/html/images/licensing_add_library.png b/docs/html/images/licensing_add_library.png
new file mode 100644
index 0000000..90b4435
--- /dev/null
+++ b/docs/html/images/licensing_add_library.png
Binary files differ
diff --git a/docs/html/images/licensing_arch.png b/docs/html/images/licensing_arch.png
new file mode 100644
index 0000000..ba7484a
--- /dev/null
+++ b/docs/html/images/licensing_arch.png
Binary files differ
diff --git a/docs/html/images/licensing_device_signin.png b/docs/html/images/licensing_device_signin.png
new file mode 100644
index 0000000..a4f5f88
--- /dev/null
+++ b/docs/html/images/licensing_device_signin.png
Binary files differ
diff --git a/docs/html/images/licensing_flow.png b/docs/html/images/licensing_flow.png
new file mode 100644
index 0000000..b33119e
--- /dev/null
+++ b/docs/html/images/licensing_flow.png
Binary files differ
diff --git a/docs/html/images/licensing_gapis_8.png b/docs/html/images/licensing_gapis_8.png
new file mode 100644
index 0000000..43ad262
--- /dev/null
+++ b/docs/html/images/licensing_gapis_8.png
Binary files differ
diff --git a/docs/html/images/licensing_package.png b/docs/html/images/licensing_package.png
new file mode 100644
index 0000000..5da5632
--- /dev/null
+++ b/docs/html/images/licensing_package.png
Binary files differ
diff --git a/docs/html/images/licensing_public_key.png b/docs/html/images/licensing_public_key.png
new file mode 100644
index 0000000..1630209
--- /dev/null
+++ b/docs/html/images/licensing_public_key.png
Binary files differ
diff --git a/docs/html/images/licensing_test_response.png b/docs/html/images/licensing_test_response.png
new file mode 100644
index 0000000..ead2152
--- /dev/null
+++ b/docs/html/images/licensing_test_response.png
Binary files differ
diff --git a/docs/html/resources/faq/commontasks.jd b/docs/html/resources/faq/commontasks.jd
index 2f09b00..9c32e9c 100644
--- a/docs/html/resources/faq/commontasks.jd
+++ b/docs/html/resources/faq/commontasks.jd
@@ -158,7 +158,7 @@ It is not necessary to put external JARs in the assets folder.
<ul>
<li>Create an {@link android.app.Dialog app.Dialog} class </li>
<li>Create an {@link android.app.AlertDialog app.AlertDialog} class </li>
- <li>Set the {@link android.R.style#Theme_Dialog} <em>theme</em> attribute to <code>&#064;android:style/Theme.Dialog</code>
+ <li>Set the {@link android.R.style#Theme_Dialog} <em>theme</em> attribute to <code>&#64;android:style/Theme.Dialog</code>
in your AndroidManifest.xml file. For example:
<pre>&lt;activity class=&quot;AddRssItem&quot; android:label=&quot;Add an item&quot; android:theme=&quot;&#064;android:style/Theme.Dialog&quot;/&gt;</pre></li>
</ul>
diff --git a/include/binder/Parcel.h b/include/binder/Parcel.h
index fd0fc1f..32c9a1d5 100644
--- a/include/binder/Parcel.h
+++ b/include/binder/Parcel.h
@@ -26,11 +26,12 @@
// ---------------------------------------------------------------------------
namespace android {
+class Flattenable;
class IBinder;
+class IPCThreadState;
class ProcessState;
class String8;
class TextOutput;
-class Flattenable;
struct flat_binder_object; // defined in support_p/binder_module.h
@@ -61,10 +62,13 @@ public:
// Parses the RPC header, returning true if the interface name
// in the header matches the expected interface from the caller.
- // If strict_policy_out is non-NULL, the RPC header's StrictMode policy
- // mask is returned.
+ //
+ // Additionally, enforceInterface does part of the work of
+ // propagating the StrictMode policy mask, populating the current
+ // IPCThreadState, which as an optimization may optionally be
+ // passed in.
bool enforceInterface(const String16& interface,
- int32_t* strict_policy_out = NULL) const;
+ IPCThreadState* threadState = NULL) const;
bool checkInterface(IBinder*) const;
void freeData();
diff --git a/include/media/AudioEffect.h b/include/media/AudioEffect.h
index e9ff8a3..c967efb 100644
--- a/include/media/AudioEffect.h
+++ b/include/media/AudioEffect.h
@@ -382,10 +382,10 @@ public:
* See EffectApi.h for details on effect command() function, valid command codes
* and formats.
*/
- virtual status_t command(int32_t cmdCode,
- int32_t cmdSize,
+ virtual status_t command(uint32_t cmdCode,
+ uint32_t cmdSize,
void *cmdData,
- int32_t *replySize,
+ uint32_t *replySize,
void *replyData);
@@ -429,10 +429,10 @@ private:
virtual void enableStatusChanged(bool enabled) {
mEffect->enableStatusChanged(enabled);
}
- virtual void commandExecuted(int cmdCode,
- int cmdSize,
+ virtual void commandExecuted(uint32_t cmdCode,
+ uint32_t cmdSize,
void *pCmdData,
- int replySize,
+ uint32_t replySize,
void *pReplyData) {
mEffect->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
}
@@ -450,7 +450,11 @@ private:
// IEffectClient
void controlStatusChanged(bool controlGranted);
void enableStatusChanged(bool enabled);
- void commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData);
+ void commandExecuted(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t replySize,
+ void *pReplyData);
void binderDied();
diff --git a/include/media/EffectApi.h b/include/media/EffectApi.h
index 8c120e5..16fb43c 100644
--- a/include/media/EffectApi.h
+++ b/include/media/EffectApi.h
@@ -284,10 +284,10 @@ typedef int32_t (*effect_process_t)(effect_interface_t self,
//
////////////////////////////////////////////////////////////////////////////////
typedef int32_t (*effect_command_t)(effect_interface_t self,
- int32_t cmdCode,
- int32_t cmdSize,
+ uint32_t cmdCode,
+ uint32_t cmdSize,
void *pCmdData,
- int32_t *replySize,
+ uint32_t *replySize,
void *pReplyData);
diff --git a/include/media/EffectBassBoostApi.h b/include/media/EffectBassBoostApi.h
index b24a5f4..75f8d78 100644
--- a/include/media/EffectBassBoostApi.h
+++ b/include/media/EffectBassBoostApi.h
@@ -23,9 +23,10 @@
extern "C" {
#endif
-// TODO: include OpenSLES_IID.h instead
+#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_BASSBOOST_ = { 0x0634f220, 0xddd4, 0x11db, 0xa0fc, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_BASSBOOST = &SL_IID_BASSBOOST_;
+#endif //OPENSL_ES_H_
/* enumerated parameter settings for BassBoost effect */
typedef enum
diff --git a/include/media/EffectEnvironmentalReverbApi.h b/include/media/EffectEnvironmentalReverbApi.h
index d490f71..2233e3f 100644
--- a/include/media/EffectEnvironmentalReverbApi.h
+++ b/include/media/EffectEnvironmentalReverbApi.h
@@ -23,9 +23,10 @@
extern "C" {
#endif
-// TODO: include OpenSLES_IID.h instead
+#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_ENVIRONMENTALREVERB_ = { 0xc2e5d5f0, 0x94bd, 0x4763, 0x9cac, { 0x4e, 0x23, 0x4d, 0x6, 0x83, 0x9e } };
const effect_uuid_t * const SL_IID_ENVIRONMENTALREVERB = &SL_IID_ENVIRONMENTALREVERB_;
+#endif //OPENSL_ES_H_
/* enumerated parameter settings for environmental reverb effect */
typedef enum
@@ -45,20 +46,19 @@ typedef enum
REVERB_PARAM_BYPASS
} t_env_reverb_params;
-//t_reverb_properties is equal to SLEnvironmentalReverbSettings defined in OpenSL ES specification.
-typedef struct s_reverb_properties {
+//t_reverb_settings is equal to SLEnvironmentalReverbSettings defined in OpenSL ES specification.
+typedef struct s_reverb_settings {
int16_t roomLevel;
int16_t roomHFLevel;
int32_t decayTime;
int16_t decayHFRatio;
int16_t reflectionsLevel;
int32_t reflectionsDelay;
- int32_t reverbDelay;
int16_t reverbLevel;
+ int32_t reverbDelay;
int16_t diffusion;
int16_t density;
- int16_t padding;
-} t_reverb_properties;
+} __attribute__((packed)) t_reverb_settings;
#if __cplusplus
diff --git a/include/media/EffectEqualizerApi.h b/include/media/EffectEqualizerApi.h
index cb05b32..0492ea0 100644
--- a/include/media/EffectEqualizerApi.h
+++ b/include/media/EffectEqualizerApi.h
@@ -19,8 +19,10 @@
#include <media/EffectApi.h>
-// for the definition of SL_IID_EQUALIZER
-#include "OpenSLES.h"
+#ifndef OPENSL_ES_H_
+static const effect_uuid_t SL_IID_EQUALIZER_ = { 0x0bed4300, 0xddd6, 0x11db, 0x8f34, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
+const effect_uuid_t * const SL_IID_EQUALIZER = &SL_IID_EQUALIZER_;
+#endif //OPENSL_ES_H_
#if __cplusplus
extern "C" {
@@ -37,9 +39,16 @@ typedef enum
EQ_PARAM_GET_BAND, // Gets the band that has the most effect on the given frequency.
EQ_PARAM_CUR_PRESET, // Gets/Sets the current preset.
EQ_PARAM_GET_NUM_OF_PRESETS, // Gets the total number of presets the equalizer supports.
- EQ_PARAM_GET_PRESET_NAME // Gets the preset name based on the index.
+ EQ_PARAM_GET_PRESET_NAME, // Gets the preset name based on the index.
+ EQ_PARAM_PROPERTIES // Gets/Sets all parameters at a time.
} t_equalizer_params;
+//t_equalizer_settings groups all current equalizer setting for backup and restore.
+typedef struct s_equalizer_settings {
+ uint16_t curPreset;
+ uint16_t numBands;
+ uint16_t bandLevels[];
+} t_equalizer_settings;
#if __cplusplus
} // extern "C"
diff --git a/include/media/EffectPresetReverbApi.h b/include/media/EffectPresetReverbApi.h
index 34ffffe..53205bb 100644
--- a/include/media/EffectPresetReverbApi.h
+++ b/include/media/EffectPresetReverbApi.h
@@ -23,10 +23,10 @@
extern "C" {
#endif
-// TODO: include OpenSLES_IID.h instead
-
+#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_PRESETREVERB_ = { 0x47382d60, 0xddd8, 0x11db, 0xbf3a, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_PRESETREVERB = &SL_IID_PRESETREVERB_;
+#endif //OPENSL_ES_H_
/* enumerated parameter settings for preset reverb effect */
typedef enum
diff --git a/include/media/EffectVirtualizerApi.h b/include/media/EffectVirtualizerApi.h
index 601c384..c3d5131 100644
--- a/include/media/EffectVirtualizerApi.h
+++ b/include/media/EffectVirtualizerApi.h
@@ -23,9 +23,10 @@
extern "C" {
#endif
-// TODO: include OpenSLES_IID.h instead
+#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_VIRTUALIZER_ = { 0x37cc2c00, 0xdddd, 0x11db, 0x8577, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_VIRTUALIZER = &SL_IID_VIRTUALIZER_;
+#endif //OPENSL_ES_H_
/* enumerated parameter settings for virtualizer effect */
typedef enum
diff --git a/include/media/EffectVisualizerApi.h b/include/media/EffectVisualizerApi.h
index 1155db8..bef1a4f 100644
--- a/include/media/EffectVisualizerApi.h
+++ b/include/media/EffectVisualizerApi.h
@@ -23,10 +23,11 @@
extern "C" {
#endif
-//TODO replace by openSL ES include when available
+#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_VISUALIZATION_ =
{ 0xe46b26a0, 0xdddd, 0x11db, 0x8afd, { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_VISUALIZATION = &SL_IID_VISUALIZATION_;
+#endif //OPENSL_ES_H_
#define VISUALIZER_CAPTURE_SIZE_MAX 1024 // maximum capture size in samples
#define VISUALIZER_CAPTURE_SIZE_MIN 128 // minimum capture size in samples
diff --git a/include/media/IEffect.h b/include/media/IEffect.h
index 6dad393..ff04869 100644
--- a/include/media/IEffect.h
+++ b/include/media/IEffect.h
@@ -33,7 +33,11 @@ public:
virtual status_t disable() = 0;
- virtual status_t command(int cmdCode, int cmdSize, void *pCmdData, int *pReplySize, void *pReplyData) = 0;
+ virtual status_t command(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *pReplySize,
+ void *pReplyData) = 0;
virtual void disconnect() = 0;
diff --git a/include/media/IEffectClient.h b/include/media/IEffectClient.h
index d22daf8..2f78c98 100644
--- a/include/media/IEffectClient.h
+++ b/include/media/IEffectClient.h
@@ -31,7 +31,11 @@ public:
virtual void controlStatusChanged(bool controlGranted) = 0;
virtual void enableStatusChanged(bool enabled) = 0;
- virtual void commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData) = 0;
+ virtual void commandExecuted(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t replySize,
+ void *pReplyData) = 0;
};
// ----------------------------------------------------------------------------
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index 60babad..18f75df 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -458,13 +458,13 @@ bool Parcel::checkInterface(IBinder* binder) const
}
bool Parcel::enforceInterface(const String16& interface,
- int32_t* strict_policy_out) const
+ IPCThreadState* threadState) const
{
- int32_t strict_policy = readInt32();
- IPCThreadState::self()->setStrictModePolicy(strict_policy);
- if (strict_policy_out != NULL) {
- *strict_policy_out = strict_policy;
+ int32_t strictPolicy = readInt32();
+ if (threadState == NULL) {
+ threadState = IPCThreadState::self();
}
+ threadState->setStrictModePolicy(strictPolicy);
const String16 str(readString16());
if (str == interface) {
return true;
diff --git a/libs/hwui/Android.mk b/libs/hwui/Android.mk
index 172952a..a9714c7 100644
--- a/libs/hwui/Android.mk
+++ b/libs/hwui/Android.mk
@@ -10,6 +10,7 @@ LOCAL_SRC_FILES:= \
Patch.cpp \
PatchCache.cpp \
Program.cpp \
+ ProgramCache.cpp \
TextureCache.cpp
LOCAL_C_INCLUDES += \
diff --git a/libs/hwui/FontRenderer.cpp b/libs/hwui/FontRenderer.cpp
index 14ad7d7..5595ab0 100644
--- a/libs/hwui/FontRenderer.cpp
+++ b/libs/hwui/FontRenderer.cpp
@@ -80,6 +80,21 @@ void Font::drawCachedGlyph(CachedGlyphInfo* glyph, int x, int y) {
nPenX, nPenY - height, 0, u1, v1);
}
+Font::CachedGlyphInfo* Font::getCachedUTFChar(SkPaint* paint, int32_t utfChar) {
+ CachedGlyphInfo* cachedGlyph = mCachedGlyphs.valueFor(utfChar);
+ if (cachedGlyph == NULL) {
+ cachedGlyph = cacheGlyph(paint, utfChar);
+ }
+
+ // Is the glyph still in texture cache?
+ if (!cachedGlyph->mIsValid) {
+ const SkGlyph& skiaGlyph = paint->getUnicharMetrics(utfChar);
+ updateGlyphCache(paint, skiaGlyph, cachedGlyph);
+ }
+
+ return cachedGlyph;
+}
+
void Font::renderUTF(SkPaint* paint, const char* text, uint32_t start, uint32_t len,
int numGlyphs, int x, int y) {
if (numGlyphs == 0 || text == NULL || len == 0) {
@@ -102,16 +117,7 @@ void Font::renderUTF(SkPaint* paint, const char* text, uint32_t start, uint32_t
break;
}
- CachedGlyphInfo* cachedGlyph = mCachedGlyphs.valueFor(utfChar);
- if (cachedGlyph == NULL) {
- cachedGlyph = cacheGlyph(paint, utfChar);
- }
-
- // Is the glyph still in texture cache?
- if (!cachedGlyph->mIsValid) {
- const SkGlyph& skiaGlyph = paint->getUnicharMetrics(utfChar);
- updateGlyphCache(paint, skiaGlyph, cachedGlyph);
- }
+ CachedGlyphInfo* cachedGlyph = getCachedUTFChar(paint, utfChar);
// If it's still not valid, we couldn't cache it, so we shouldn't draw garbage
if (cachedGlyph->mIsValid) {
@@ -340,6 +346,8 @@ void FontRenderer::initTextTexture() {
nextLine += mCacheLines.top()->mMaxHeight;
mCacheLines.push(new CacheTextureLine(mCacheWidth, 24, nextLine, 0));
nextLine += mCacheLines.top()->mMaxHeight;
+ mCacheLines.push(new CacheTextureLine(mCacheWidth, 24, nextLine, 0));
+ nextLine += mCacheLines.top()->mMaxHeight;
mCacheLines.push(new CacheTextureLine(mCacheWidth, 32, nextLine, 0));
nextLine += mCacheLines.top()->mMaxHeight;
mCacheLines.push(new CacheTextureLine(mCacheWidth, 32, nextLine, 0));
@@ -392,6 +400,12 @@ void FontRenderer::checkInit() {
initTextTexture();
initVertexArrayBuffers();
+ // We store a string with letters in a rough frequency of occurrence
+ mLatinPrecache = String16("eisarntolcdugpmhbyfvkwzxjq ");
+ mLatinPrecache += String16("EISARNTOLCDUGPMHBYFVKWZXJQ");
+ mLatinPrecache += String16(",.?!()-+@;:`'");
+ mLatinPrecache += String16("0123456789");
+
mInitialized = true;
}
@@ -484,8 +498,38 @@ void FontRenderer::appendMeshQuad(float x1, float y1, float z1, float u1, float
}
}
-void FontRenderer::setFont(uint32_t fontId, float fontSize) {
+uint32_t FontRenderer::getRemainingCacheCapacity() {
+ uint32_t remainingCapacity = 0;
+ float totalPixels = 0;
+ for(uint32_t i = 0; i < mCacheLines.size(); i ++) {
+ remainingCapacity += (mCacheLines[i]->mMaxWidth - mCacheLines[i]->mCurrentCol);
+ totalPixels += mCacheLines[i]->mMaxWidth;
+ }
+ remainingCapacity = (remainingCapacity * 100) / totalPixels;
+ return remainingCapacity;
+}
+
+void FontRenderer::precacheLatin(SkPaint* paint) {
+ // Remaining capacity is measured in %
+ uint32_t remainingCapacity = getRemainingCacheCapacity();
+ uint32_t precacheIdx = 0;
+ while(remainingCapacity > 25 && precacheIdx < mLatinPrecache.size()) {
+ mCurrentFont->getCachedUTFChar(paint, (int32_t)mLatinPrecache[precacheIdx]);
+ remainingCapacity = getRemainingCacheCapacity();
+ precacheIdx ++;
+ }
+}
+
+void FontRenderer::setFont(SkPaint* paint, uint32_t fontId, float fontSize) {
+ uint32_t currentNumFonts = mActiveFonts.size();
mCurrentFont = Font::create(this, fontId, fontSize);
+
+ const float maxPrecacheFontSize = 40.0f;
+ bool isNewFont = currentNumFonts != mActiveFonts.size();
+
+ if(isNewFont && fontSize <= maxPrecacheFontSize ){
+ precacheLatin(paint);
+ }
}
void FontRenderer::renderText(SkPaint* paint, const Rect* clip, const char *text,
diff --git a/libs/hwui/FontRenderer.h b/libs/hwui/FontRenderer.h
index bacd3aa..2f7a8ba 100644
--- a/libs/hwui/FontRenderer.h
+++ b/libs/hwui/FontRenderer.h
@@ -18,6 +18,7 @@
#define ANDROID_UI_FONT_RENDERER_H
#include <utils/String8.h>
+#include <utils/String16.h>
#include <utils/Vector.h>
#include <utils/KeyedVector.h>
@@ -82,10 +83,12 @@ protected:
void invalidateTextureCache();
- CachedGlyphInfo *cacheGlyph(SkPaint* paint, int32_t glyph);
+ CachedGlyphInfo* cacheGlyph(SkPaint* paint, int32_t glyph);
void updateGlyphCache(SkPaint* paint, const SkGlyph& skiaGlyph, CachedGlyphInfo *glyph);
void drawCachedGlyph(CachedGlyphInfo *glyph, int x, int y);
+ CachedGlyphInfo* getCachedUTFChar(SkPaint* paint, int32_t utfChar);
+
FontRenderer* mState;
uint32_t mFontId;
float mFontSize;
@@ -99,7 +102,7 @@ public:
void init();
void deinit();
- void setFont(uint32_t fontId, float fontSize);
+ void setFont(SkPaint* paint, uint32_t fontId, float fontSize);
void renderText(SkPaint* paint, const Rect* clip, const char *text, uint32_t startIndex,
uint32_t len, int numGlyphs, int x, int y);
@@ -160,6 +163,9 @@ protected:
void checkInit();
+ String16 mLatinPrecache;
+ void precacheLatin(SkPaint* paint);
+
void issueDrawCommand();
void appendMeshQuad(float x1, float y1, float z1, float u1, float v1, float x2, float y2,
float z2, float u2, float v2, float x3, float y3, float z3, float u3, float v3,
@@ -169,6 +175,7 @@ protected:
uint32_t mCacheHeight;
Vector<CacheTextureLine*> mCacheLines;
+ uint32_t getRemainingCacheCapacity();
Font* mCurrentFont;
Vector<Font*> mActiveFonts;
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index d30d718..0ed6276 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -45,32 +45,22 @@ namespace uirenderer {
#define MB(s) s * 1024 * 1024
// Generates simple and textured vertices
-#define SV(x, y) { { x, y } }
#define FV(x, y, u, v) { { x, y }, { u, v } }
///////////////////////////////////////////////////////////////////////////////
// Globals
///////////////////////////////////////////////////////////////////////////////
-static const SimpleVertex gDrawColorVertices[] = {
- SV(0.0f, 0.0f),
- SV(1.0f, 0.0f),
- SV(0.0f, 1.0f),
- SV(1.0f, 1.0f)
-};
-static const GLsizei gDrawColorVertexStride = sizeof(SimpleVertex);
-static const GLsizei gDrawColorVertexCount = 4;
-
// This array is never used directly but used as a memcpy source in the
// OpenGLRenderer constructor
-static const TextureVertex gDrawTextureVertices[] = {
+static const TextureVertex gMeshVertices[] = {
FV(0.0f, 0.0f, 0.0f, 0.0f),
FV(1.0f, 0.0f, 1.0f, 0.0f),
FV(0.0f, 1.0f, 0.0f, 1.0f),
FV(1.0f, 1.0f, 1.0f, 1.0f)
};
-static const GLsizei gDrawTextureVertexStride = sizeof(TextureVertex);
-static const GLsizei gDrawTextureVertexCount = 4;
+static const GLsizei gMeshStride = sizeof(TextureVertex);
+static const GLsizei gMeshCount = 4;
// In this array, the index of each Blender equals the value of the first
// entry. For instance, gBlends[1] == gBlends[SkXfermode::kSrc_Mode]
@@ -143,7 +133,18 @@ OpenGLRenderer::OpenGLRenderer():
mLastTexture = 0;
- memcpy(mDrawTextureVertices, gDrawTextureVertices, sizeof(gDrawTextureVertices));
+ memcpy(mMeshVertices, gMeshVertices, sizeof(gMeshVertices));
+
+ ProgramDescription d;
+ mProgramCache.get(d);
+ d.hasTexture = true;
+ mProgramCache.get(d);
+ d.hasAlpha8Texture = true;
+ d.hasGradient = true;
+ d.hasBitmap = true;
+ d.shadersMode = SkXfermode::kDstOut_Mode;
+ d.colorOp = ProgramDescription::kColorMatrix;
+ mProgramCache.get(d);
}
OpenGLRenderer::~OpenGLRenderer() {
@@ -569,7 +570,7 @@ void OpenGLRenderer::drawText(const char* text, int bytesCount, int count,
// TODO: Implement scale properly
const Rect& clip = mSnapshot->getLocalClip();
- mFontRenderer.setFont(SkTypeface::UniqueID(paint->getTypeface()), paint->getTextSize());
+ mFontRenderer.setFont(paint, SkTypeface::UniqueID(paint->getTypeface()), paint->getTextSize());
mFontRenderer.renderText(paint, &clip, text, 0, bytesCount, count, x, y);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
@@ -650,9 +651,13 @@ void OpenGLRenderer::drawColorRect(float left, float top, float right, float bot
mModelView.scale(right - left, bottom - top, 1.0f);
if (!useProgram(mDrawColorProgram)) {
- const GLvoid* p = &gDrawColorVertices[0].position[0];
+ const GLvoid* vertices = &mMeshVertices[0].position[0];
+ const GLvoid* texCoords = &mMeshVertices[0].texture[0];
+
glVertexAttribPointer(mDrawColorProgram->position, 2, GL_FLOAT, GL_FALSE,
- gDrawColorVertexStride, p);
+ gMeshStride, vertices);
+ glVertexAttribPointer(mDrawColorProgram->texCoords, 2, GL_FLOAT, GL_FALSE,
+ gMeshStride, texCoords);
}
if (!ignoreTransform) {
@@ -664,7 +669,7 @@ void OpenGLRenderer::drawColorRect(float left, float top, float right, float bot
glUniform4f(mDrawColorProgram->color, r, g, b, a);
- glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawColorVertexCount);
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
}
void OpenGLRenderer::drawLinearGradientShader(float left, float top, float right, float bottom,
@@ -717,9 +722,9 @@ void OpenGLRenderer::drawLinearGradientShader(float left, float top, float right
&screenSpace.data[0]);
glVertexAttribPointer(mDrawLinearGradientProgram->position, 2, GL_FLOAT, GL_FALSE,
- gDrawTextureVertexStride, &mDrawTextureVertices[0].position[0]);
+ gMeshStride, &mMeshVertices[0].position[0]);
- glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
}
void OpenGLRenderer::drawBitmapShader(float left, float top, float right, float bottom,
@@ -757,7 +762,7 @@ void OpenGLRenderer::drawBitmapShader(float left, float top, float right, float
resetDrawTextureTexCoords(u1, v1, u2, v2);
drawTextureMesh(left, top, right, bottom, texture->id, alpha, mode, texture->blend,
- &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
+ &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
}
@@ -769,13 +774,13 @@ void OpenGLRenderer::drawTextureRect(float left, float top, float right, float b
getAlphaAndMode(paint, &alpha, &mode);
drawTextureMesh(left, top, right, bottom, texture->id, alpha / 255.0f, mode, texture->blend,
- &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
+ &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
}
void OpenGLRenderer::drawTextureRect(float left, float top, float right, float bottom,
GLuint texture, float alpha, SkXfermode::Mode mode, bool blend) {
drawTextureMesh(left, top, right, bottom, texture, alpha, mode, blend,
- &mDrawTextureVertices[0].position[0], &mDrawTextureVertices[0].texture[0], NULL);
+ &mMeshVertices[0].position[0], &mMeshVertices[0].texture[0], NULL);
}
void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float bottom,
@@ -794,12 +799,12 @@ void OpenGLRenderer::drawTextureMesh(float left, float top, float right, float b
glUniform4f(mDrawTextureProgram->color, alpha, alpha, alpha, alpha);
glVertexAttribPointer(mDrawTextureProgram->position, 2, GL_FLOAT, GL_FALSE,
- gDrawTextureVertexStride, vertices);
+ gMeshStride, vertices);
glVertexAttribPointer(mDrawTextureProgram->texCoords, 2, GL_FLOAT, GL_FALSE,
- gDrawTextureVertexStride, texCoords);
+ gMeshStride, texCoords);
if (!indices) {
- glDrawArrays(GL_TRIANGLE_STRIP, 0, gDrawTextureVertexCount);
+ glDrawArrays(GL_TRIANGLE_STRIP, 0, gMeshCount);
} else {
glDrawElements(GL_TRIANGLES, elementsCount, GL_UNSIGNED_SHORT, indices);
}
@@ -842,7 +847,7 @@ bool OpenGLRenderer::useProgram(const sp<Program>& program) {
}
void OpenGLRenderer::resetDrawTextureTexCoords(float u1, float v1, float u2, float v2) {
- TextureVertex* v = &mDrawTextureVertices[0];
+ TextureVertex* v = &mMeshVertices[0];
TextureVertex::setUV(v++, u1, v1);
TextureVertex::setUV(v++, u2, v1);
TextureVertex::setUV(v++, u1, v2);
diff --git a/libs/hwui/OpenGLRenderer.h b/libs/hwui/OpenGLRenderer.h
index 248c9c3..975be05 100644
--- a/libs/hwui/OpenGLRenderer.h
+++ b/libs/hwui/OpenGLRenderer.h
@@ -41,6 +41,7 @@
#include "PatchCache.h"
#include "Vertex.h"
#include "FontRenderer.h"
+#include "ProgramCache.h"
namespace android {
namespace uirenderer {
@@ -268,7 +269,7 @@ private:
SkXfermode::Mode mode);
/**
- * Resets the texture coordinates stored in mDrawTextureVertices. Setting the values
+ * Resets the texture coordinates stored in mMeshVertices. Setting the values
* back to default is achieved by calling:
*
* resetDrawTextureTexCoords(0.0f, 0.0f, 1.0f, 1.0f);
@@ -337,7 +338,7 @@ private:
sp<DrawLinearGradientProgram> mDrawLinearGradientProgram;
// Used to draw textured quads
- TextureVertex mDrawTextureVertices[4];
+ TextureVertex mMeshVertices[4];
// Current texture state
GLuint mLastTexture;
@@ -372,6 +373,7 @@ private:
TextureCache mTextureCache;
LayerCache mLayerCache;
GradientCache mGradientCache;
+ ProgramCache mProgramCache;
PatchCache mPatchCache;
}; // class OpenGLRenderer
diff --git a/libs/hwui/Program.cpp b/libs/hwui/Program.cpp
index 6e60808..86fc154 100644
--- a/libs/hwui/Program.cpp
+++ b/libs/hwui/Program.cpp
@@ -27,7 +27,6 @@ namespace uirenderer {
#define SHADER_SOURCE(name, source) const char* name = #source
-#include "shaders/drawColor.vert"
#include "shaders/drawColor.frag"
#include "shaders/drawTexture.vert"
@@ -127,7 +126,7 @@ GLuint Program::buildShader(const char* source, GLenum type) {
///////////////////////////////////////////////////////////////////////////////
DrawColorProgram::DrawColorProgram():
- Program(gDrawColorVertexShader, gDrawColorFragmentShader) {
+ Program(gDrawTextureVertexShader, gDrawColorFragmentShader) {
getAttribsAndUniforms();
}
@@ -138,6 +137,7 @@ DrawColorProgram::DrawColorProgram(const char* vertex, const char* fragment):
void DrawColorProgram::getAttribsAndUniforms() {
position = addAttrib("position");
+ texCoords = addAttrib("texCoords");
color = addUniform("color");
transform = addUniform("transform");
}
@@ -154,11 +154,13 @@ void DrawColorProgram::set(const mat4& projectionMatrix, const mat4& modelViewMa
void DrawColorProgram::use() {
Program::use();
glEnableVertexAttribArray(position);
+ glEnableVertexAttribArray(texCoords);
}
void DrawColorProgram::remove() {
Program::remove();
glDisableVertexAttribArray(position);
+ glDisableVertexAttribArray(texCoords);
}
///////////////////////////////////////////////////////////////////////////////
@@ -167,26 +169,21 @@ void DrawColorProgram::remove() {
DrawTextureProgram::DrawTextureProgram():
DrawColorProgram(gDrawTextureVertexShader, gDrawTextureFragmentShader) {
- texCoords = addAttrib("texCoords");
sampler = addUniform("sampler");
}
DrawTextureProgram::DrawTextureProgram(const char* vertex, const char* fragment):
DrawColorProgram(vertex, fragment) {
- texCoords = addAttrib("texCoords");
sampler = addUniform("sampler");
}
void DrawTextureProgram::use() {
DrawColorProgram::use();
- glActiveTexture(GL_TEXTURE0);
glUniform1i(sampler, 0);
- glEnableVertexAttribArray(texCoords);
}
void DrawTextureProgram::remove() {
DrawColorProgram::remove();
- glDisableVertexAttribArray(texCoords);
}
///////////////////////////////////////////////////////////////////////////////
diff --git a/libs/hwui/Program.h b/libs/hwui/Program.h
index 824aa05..2cdd905 100644
--- a/libs/hwui/Program.h
+++ b/libs/hwui/Program.h
@@ -53,6 +53,16 @@ public:
virtual void remove();
/**
+ * Returns the OpenGL name of the specified attribute.
+ */
+ int getAttrib(const char* name);
+
+ /**
+ * Returns the OpenGL name of the specified uniform.
+ */
+ int getUniform(const char* name);
+
+ /**
* Indicates whether this program is currently in use with
* the GL context.
*/
@@ -67,10 +77,6 @@ protected:
* @return The OpenGL name of the attribute.
*/
int addAttrib(const char* name);
- /**
- * Returns the OpenGL name of the specified attribute.
- */
- int getAttrib(const char* name);
/**
* Adds a uniform with the specified name.
@@ -78,10 +84,6 @@ protected:
* @return The OpenGL name of the uniform.
*/
int addUniform(const char* name);
- /**
- * Returns the OpenGL name of the specified uniform.
- */
- int getUniform(const char* name);
private:
/**
@@ -145,6 +147,11 @@ public:
int position;
/**
+ * Name of the texture coordinates attribute.
+ */
+ int texCoords;
+
+ /**
* Name of the color uniform.
*/
int color;
@@ -184,11 +191,6 @@ public:
* Name of the texture sampler uniform.
*/
int sampler;
-
- /**
- * Name of the texture coordinates attribute.
- */
- int texCoords;
};
class DrawTextProgram: public DrawTextureProgram {
diff --git a/libs/hwui/ProgramCache.cpp b/libs/hwui/ProgramCache.cpp
new file mode 100644
index 0000000..5a89eb6
--- /dev/null
+++ b/libs/hwui/ProgramCache.cpp
@@ -0,0 +1,332 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#define LOG_TAG "OpenGLRenderer"
+
+#include <utils/String8.h>
+
+#include "ProgramCache.h"
+
+namespace android {
+namespace uirenderer {
+
+///////////////////////////////////////////////////////////////////////////////
+// Vertex shaders snippets
+///////////////////////////////////////////////////////////////////////////////
+
+// TODO: Implement BitmapShader, implement repeat/mirror for npot
+
+const char* gVS_Header_Attributes =
+ "attribute vec4 position;\n";
+const char* gVS_Header_Attributes_TexCoords =
+ "attribute vec2 texCoords;\n";
+const char* gVS_Header_Uniforms =
+ "uniform mat4 transform;\n";
+const char* gVS_Header_Uniforms_HasGradient =
+ "uniform float gradientLength;\n"
+ "uniform vec2 gradient;\n"
+ "uniform vec2 gradientStart;\n"
+ "uniform mat4 screenSpace;\n";
+const char* gVS_Header_Varyings_HasTexture =
+ "varying vec2 outTexCoords;\n";
+const char* gVS_Header_Varyings_HasBitmap =
+ "varying vec2 outBitmapTexCoords;\n";
+const char* gVS_Header_Varyings_HasGradient =
+ "varying float index;\n";
+const char* gVS_Main =
+ "\nvoid main(void) {\n";
+const char* gVS_Main_OutTexCoords =
+ " outTexCoords = texCoords;\n";
+const char* gVS_Main_OutGradientIndex =
+ " vec4 location = screenSpace * position;\n"
+ " index = dot(location.xy - gradientStart, gradient) * gradientLength;\n";
+const char* gVS_Main_Position =
+ " gl_Position = transform * position;\n";
+const char* gVS_Footer =
+ "}\n\n";
+
+///////////////////////////////////////////////////////////////////////////////
+// Fragment shaders snippets
+///////////////////////////////////////////////////////////////////////////////
+
+const char* gFS_Header =
+ "precision mediump float;\n\n";
+const char* gFS_Uniforms_Color =
+ "uniform vec4 color;\n";
+const char* gFS_Uniforms_TextureSampler =
+ "uniform sampler2D sampler;\n";
+const char* gFS_Uniforms_GradientSampler =
+ "uniform sampler2D gradientSampler;\n";
+const char* gFS_Uniforms_BitmapSampler =
+ "uniform sampler2D bitmapSampler;\n";
+const char* gFS_Uniforms_ColorOp[4] = {
+ // None
+ "",
+ // Matrix
+ "uniform mat4 colorMatrix;\n"
+ "uniform vec4 colorMatrixVector;\n",
+ // Lighting
+ "uniform float lightingMul;\n"
+ "uniform float lightingAdd;\n",
+ // PorterDuff
+ "uniform vec4 colorBLend;\n"
+};
+const char* gFS_Main =
+ "\nvoid main(void) {\n"
+ " vec4 fragColor;\n";
+const char* gFS_Main_FetchColor =
+ " fragColor = color;\n";
+const char* gFS_Main_FetchTexture =
+ " fragColor = color * texture2D(sampler, outTexCoords);\n";
+const char* gFS_Main_FetchA8Texture =
+ " fragColor = color * texture2D(sampler, outTexCoords).a;\n";
+const char* gFS_Main_FetchGradient =
+ " vec4 gradientColor = texture2D(gradientSampler, vec2(index, 0.5));\n";
+const char* gFS_Main_FetchBitmap =
+ " vec4 bitmapColor = texture2D(bitmapSampler, outBitmapTexCoords);\n";
+const char* gFS_Main_BlendShadersBG =
+ " fragColor = blendShaders(bitmapColor, gradientColor)";
+const char* gFS_Main_BlendShadersGB =
+ " fragColor = blendShaders(gradientColor, bitmapColor)";
+const char* gFS_Main_BlendShaders_Modulate =
+ " * fragColor.a;\n";
+const char* gFS_Main_FragColor =
+ " gl_FragColor = fragColor;\n";
+const char* gFS_Main_ApplyColorOp[4] = {
+ // None
+ "",
+ // Matrix
+ " fragColor *= colorMatrix;\n"
+ " fragColor += colorMatrixVector;\n",
+ // Lighting
+ " fragColor *= lightingMul;\n"
+ " fragColor += lightingAdd;\n",
+ // PorterDuff
+ " fragColor = blendColors(colorBlend, fragColor);\n"
+};
+const char* gFS_Footer =
+ "}\n\n";
+
+///////////////////////////////////////////////////////////////////////////////
+// PorterDuff snippets
+///////////////////////////////////////////////////////////////////////////////
+
+const char* gPorterDuff[12] = {
+ // Clear
+ "return vec4(0.0, 0.0, 0.0, 0.0);\n",
+ // Src
+ "return src;\n",
+ // Dst
+ "return dst;\n",
+ // SrcOver
+ "return vec4(src.rgb + (1.0 - src.a) * dst.rgb, src.a + dst.a - src.a * dst.a);\n",
+ // DstOver
+ "return vec4(dst.rgb + (1.0 - dst.a) * src.rgb, src.a + dst.a - src.a * dst.a);\n",
+ // SrcIn
+ "return vec4(src.rgb * dst.a, src.a * dst.a);\n",
+ // DstIn
+ "return vec4(dst.rgb * src.a, src.a * dst.a);\n",
+ // SrcOut
+ "return vec4(src.rgb * (1.0 - dst.a), src.a * (1.0 - dst.a));\n",
+ // DstOut
+ "return vec4(dst.rgb * (1.0 - src.a), dst.a * (1.0 - src.a));\n",
+ // SrcAtop
+ "return vec4(src.rgb * dst.a + (1.0 - src.a) * dst.rgb, dst.a);\n",
+ // DstAtop
+ "return vec4(dst.rgb * src.a + (1.0 - dst.a) * src.rgb, src.a);\n",
+ // Xor
+ "return vec4(src.rgb * (1.0 - dst.a) + (1.0 - src.a) * dst.rgb, "
+ "src.a + dst.a - 2.0 * src.a * dst.a);\n",
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Constructors/destructors
+///////////////////////////////////////////////////////////////////////////////
+
+ProgramCache::ProgramCache() {
+}
+
+ProgramCache::~ProgramCache() {
+ clear();
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Cache management
+///////////////////////////////////////////////////////////////////////////////
+
+void ProgramCache::clear() {
+ size_t count = mCache.size();
+ for (size_t i = 0; i < count; i++) {
+ delete mCache.valueAt(i);
+ }
+ mCache.clear();
+}
+
+Program* ProgramCache::get(const ProgramDescription& description) {
+ programid key = description.key();
+ ssize_t index = mCache.indexOfKey(key);
+ Program* program = NULL;
+ if (index < 0) {
+ PROGRAM_LOGD("Could not find program with key 0x%x", key);
+ program = generateProgram(description, key);
+ mCache.add(key, program);
+ } else {
+ program = mCache.valueAt(index);
+ }
+ return program;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Program generation
+///////////////////////////////////////////////////////////////////////////////
+
+Program* ProgramCache::generateProgram(const ProgramDescription& description, programid key) {
+ String8 vertexShader = generateVertexShader(description);
+ String8 fragmentShader = generateFragmentShader(description);
+
+ Program* program = new Program(vertexShader.string(), fragmentShader.string());
+ return program;
+}
+
+String8 ProgramCache::generateVertexShader(const ProgramDescription& description) {
+ // Add attributes
+ String8 shader(gVS_Header_Attributes);
+ if (description.hasTexture || description.hasBitmap) {
+ shader.append(gVS_Header_Attributes_TexCoords);
+ }
+ // Uniforms
+ shader.append(gVS_Header_Uniforms);
+ if (description.hasGradient) {
+ shader.append(gVS_Header_Uniforms_HasGradient);
+ }
+ // Varyings
+ if (description.hasTexture) {
+ shader.append(gVS_Header_Varyings_HasTexture);
+ }
+ if (description.hasGradient) {
+ shader.append(gVS_Header_Varyings_HasGradient);
+ }
+ if (description.hasBitmap) {
+ shader.append(gVS_Header_Varyings_HasBitmap);
+ }
+
+ // Begin the shader
+ shader.append(gVS_Main); {
+ if (description.hasTexture) {
+ shader.append(gVS_Main_OutTexCoords);
+ }
+ if (description.hasGradient) {
+ shader.append(gVS_Main_OutGradientIndex);
+ }
+ // Output transformed position
+ shader.append(gVS_Main_Position);
+ }
+ // End the shader
+ shader.append(gVS_Footer);
+
+ PROGRAM_LOGD("*** Generated vertex shader:\n\n%s", shader.string());
+
+ return shader;
+}
+
+String8 ProgramCache::generateFragmentShader(const ProgramDescription& description) {
+ // Set the default precision
+ String8 shader(gFS_Header);
+
+ // Varyings
+ if (description.hasTexture) {
+ shader.append(gVS_Header_Varyings_HasTexture);
+ }
+ if (description.hasGradient) {
+ shader.append(gVS_Header_Varyings_HasGradient);
+ }
+ if (description.hasBitmap) {
+ shader.append(gVS_Header_Varyings_HasBitmap);
+ }
+
+
+ // Uniforms
+ shader.append(gFS_Uniforms_Color);
+ if (description.hasTexture) {
+ shader.append(gFS_Uniforms_TextureSampler);
+ }
+ if (description.hasGradient) {
+ shader.append(gFS_Uniforms_GradientSampler);
+ }
+ if (description.hasBitmap) {
+ shader.append(gFS_Uniforms_BitmapSampler);
+ }
+ shader.append(gFS_Uniforms_ColorOp[description.colorOp]);
+
+ // Generate required functions
+ if (description.hasGradient && description.hasBitmap) {
+ generatePorterDuffBlend(shader, "blendShaders", description.shadersMode);
+ }
+ if (description.colorOp == ProgramDescription::kColorBlend) {
+ generatePorterDuffBlend(shader, "blendColors", description.colorMode);
+ }
+
+ // Begin the shader
+ shader.append(gFS_Main); {
+ // Stores the result in fragColor directly
+ if (description.hasTexture) {
+ if (description.hasAlpha8Texture) {
+ shader.append(gFS_Main_FetchA8Texture);
+ } else {
+ shader.append(gFS_Main_FetchTexture);
+ }
+ } else {
+ shader.append(gFS_Main_FetchColor);
+ }
+ if (description.hasGradient) {
+ shader.append(gFS_Main_FetchGradient);
+ }
+ if (description.hasBitmap) {
+ shader.append(gFS_Main_FetchBitmap);
+ }
+ // Case when we have two shaders set
+ if (description.hasGradient && description.hasBitmap) {
+ if (description.isBitmapFirst) {
+ shader.append(gFS_Main_BlendShadersBG);
+ } else {
+ shader.append(gFS_Main_BlendShadersGB);
+ }
+ shader.append(gFS_Main_BlendShaders_Modulate);
+ }
+ // Apply the color op if needed
+ shader.append(gFS_Main_ApplyColorOp[description.colorOp]);
+ // Output the fragment
+ shader.append(gFS_Main_FragColor);
+ }
+ // End the shader
+ shader.append(gFS_Footer);
+
+ PROGRAM_LOGD("*** Generated fragment shader:\n\n%s", shader.string());
+ return shader;
+}
+
+void ProgramCache::generatePorterDuffBlend(String8& shader, const char* name,
+ SkXfermode::Mode mode) {
+ shader.append("\nvec4 ");
+ shader.append(name);
+ shader.append("(vec4 src, vec4 dst) {\n");
+ shader.append(" ");
+ shader.append(gPorterDuff[mode]);
+ shader.append("}\n");
+}
+
+}; // namespace uirenderer
+}; // namespace android
diff --git a/libs/hwui/ProgramCache.h b/libs/hwui/ProgramCache.h
new file mode 100644
index 0000000..7f2f5fa
--- /dev/null
+++ b/libs/hwui/ProgramCache.h
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#ifndef ANDROID_UI_PROGRAM_CACHE_H
+#define ANDROID_UI_PROGRAM_CACHE_H
+
+#include <utils/KeyedVector.h>
+#include <utils/Log.h>
+
+#include <SkXfermode.h>
+
+#include "Program.h"
+
+namespace android {
+namespace uirenderer {
+
+///////////////////////////////////////////////////////////////////////////////
+// Defines
+///////////////////////////////////////////////////////////////////////////////
+
+// Debug
+#define DEBUG_PROGRAM_CACHE 0
+
+// Debug
+#if DEBUG_PROGRAM_CACHE
+ #define PROGRAM_LOGD(...) LOGD(__VA_ARGS__)
+#else
+ #define PROGRAM_LOGD(...)
+#endif
+
+#define PROGRAM_KEY_TEXTURE 0x1
+#define PROGRAM_KEY_A8_TEXTURE 0x2
+#define PROGRAM_KEY_BITMAP 0x4
+#define PROGRAM_KEY_GRADIENT 0x8
+#define PROGRAM_KEY_BITMAP_FIRST 0x10
+#define PROGRAM_KEY_COLOR_MATRIX 0x20
+#define PROGRAM_KEY_COLOR_LIGHTING 0x40
+#define PROGRAM_KEY_COLOR_BLEND 0x80
+
+// Support only the 12 Porter-Duff modes for now
+#define PROGRAM_MAX_XFERMODE 0xC
+#define PROGRAM_XFERMODE_SHADER_SHIFT 24
+#define PROGRAM_XFERMODE_COLOR_OP_SHIFT 20
+
+///////////////////////////////////////////////////////////////////////////////
+// Types
+///////////////////////////////////////////////////////////////////////////////
+
+typedef uint32_t programid;
+
+///////////////////////////////////////////////////////////////////////////////
+// Cache
+///////////////////////////////////////////////////////////////////////////////
+
+/**
+ * Describe the features required for a given program. The features
+ * determine the generation of both the vertex and fragment shaders.
+ * A ProgramDescription must be used in conjunction with a ProgramCache.
+ */
+struct ProgramDescription {
+ enum ColorModifier {
+ kColorNone,
+ kColorMatrix,
+ kColorLighting,
+ kColorBlend
+ };
+
+ ProgramDescription():
+ hasTexture(false), hasAlpha8Texture(false),
+ hasBitmap(false), hasGradient(false), shadersMode(SkXfermode::kClear_Mode),
+ colorOp(kColorNone), colorMode(SkXfermode::kClear_Mode) {
+ }
+
+ // Texturing
+ bool hasTexture;
+ bool hasAlpha8Texture;
+
+ // Shaders
+ bool hasBitmap;
+ bool hasGradient;
+ SkXfermode::Mode shadersMode;
+ bool isBitmapFirst;
+
+ // Color operations
+ int colorOp;
+ SkXfermode::Mode colorMode;
+
+ programid key() const {
+ programid key = 0;
+ if (hasTexture) key |= PROGRAM_KEY_TEXTURE;
+ if (hasAlpha8Texture) key |= PROGRAM_KEY_A8_TEXTURE;
+ if (hasBitmap) key |= PROGRAM_KEY_BITMAP;
+ if (hasGradient) key |= PROGRAM_KEY_GRADIENT;
+ if (isBitmapFirst) key |= PROGRAM_KEY_BITMAP_FIRST;
+ if (hasBitmap && hasGradient) {
+ key |= (shadersMode & PROGRAM_MAX_XFERMODE) << PROGRAM_XFERMODE_SHADER_SHIFT;
+ }
+ switch (colorOp) {
+ case kColorMatrix:
+ key |= PROGRAM_KEY_COLOR_MATRIX;
+ break;
+ case kColorLighting:
+ key |= PROGRAM_KEY_COLOR_LIGHTING;
+ break;
+ case kColorBlend:
+ key |= PROGRAM_KEY_COLOR_BLEND;
+ key |= (colorMode & PROGRAM_MAX_XFERMODE) << PROGRAM_XFERMODE_COLOR_OP_SHIFT;
+ break;
+ case kColorNone:
+ break;
+ }
+ return key;
+ }
+}; // struct ProgramDescription
+
+/**
+ * Generates and caches program. Programs are generated based on
+ * ProgramDescriptions.
+ */
+class ProgramCache {
+public:
+ ProgramCache();
+ ~ProgramCache();
+
+ Program* get(const ProgramDescription& description);
+
+ void clear();
+
+private:
+ Program* generateProgram(const ProgramDescription& description, programid key);
+ String8 generateVertexShader(const ProgramDescription& description);
+ String8 generateFragmentShader(const ProgramDescription& description);
+ void generatePorterDuffBlend(String8& shader, const char* name, SkXfermode::Mode mode);
+
+ KeyedVector<programid, Program*> mCache;
+
+}; // class ProgramCache
+
+}; // namespace uirenderer
+}; // namespace android
+
+#endif // ANDROID_UI_PROGRAM_CACHE_H
diff --git a/libs/hwui/Vertex.h b/libs/hwui/Vertex.h
index ffd0633..1f54086 100644
--- a/libs/hwui/Vertex.h
+++ b/libs/hwui/Vertex.h
@@ -21,14 +21,6 @@ namespace android {
namespace uirenderer {
/**
- * Simple structure to describe a vertex with a position.
- * This is used to draw filled rectangles without a texture.
- */
-struct SimpleVertex {
- float position[2];
-}; // struct SimpleVertex
-
-/**
* Simple structure to describe a vertex with a position and a texture.
*/
struct TextureVertex {
diff --git a/libs/hwui/shaders/drawColor.vert b/libs/hwui/shaders/drawColor.vert
deleted file mode 100644
index 20e2636..0000000
--- a/libs/hwui/shaders/drawColor.vert
+++ /dev/null
@@ -1,11 +0,0 @@
-SHADER_SOURCE(gDrawColorVertexShader,
-
-attribute vec4 position;
-
-uniform mat4 transform;
-
-void main(void) {
- gl_Position = transform * position;
-}
-
-);
diff --git a/libs/hwui/shaders/drawLinearGradient.vert b/libs/hwui/shaders/drawLinearGradient.vert
index f5c669b..d2f857d 100644
--- a/libs/hwui/shaders/drawLinearGradient.vert
+++ b/libs/hwui/shaders/drawLinearGradient.vert
@@ -2,10 +2,10 @@ SHADER_SOURCE(gDrawLinearGradientVertexShader,
attribute vec4 position;
+uniform mat4 transform;
uniform float gradientLength;
uniform vec2 gradient;
uniform vec2 start;
-uniform mat4 transform;
uniform mat4 screenSpace;
varying float index;
diff --git a/libs/rs/rsContext.cpp b/libs/rs/rsContext.cpp
index e897d00..d6df581 100644
--- a/libs/rs/rsContext.cpp
+++ b/libs/rs/rsContext.cpp
@@ -468,8 +468,11 @@ Context::Context(Device *dev, bool isGraphics, bool useDepth)
timerInit();
timerSet(RS_TIMER_INTERNAL);
- LOGV("RS Launching thread(s)");
- mWorkers.mCount = 2;
+ int cpu = sysconf(_SC_NPROCESSORS_ONLN);
+ LOGV("RS Launching thread(s), reported CPU count %i", cpu);
+ if (cpu < 2) cpu = 0;
+
+ mWorkers.mCount = (uint32_t)cpu;
mWorkers.mThreadId = (pthread_t *) calloc(mWorkers.mCount, sizeof(pthread_t));
mWorkers.mNativeThreadId = (pid_t *) calloc(mWorkers.mCount, sizeof(pid_t));
mWorkers.mLaunchSignals = new Signal[mWorkers.mCount];
diff --git a/location/java/android/location/Country.aidl b/location/java/android/location/Country.aidl
new file mode 100644
index 0000000..c83d645
--- /dev/null
+++ b/location/java/android/location/Country.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2010, 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.
+ */
+
+package android.location;
+
+parcelable Country; \ No newline at end of file
diff --git a/location/java/android/location/Country.java b/location/java/android/location/Country.java
new file mode 100755
index 0000000..3c05403
--- /dev/null
+++ b/location/java/android/location/Country.java
@@ -0,0 +1,161 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package android.location;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/**
+ * This class wraps the country information.
+ *
+ * @hide
+ */
+public class Country implements Parcelable {
+ /**
+ * The country code came from the mobile network
+ */
+ public static final int COUNTRY_SOURCE_NETWORK = 0;
+
+ /**
+ * The country code came from the location service
+ */
+ public static final int COUNTRY_SOURCE_LOCATION = 1;
+
+ /**
+ * The country code was read from the SIM card
+ */
+ public static final int COUNTRY_SOURCE_SIM = 2;
+
+ /**
+ * The country code came from the system locale setting
+ */
+ public static final int COUNTRY_SOURCE_LOCALE = 3;
+
+ /**
+ * The ISO 3166-1 two letters country code.
+ */
+ private final String mCountryIso;
+
+ /**
+ * Where the country code came from.
+ */
+ private final int mSource;
+
+ private int mHashCode;
+ /**
+ *
+ * @param countryIso the ISO 3166-1 two letters country code.
+ * @param source where the countryIso came from, could be one of below
+ * values
+ * <p>
+ * <ul>
+ * <li>{@link #COUNTRY_SOURCE_NETWORK}</li>
+ * <li>{@link #COUNTRY_SOURCE_LOCATION}</li>
+ * <li>{@link #COUNTRY_SOURCE_SIM}</li>
+ * <li>{@link #COUNTRY_SOURCE_LOCALE}</li>
+ * </ul>
+ */
+ public Country(final String countryIso, final int source) {
+ if (countryIso == null || source < COUNTRY_SOURCE_NETWORK
+ || source > COUNTRY_SOURCE_LOCALE) {
+ throw new IllegalArgumentException();
+ }
+ mCountryIso = countryIso.toLowerCase();
+ mSource = source;
+ }
+
+ public Country(Country country) {
+ mCountryIso = country.mCountryIso;
+ mSource = country.mSource;
+ }
+
+ /**
+ * @return the ISO 3166-1 two letters country code
+ */
+ public final String getCountryIso() {
+ return mCountryIso;
+ }
+
+ /**
+ * @return where the country code came from, could be one of below values
+ * <p>
+ * <ul>
+ * <li>{@link #COUNTRY_SOURCE_NETWORK}</li>
+ * <li>{@link #COUNTRY_SOURCE_LOCATION}</li>
+ * <li>{@link #COUNTRY_SOURCE_SIM}</li>
+ * <li>{@link #COUNTRY_SOURCE_LOCALE}</li>
+ * </ul>
+ */
+ public final int getSource() {
+ return mSource;
+ }
+
+ public static final Parcelable.Creator<Country> CREATOR = new Parcelable.Creator<Country>() {
+ public Country createFromParcel(Parcel in) {
+ return new Country(in.readString(), in.readInt());
+ }
+
+ public Country[] newArray(int size) {
+ return new Country[size];
+ }
+ };
+
+ public int describeContents() {
+ return 0;
+ }
+
+ public void writeToParcel(Parcel parcel, int flags) {
+ parcel.writeString(mCountryIso);
+ parcel.writeInt(mSource);
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if (object == this) {
+ return true;
+ }
+ if (object instanceof Country) {
+ Country c = (Country) object;
+ return mCountryIso.equals(c.getCountryIso()) && mSource == c.getSource();
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ int hash = mHashCode;
+ if (hash == 0) {
+ hash = 17;
+ hash = hash * 13 + mCountryIso.hashCode();
+ hash = hash * 13 + mSource;
+ mHashCode = hash;
+ }
+ return mHashCode;
+ }
+
+ /**
+ * Compare the specified country to this country object ignoring the mSource
+ * field, return true if the countryIso fields are equal
+ *
+ * @param country the country to compare
+ * @return true if the specified country's countryIso field is equal to this
+ * country's, false otherwise.
+ */
+ public boolean equalsIgnoreSource(Country country) {
+ return country != null && mCountryIso.equals(country.getCountryIso());
+ }
+}
diff --git a/location/java/android/location/CountryDetector.java b/location/java/android/location/CountryDetector.java
new file mode 100644
index 0000000..0b780ce
--- /dev/null
+++ b/location/java/android/location/CountryDetector.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package android.location;
+
+import java.util.HashMap;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.util.Log;
+
+/**
+ * This class provides access to the system country detector service. This
+ * service allows applications to obtain the country that the user is in.
+ * <p>
+ * The country will be detected in order of reliability, like
+ * <ul>
+ * <li>Mobile network</li>
+ * <li>Location</li>
+ * <li>SIM's country</li>
+ * <li>Phone's locale</li>
+ * </ul>
+ * <p>
+ * Call the {@link #detectCountry()} to get the available country immediately.
+ * <p>
+ * To be notified of the future country change, use the
+ * {@link #addCountryListener}
+ * <p>
+ * <p>
+ * You do not instantiate this class directly; instead, retrieve it through
+ * {@link android.content.Context#getSystemService
+ * Context.getSystemService(Context.COUNTRY_DETECTOR)}.
+ * <p>
+ * Both ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permissions are needed.
+ *
+ * @hide
+ */
+public class CountryDetector {
+
+ /**
+ * The class to wrap the ICountryListener.Stub and CountryListener objects
+ * together. The CountryListener will be notified through the specific
+ * looper once the country changed and detected.
+ */
+ private final static class ListenerTransport extends ICountryListener.Stub {
+
+ private final CountryListener mListener;
+
+ private final Handler mHandler;
+
+ public ListenerTransport(CountryListener listener, Looper looper) {
+ mListener = listener;
+ if (looper != null) {
+ mHandler = new Handler(looper);
+ } else {
+ mHandler = new Handler();
+ }
+ }
+
+ public void onCountryDetected(final Country country) {
+ mHandler.post(new Runnable() {
+ public void run() {
+ mListener.onCountryDetected(country);
+ }
+ });
+ }
+ }
+
+ private final static String TAG = "CountryDetector";
+ private final ICountryDetector mService;
+ private final HashMap<CountryListener, ListenerTransport> mListeners;
+
+ /**
+ * @hide - hide this constructor because it has a parameter of type
+ * ICountryDetector, which is a system private class. The right way to
+ * create an instance of this class is using the factory
+ * Context.getSystemService.
+ */
+ public CountryDetector(ICountryDetector service) {
+ mService = service;
+ mListeners = new HashMap<CountryListener, ListenerTransport>();
+ }
+
+ /**
+ * Start detecting the country that the user is in.
+ *
+ * @return the country if it is available immediately, otherwise null will
+ * be returned.
+ */
+ public Country detectCountry() {
+ try {
+ return mService.detectCountry();
+ } catch (RemoteException e) {
+ Log.e(TAG, "detectCountry: RemoteException", e);
+ return null;
+ }
+ }
+
+ /**
+ * Add a listener to receive the notification when the country is detected
+ * or changed.
+ *
+ * @param listener will be called when the country is detected or changed.
+ * @param looper a Looper object whose message queue will be used to
+ * implement the callback mechanism. If looper is null then the
+ * callbacks will be called on the main thread.
+ */
+ public void addCountryListener(CountryListener listener, Looper looper) {
+ synchronized (mListeners) {
+ if (!mListeners.containsKey(listener)) {
+ ListenerTransport transport = new ListenerTransport(listener, looper);
+ try {
+ mService.addCountryListener(transport);
+ mListeners.put(listener, transport);
+ } catch (RemoteException e) {
+ Log.e(TAG, "addCountryListener: RemoteException", e);
+ }
+ }
+ }
+ }
+
+ /**
+ * Remove the listener
+ */
+ public void removeCountryListener(CountryListener listener) {
+ synchronized (mListeners) {
+ ListenerTransport transport = mListeners.get(listener);
+ if (transport != null) {
+ try {
+ mListeners.remove(listener);
+ mService.removeCountryListener(transport);
+ } catch (RemoteException e) {
+ Log.e(TAG, "removeCountryListener: RemoteException", e);
+ }
+ }
+ }
+ }
+}
diff --git a/location/java/android/location/CountryListener.java b/location/java/android/location/CountryListener.java
new file mode 100644
index 0000000..e36db41
--- /dev/null
+++ b/location/java/android/location/CountryListener.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package android.location;
+
+/**
+ * The listener for receiving the notification when the country is detected or
+ * changed
+ *
+ * @hide
+ */
+public interface CountryListener {
+ /**
+ * @param country the changed or detected country.
+ */
+ void onCountryDetected(Country country);
+}
diff --git a/location/java/android/location/ICountryDetector.aidl b/location/java/android/location/ICountryDetector.aidl
new file mode 100644
index 0000000..6eaf07c
--- /dev/null
+++ b/location/java/android/location/ICountryDetector.aidl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2010, 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.
+ */
+
+package android.location;
+
+import android.location.Country;
+import android.location.ICountryListener;
+
+/**
+ * The API for detecting the country where the user is.
+ *
+ * {@hide}
+ */
+interface ICountryDetector
+{
+ /**
+ * Start detecting the country that the user is in.
+ * @return the country if it is available immediately, otherwise null will be returned.
+ */
+ Country detectCountry();
+
+ /**
+ * Add a listener to receive the notification when the country is detected or changed.
+ */
+ void addCountryListener(in ICountryListener listener);
+
+ /**
+ * Remove the listener
+ */
+ void removeCountryListener(in ICountryListener listener);
+} \ No newline at end of file
diff --git a/location/java/android/location/ICountryListener.aidl b/location/java/android/location/ICountryListener.aidl
new file mode 100644
index 0000000..76ecb13
--- /dev/null
+++ b/location/java/android/location/ICountryListener.aidl
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2010, 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.
+ */
+
+package android.location;
+
+import android.location.Country;
+/**
+ * {@hide}
+ */
+oneway interface ICountryListener
+{
+ void onCountryDetected(in Country country);
+}
diff --git a/location/tests/locationtests/src/android/location/CountryTester.java b/location/tests/locationtests/src/android/location/CountryTester.java
new file mode 100644
index 0000000..9802d5a
--- /dev/null
+++ b/location/tests/locationtests/src/android/location/CountryTester.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package android.location;
+
+import android.test.AndroidTestCase;
+
+public class CountryTester extends AndroidTestCase {
+ public void testCountryEquals() {
+ Country countryA = new Country("US", Country.COUNTRY_SOURCE_NETWORK);
+ Country countryB = new Country("US", Country.COUNTRY_SOURCE_LOCALE);
+ Country countryC = new Country("CN", Country.COUNTRY_SOURCE_LOCALE);
+ Country countryD = new Country("us", Country.COUNTRY_SOURCE_NETWORK);
+ assertTrue(countryA.equalsIgnoreSource(countryB));
+ assertFalse(countryA.equalsIgnoreSource(countryC));
+ assertFalse(countryA.equals(countryC));
+ assertTrue(countryA.equals(countryD));
+ assertTrue(countryA.hashCode() == countryD.hashCode());
+ }
+}
diff --git a/media/java/android/media/BassBoost.java b/media/java/android/media/BassBoost.java
index ef4ce05..75c2c88 100644
--- a/media/java/android/media/BassBoost.java
+++ b/media/java/android/media/BassBoost.java
@@ -19,17 +19,19 @@ package android.media;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
+import android.media.AudioEffect;
import android.os.Bundle;
import android.util.Log;
+
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
+import java.util.StringTokenizer;
-import android.media.AudioEffect;
/**
* Bass boost is an audio effect to boost or amplify low frequencies of the sound. It is comparable
- * to an simple equalizer but limited to one band amplification in the low frequency range.
+ * to a simple equalizer but limited to one band amplification in the low frequency range.
* <p>An application creates a BassBoost object to instantiate and control a bass boost engine
* in the audio framework.
* <p>The methods, parameter types and units exposed by the BassBoost implementation are directly
@@ -210,4 +212,82 @@ public class BassBoost extends AudioEffect {
}
}
}
+
+ /**
+ * The Settings class regroups all bass boost parameters. It is used in
+ * conjuntion with getProperties() and setProperties() methods to backup and restore
+ * all parameters in a single call.
+ */
+ public static class Settings {
+ public short strength;
+
+ public Settings() {
+ }
+
+ /**
+ * Settings class constructor from a key=value; pairs formatted string. The string is
+ * typically returned by Settings.toString() method.
+ * @throws IllegalArgumentException if the string is not correctly formatted.
+ */
+ public Settings(String settings) {
+ StringTokenizer st = new StringTokenizer(settings, "=;");
+ int tokens = st.countTokens();
+ if (st.countTokens() != 3) {
+ throw new IllegalArgumentException("settings: " + settings);
+ }
+ String key = st.nextToken();
+ if (!key.equals("BassBoost")) {
+ throw new IllegalArgumentException(
+ "invalid settings for BassBoost: " + key);
+ }
+ try {
+ key = st.nextToken();
+ if (!key.equals("strength")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ strength = Short.parseShort(st.nextToken());
+ } catch (NumberFormatException nfe) {
+ throw new IllegalArgumentException("invalid value for key: " + key);
+ }
+ }
+
+ @Override
+ public String toString() {
+ String str = new String (
+ "BassBoost"+
+ ";strength="+Short.toString(strength)
+ );
+ return str;
+ }
+ };
+
+
+ /**
+ * Gets the bass boost properties. This method is useful when a snapshot of current
+ * bass boost settings must be saved by the application.
+ * @return a BassBoost.Settings object containing all current parameters values
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public BassBoost.Settings getProperties()
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ Settings settings = new Settings();
+ short[] value = new short[1];
+ checkStatus(getParameter(PARAM_STRENGTH, value));
+ settings.strength = value[0];
+ return settings;
+ }
+
+ /**
+ * Sets the bass boost properties. This method is useful when bass boost settings have to
+ * be applied from a previous backup.
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public void setProperties(BassBoost.Settings settings)
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ checkStatus(setParameter(PARAM_STRENGTH, settings.strength));
+ }
}
diff --git a/media/java/android/media/EnvironmentalReverb.java b/media/java/android/media/EnvironmentalReverb.java
index 88230fc..3cc8452 100644
--- a/media/java/android/media/EnvironmentalReverb.java
+++ b/media/java/android/media/EnvironmentalReverb.java
@@ -19,12 +19,13 @@ package android.media;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
+import android.media.AudioEffect;
import android.os.Bundle;
import android.util.Log;
+
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
-
-import android.media.AudioEffect;
+import java.util.StringTokenizer;
/**
* A sound generated within a room travels in many directions. The listener first hears the
@@ -107,6 +108,9 @@ public class EnvironmentalReverb extends AudioEffect {
*/
public static final int PARAM_DENSITY = 9;
+ // used by setProperties()/getProperties
+ private static final int PARAM_PROPERTIES = 10;
+
/**
* Registered listener for parameter changes
*/
@@ -142,7 +146,6 @@ public class EnvironmentalReverb extends AudioEffect {
public EnvironmentalReverb(int priority, int audioSession)
throws IllegalArgumentException, UnsupportedOperationException, RuntimeException {
super(EFFECT_TYPE_ENV_REVERB, EFFECT_TYPE_NULL, priority, audioSession);
- Log.e(TAG, "contructor");
}
/**
@@ -501,4 +504,169 @@ public class EnvironmentalReverb extends AudioEffect {
}
}
}
+
+ /**
+ * The Settings class regroups all environmental reverb parameters. It is used in
+ * conjuntion with getProperties() and setProperties() methods to backup and restore
+ * all parameters in a single call.
+ */
+ public static class Settings {
+ public short roomLevel;
+ public short roomHFLevel;
+ public int decayTime;
+ public short decayHFRatio;
+ public short reflectionsLevel;
+ public int reflectionsDelay;
+ public short reverbLevel;
+ public int reverbDelay;
+ public short diffusion;
+ public short density;
+
+ public Settings() {
+ }
+
+ /**
+ * Settings class constructor from a key=value; pairs formatted string. The string is
+ * typically returned by Settings.toString() method.
+ * @throws IllegalArgumentException if the string is not correctly formatted.
+ */
+ public Settings(String settings) {
+ StringTokenizer st = new StringTokenizer(settings, "=;");
+ int tokens = st.countTokens();
+ if (st.countTokens() != 21) {
+ throw new IllegalArgumentException("settings: " + settings);
+ }
+ String key = st.nextToken();
+ if (!key.equals("EnvironmentalReverb")) {
+ throw new IllegalArgumentException(
+ "invalid settings for EnvironmentalReverb: " + key);
+ }
+
+ try {
+ key = st.nextToken();
+ if (!key.equals("roomLevel")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ roomLevel = Short.parseShort(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("roomHFLevel")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ roomHFLevel = Short.parseShort(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("decayTime")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ decayTime = Integer.parseInt(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("decayHFRatio")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ decayHFRatio = Short.parseShort(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("reflectionsLevel")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ reflectionsLevel = Short.parseShort(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("reflectionsDelay")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ reflectionsDelay = Integer.parseInt(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("reverbLevel")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ reverbLevel = Short.parseShort(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("reverbDelay")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ reverbDelay = Integer.parseInt(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("diffusion")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ diffusion = Short.parseShort(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("density")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ density = Short.parseShort(st.nextToken());
+ } catch (NumberFormatException nfe) {
+ throw new IllegalArgumentException("invalid value for key: " + key);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return new String (
+ "EnvironmentalReverb"+
+ ";roomLevel="+Short.toString(roomLevel)+
+ ";roomHFLevel="+Short.toString(roomHFLevel)+
+ ";decayTime="+Integer.toString(decayTime)+
+ ";decayHFRatio="+Short.toString(decayHFRatio)+
+ ";reflectionsLevel="+Short.toString(reflectionsLevel)+
+ ";reflectionsDelay="+Integer.toString(reflectionsDelay)+
+ ";reverbLevel="+Short.toString(reverbLevel)+
+ ";reverbDelay="+Integer.toString(reverbDelay)+
+ ";diffusion="+Short.toString(diffusion)+
+ ";density="+Short.toString(density)
+ );
+ }
+ };
+
+ // Keep this in sync with sizeof(s_reverb_settings) defined in
+ // frameworks/base/include/media/EffectEnvironmentalReverbApi.h
+ static private int PROPERTY_SIZE = 26;
+
+ /**
+ * Gets the environmental reverb properties. This method is useful when a snapshot of current
+ * reverb settings must be saved by the application.
+ * @return an EnvironmentalReverb.Settings object containing all current parameters values
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public EnvironmentalReverb.Settings getProperties()
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ byte[] param = new byte[PROPERTY_SIZE];
+ checkStatus(getParameter(PARAM_PROPERTIES, param));
+ Settings settings = new Settings();
+ settings.roomLevel = byteArrayToShort(param, 0);
+ settings.roomHFLevel = byteArrayToShort(param, 2);
+ settings.decayTime = byteArrayToInt(param, 4);
+ settings.decayHFRatio = byteArrayToShort(param, 8);
+ settings.reflectionsLevel = byteArrayToShort(param, 10);
+ settings.reflectionsDelay = byteArrayToInt(param, 12);
+ settings.reverbLevel = byteArrayToShort(param, 16);
+ settings.reverbDelay = byteArrayToInt(param, 18);
+ settings.diffusion = byteArrayToShort(param, 22);
+ settings.density = byteArrayToShort(param, 24);
+ return settings;
+ }
+
+ /**
+ * Sets the environmental reverb properties. This method is useful when reverb settings have to
+ * be applied from a previous backup.
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public void setProperties(EnvironmentalReverb.Settings settings)
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+
+ byte[] param = concatArrays(shortToByteArray(settings.roomLevel),
+ shortToByteArray(settings.roomHFLevel),
+ intToByteArray(settings.decayTime),
+ shortToByteArray(settings.decayHFRatio),
+ shortToByteArray(settings.reflectionsLevel),
+ intToByteArray(settings.reflectionsDelay),
+ shortToByteArray(settings.reverbLevel),
+ intToByteArray(settings.reverbDelay),
+ shortToByteArray(settings.diffusion),
+ shortToByteArray(settings.density));
+
+ checkStatus(setParameter(PARAM_PROPERTIES, param));
+ }
}
diff --git a/media/java/android/media/Equalizer.java b/media/java/android/media/Equalizer.java
index 082f694..21c37bb 100644
--- a/media/java/android/media/Equalizer.java
+++ b/media/java/android/media/Equalizer.java
@@ -19,13 +19,15 @@ package android.media;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
+import android.media.AudioEffect;
import android.os.Bundle;
import android.util.Log;
+
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
+import java.util.StringTokenizer;
-import android.media.AudioEffect;
/**
* An Equalizer is used to alter the frequency response of a particular music source or of the main
@@ -87,12 +89,19 @@ public class Equalizer extends AudioEffect {
* Request preset name. Parameter ID for OnParameterChangeListener
*/
public static final int PARAM_GET_PRESET_NAME = 8;
+ // used by setProperties()/getProperties
+ private static final int PARAM_PROPERTIES = 9;
/**
* maximum size for perset name
*/
public static final int PARAM_STRING_SIZE_MAX = 32;
/**
+ * Number of bands implemented by Equalizer engine
+ */
+ private short mNumBands = 0;
+
+ /**
* Number of presets implemented by Equalizer engine
*/
private int mNumPresets;
@@ -136,6 +145,8 @@ public class Equalizer extends AudioEffect {
UnsupportedOperationException, RuntimeException {
super(EFFECT_TYPE_EQUALIZER, EFFECT_TYPE_NULL, priority, audioSession);
+ getNumberOfBands();
+
mNumPresets = (int)getNumberOfPresets();
if (mNumPresets != 0) {
@@ -150,7 +161,6 @@ public class Equalizer extends AudioEffect {
while (value[length] != 0) length++;
try {
mPresetNames[i] = new String(value, 0, length, "ISO-8859-1");
- Log.e(TAG, "preset #: "+i+" name: "+mPresetNames[i]+" length: "+length);
} catch (java.io.UnsupportedEncodingException e) {
Log.e(TAG, "preset name decode error");
}
@@ -167,11 +177,15 @@ public class Equalizer extends AudioEffect {
*/
public short getNumberOfBands()
throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ if (mNumBands != 0) {
+ return mNumBands;
+ }
int[] param = new int[1];
param[0] = PARAM_NUM_BANDS;
short[] value = new short[1];
checkStatus(getParameter(param, value));
- return value[0];
+ mNumBands = value[0];
+ return mNumBands;
}
/**
@@ -440,4 +454,120 @@ public class Equalizer extends AudioEffect {
}
}
+ /**
+ * The Settings class regroups all equalizer parameters. It is used in
+ * conjuntion with getProperties() and setProperties() methods to backup and restore
+ * all parameters in a single call.
+ */
+ public static class Settings {
+ public short curPreset;
+ public short numBands = 0;
+ public short[] bandLevels = null;
+
+ public Settings() {
+ }
+
+ /**
+ * Settings class constructor from a key=value; pairs formatted string. The string is
+ * typically returned by Settings.toString() method.
+ * @throws IllegalArgumentException if the string is not correctly formatted.
+ */
+ public Settings(String settings) {
+ StringTokenizer st = new StringTokenizer(settings, "=;");
+ int tokens = st.countTokens();
+ if (st.countTokens() < 5) {
+ throw new IllegalArgumentException("settings: " + settings);
+ }
+ String key = st.nextToken();
+ if (!key.equals("Equalizer")) {
+ throw new IllegalArgumentException(
+ "invalid settings for Equalizer: " + key);
+ }
+ try {
+ key = st.nextToken();
+ if (!key.equals("curPreset")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ curPreset = Short.parseShort(st.nextToken());
+ key = st.nextToken();
+ if (!key.equals("numBands")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ numBands = Short.parseShort(st.nextToken());
+ if (st.countTokens() != numBands*2) {
+ throw new IllegalArgumentException("settings: " + settings);
+ }
+ bandLevels = new short[numBands];
+ for (int i = 0; i < numBands; i++) {
+ key = st.nextToken();
+ if (!key.equals("band"+(i+1)+"Level")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ bandLevels[i] = Short.parseShort(st.nextToken());
+ }
+ } catch (NumberFormatException nfe) {
+ throw new IllegalArgumentException("invalid value for key: " + key);
+ }
+ }
+
+ @Override
+ public String toString() {
+
+ String str = new String (
+ "Equalizer"+
+ ";curPreset="+Short.toString(curPreset)+
+ ";numBands="+Short.toString(numBands)
+ );
+ for (int i = 0; i < numBands; i++) {
+ str = str.concat(";band"+(i+1)+"Level="+Short.toString(bandLevels[i]));
+ }
+ return str;
+ }
+ };
+
+
+ /**
+ * Gets the equalizer properties. This method is useful when a snapshot of current
+ * equalizer settings must be saved by the application.
+ * @return an Equalizer.Settings object containing all current parameters values
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public Equalizer.Settings getProperties()
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ byte[] param = new byte[4 + mNumBands * 2];
+ checkStatus(getParameter(PARAM_PROPERTIES, param));
+ Settings settings = new Settings();
+ settings.curPreset = byteArrayToShort(param, 0);
+ settings.numBands = byteArrayToShort(param, 2);
+ settings.bandLevels = new short[mNumBands];
+ for (int i = 0; i < mNumBands; i++) {
+ settings.bandLevels[i] = byteArrayToShort(param, 4 + 2*i);
+ }
+ return settings;
+ }
+
+ /**
+ * Sets the equalizer properties. This method is useful when equalizer settings have to
+ * be applied from a previous backup.
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public void setProperties(Equalizer.Settings settings)
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ if (settings.numBands != settings.bandLevels.length ||
+ settings.numBands != mNumBands) {
+ throw new IllegalArgumentException("settings invalid band count: " +settings.numBands);
+ }
+
+ byte[] param = concatArrays(shortToByteArray(settings.curPreset),
+ shortToByteArray(mNumBands));
+ for (int i = 0; i < mNumBands; i++) {
+ param = concatArrays(param,
+ shortToByteArray(settings.bandLevels[i]));
+ }
+ checkStatus(setParameter(PARAM_PROPERTIES, param));
+ }
}
diff --git a/media/java/android/media/MtpClient.java b/media/java/android/media/MtpClient.java
index 0fe9bb4..1aebcb8 100644
--- a/media/java/android/media/MtpClient.java
+++ b/media/java/android/media/MtpClient.java
@@ -16,6 +16,7 @@
package android.media;
+import android.os.ParcelFileDescriptor;
import android.util.Log;
/**
@@ -64,6 +65,11 @@ public class MtpClient {
return native_get_storage_id(deviceID, objectID);
}
+ // create a file descriptor for reading the contents of an object over MTP
+ public ParcelFileDescriptor openFile(int deviceID, int objectID) {
+ return native_open_file(deviceID, objectID);
+ }
+
public interface Listener {
// called when a new MTP device has been discovered
void deviceAdded(int id);
@@ -94,4 +100,5 @@ public class MtpClient {
private native boolean native_delete_object(int deviceID, int objectID);
private native int native_get_parent(int deviceID, int objectID);
private native int native_get_storage_id(int deviceID, int objectID);
+ private native ParcelFileDescriptor native_open_file(int deviceID, int objectID);
}
diff --git a/media/java/android/media/PresetReverb.java b/media/java/android/media/PresetReverb.java
index 83a01a4..c7d7037 100644
--- a/media/java/android/media/PresetReverb.java
+++ b/media/java/android/media/PresetReverb.java
@@ -19,12 +19,14 @@ package android.media;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
+import android.media.AudioEffect;
import android.os.Bundle;
import android.util.Log;
+
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
+import java.util.StringTokenizer;
-import android.media.AudioEffect;
/**
* A sound generated within a room travels in many directions. The listener first hears the
@@ -116,7 +118,6 @@ public class PresetReverb extends AudioEffect {
public PresetReverb(int priority, int audioSession)
throws IllegalArgumentException, UnsupportedOperationException, RuntimeException {
super(EFFECT_TYPE_PRESET_REVERB, EFFECT_TYPE_NULL, priority, audioSession);
- Log.e(TAG, "contructor");
}
/**
@@ -144,10 +145,8 @@ public class PresetReverb extends AudioEffect {
*/
public short getPreset()
throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
- int[] param = new int[1];
- param[0] = PARAM_PRESET;
short[] value = new short[1];
- checkStatus(getParameter(param, value));
+ checkStatus(getParameter(PARAM_PRESET, value));
return value[0];
}
@@ -216,4 +215,82 @@ public class PresetReverb extends AudioEffect {
}
}
}
+
+ /**
+ * The Settings class regroups all preset reverb parameters. It is used in
+ * conjuntion with getProperties() and setProperties() methods to backup and restore
+ * all parameters in a single call.
+ */
+ public static class Settings {
+ public short preset;
+
+ public Settings() {
+ }
+
+ /**
+ * Settings class constructor from a key=value; pairs formatted string. The string is
+ * typically returned by Settings.toString() method.
+ * @throws IllegalArgumentException if the string is not correctly formatted.
+ */
+ public Settings(String settings) {
+ StringTokenizer st = new StringTokenizer(settings, "=;");
+ int tokens = st.countTokens();
+ if (st.countTokens() != 3) {
+ throw new IllegalArgumentException("settings: " + settings);
+ }
+ String key = st.nextToken();
+ if (!key.equals("PresetReverb")) {
+ throw new IllegalArgumentException(
+ "invalid settings for PresetReverb: " + key);
+ }
+ try {
+ key = st.nextToken();
+ if (!key.equals("preset")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ preset = Short.parseShort(st.nextToken());
+ } catch (NumberFormatException nfe) {
+ throw new IllegalArgumentException("invalid value for key: " + key);
+ }
+ }
+
+ @Override
+ public String toString() {
+ String str = new String (
+ "PresetReverb"+
+ ";preset="+Short.toString(preset)
+ );
+ return str;
+ }
+ };
+
+
+ /**
+ * Gets the preset reverb properties. This method is useful when a snapshot of current
+ * preset reverb settings must be saved by the application.
+ * @return a PresetReverb.Settings object containing all current parameters values
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public PresetReverb.Settings getProperties()
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ Settings settings = new Settings();
+ short[] value = new short[1];
+ checkStatus(getParameter(PARAM_PRESET, value));
+ settings.preset = value[0];
+ return settings;
+ }
+
+ /**
+ * Sets the preset reverb properties. This method is useful when preset reverb settings have to
+ * be applied from a previous backup.
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public void setProperties(PresetReverb.Settings settings)
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ checkStatus(setParameter(PARAM_PRESET, settings.preset));
+ }
}
diff --git a/media/java/android/media/Virtualizer.java b/media/java/android/media/Virtualizer.java
index 9f71297..2c8909e 100644
--- a/media/java/android/media/Virtualizer.java
+++ b/media/java/android/media/Virtualizer.java
@@ -19,13 +19,15 @@ package android.media;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
+import android.media.AudioEffect;
import android.os.Bundle;
import android.util.Log;
+
import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
+import java.util.StringTokenizer;
-import android.media.AudioEffect;
/**
* An audio virtualizer is a general name for an effect to spatialize audio channels. The exact
@@ -211,4 +213,82 @@ public class Virtualizer extends AudioEffect {
}
}
}
+
+ /**
+ * The Settings class regroups all virtualizer parameters. It is used in
+ * conjuntion with getProperties() and setProperties() methods to backup and restore
+ * all parameters in a single call.
+ */
+ public static class Settings {
+ public short strength;
+
+ public Settings() {
+ }
+
+ /**
+ * Settings class constructor from a key=value; pairs formatted string. The string is
+ * typically returned by Settings.toString() method.
+ * @throws IllegalArgumentException if the string is not correctly formatted.
+ */
+ public Settings(String settings) {
+ StringTokenizer st = new StringTokenizer(settings, "=;");
+ int tokens = st.countTokens();
+ if (st.countTokens() != 3) {
+ throw new IllegalArgumentException("settings: " + settings);
+ }
+ String key = st.nextToken();
+ if (!key.equals("Virtualizer")) {
+ throw new IllegalArgumentException(
+ "invalid settings for Virtualizer: " + key);
+ }
+ try {
+ key = st.nextToken();
+ if (!key.equals("strength")) {
+ throw new IllegalArgumentException("invalid key name: " + key);
+ }
+ strength = Short.parseShort(st.nextToken());
+ } catch (NumberFormatException nfe) {
+ throw new IllegalArgumentException("invalid value for key: " + key);
+ }
+ }
+
+ @Override
+ public String toString() {
+ String str = new String (
+ "Virtualizer"+
+ ";strength="+Short.toString(strength)
+ );
+ return str;
+ }
+ };
+
+
+ /**
+ * Gets the virtualizer properties. This method is useful when a snapshot of current
+ * virtualizer settings must be saved by the application.
+ * @return a Virtualizer.Settings object containing all current parameters values
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public Virtualizer.Settings getProperties()
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ Settings settings = new Settings();
+ short[] value = new short[1];
+ checkStatus(getParameter(PARAM_STRENGTH, value));
+ settings.strength = value[0];
+ return settings;
+ }
+
+ /**
+ * Sets the virtualizer properties. This method is useful when virtualizer settings have to
+ * be applied from a previous backup.
+ * @throws IllegalStateException
+ * @throws IllegalArgumentException
+ * @throws UnsupportedOperationException
+ */
+ public void setProperties(Virtualizer.Settings settings)
+ throws IllegalStateException, IllegalArgumentException, UnsupportedOperationException {
+ checkStatus(setParameter(PARAM_STRENGTH, settings.strength));
+ }
}
diff --git a/media/jni/android_media_MtpClient.cpp b/media/jni/android_media_MtpClient.cpp
index f69053c..67740bc 100644
--- a/media/jni/android_media_MtpClient.cpp
+++ b/media/jni/android_media_MtpClient.cpp
@@ -29,6 +29,7 @@
#include "MtpClient.h"
#include "MtpDevice.h"
+#include "MtpObjectInfo.h"
using namespace android;
@@ -38,6 +39,19 @@ static jmethodID method_deviceAdded;
static jmethodID method_deviceRemoved;
static jfieldID field_context;
+static struct file_descriptor_offsets_t
+{
+ jclass mClass;
+ jmethodID mConstructor;
+ jfieldID mDescriptor;
+} gFileDescriptorOffsets;
+
+static struct parcel_file_descriptor_offsets_t
+{
+ jclass mClass;
+ jmethodID mConstructor;
+} gParcelFileDescriptorOffsets;
+
#ifdef HAVE_ANDROID_OS
static void checkAndClearExceptionFromCallback(JNIEnv* env, const char* methodName) {
@@ -187,6 +201,38 @@ android_media_MtpClient_get_storage_id(JNIEnv *env, jobject thiz,
return -1;
}
+static jobject
+android_media_MtpClient_open_file(JNIEnv *env, jobject thiz,
+ jint device_id, jint object_id)
+{
+#ifdef HAVE_ANDROID_OS
+ MyClient *client = (MyClient *)env->GetIntField(thiz, field_context);
+ MtpDevice* device = client->getDevice(device_id);
+ if (!device)
+ return NULL;
+
+ MtpObjectInfo* info = device->getObjectInfo(object_id);
+ if (!info)
+ return NULL;
+ int object_size = info->mCompressedSize;
+ delete info;
+ int fd = device->readObject(object_id, object_size);
+ if (fd < 0)
+ return NULL;
+
+ jobject fileDescriptor = env->NewObject(gFileDescriptorOffsets.mClass,
+ gFileDescriptorOffsets.mConstructor);
+ if (fileDescriptor != NULL) {
+ env->SetIntField(fileDescriptor, gFileDescriptorOffsets.mDescriptor, fd);
+ } else {
+ return NULL;
+ }
+ return env->NewObject(gParcelFileDescriptorOffsets.mClass,
+ gParcelFileDescriptorOffsets.mConstructor, fileDescriptor);
+#endif
+ return NULL;
+}
+
// ----------------------------------------------------------------------------
static JNINativeMethod gMethods[] = {
@@ -197,6 +243,8 @@ static JNINativeMethod gMethods[] = {
{"native_delete_object", "(II)Z", (void *)android_media_MtpClient_delete_object},
{"native_get_parent", "(II)I", (void *)android_media_MtpClient_get_parent},
{"native_get_storage_id", "(II)I", (void *)android_media_MtpClient_get_storage_id},
+ {"native_open_file", "(II)Landroid/os/ParcelFileDescriptor;",
+ (void *)android_media_MtpClient_open_file},
};
static const char* const kClassPathName = "android/media/MtpClient";
@@ -228,6 +276,21 @@ int register_android_media_MtpClient(JNIEnv *env)
return -1;
}
+ clazz = env->FindClass("java/io/FileDescriptor");
+ LOG_FATAL_IF(clazz == NULL, "Unable to find class java.io.FileDescriptor");
+ gFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
+ gFileDescriptorOffsets.mConstructor = env->GetMethodID(clazz, "<init>", "()V");
+ gFileDescriptorOffsets.mDescriptor = env->GetFieldID(clazz, "descriptor", "I");
+ LOG_FATAL_IF(gFileDescriptorOffsets.mDescriptor == NULL,
+ "Unable to find descriptor field in java.io.FileDescriptor");
+
+ clazz = env->FindClass("android/os/ParcelFileDescriptor");
+ LOG_FATAL_IF(clazz == NULL, "Unable to find class android.os.ParcelFileDescriptor");
+ gParcelFileDescriptorOffsets.mClass = (jclass) env->NewGlobalRef(clazz);
+ gParcelFileDescriptorOffsets.mConstructor = env->GetMethodID(clazz, "<init>", "(Ljava/io/FileDescriptor;)V");
+ LOG_FATAL_IF(gParcelFileDescriptorOffsets.mConstructor == NULL,
+ "Unable to find constructor for android.os.ParcelFileDescriptor");
+
return AndroidRuntime::registerNativeMethods(env,
"android/media/MtpClient", gMethods, NELEM(gMethods));
}
diff --git a/media/jni/audioeffect/android_media_AudioEffect.cpp b/media/jni/audioeffect/android_media_AudioEffect.cpp
index beb3dfc..8d9f4fe 100644
--- a/media/jni/audioeffect/android_media_AudioEffect.cpp
+++ b/media/jni/audioeffect/android_media_AudioEffect.cpp
@@ -549,7 +549,7 @@ static jint android_media_AudioEffect_native_setParameter(JNIEnv *env,
p = (effect_param_t *) malloc(sizeof(effect_param_t) + voffset + vsize);
memcpy(p->data, lpParam, psize);
p->psize = psize;
- memcpy(p->data + voffset, lpValue, psize);
+ memcpy(p->data + voffset, lpValue, vsize);
p->vsize = vsize;
lStatus = lpAudioEffect->setParameter(p);
@@ -698,8 +698,11 @@ static jint android_media_AudioEffect_native_command(JNIEnv *env, jobject thiz,
}
}
- lStatus = translateError(lpAudioEffect->command(cmdCode, cmdSize, pCmdData,
- pReplySize, pReplyData));
+ lStatus = translateError(lpAudioEffect->command((uint32_t)cmdCode,
+ (uint32_t)cmdSize,
+ pCmdData,
+ (uint32_t *)pReplySize,
+ pReplyData));
command_Exit:
diff --git a/media/libeffects/factory/EffectsFactory.c b/media/libeffects/factory/EffectsFactory.c
index 0be280c..c19a505 100644
--- a/media/libeffects/factory/EffectsFactory.c
+++ b/media/libeffects/factory/EffectsFactory.c
@@ -73,7 +73,12 @@ int Effect_Process(effect_interface_t self, audio_buffer_t *inBuffer, audio_buff
return ret;
}
-int Effect_Command(effect_interface_t self, int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
+int Effect_Command(effect_interface_t self,
+ uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *replySize,
+ void *pReplyData)
{
int ret = init();
if (ret < 0) {
diff --git a/media/libeffects/lvm/wrapper/Android.mk b/media/libeffects/lvm/wrapper/Android.mk
index aed594d..7855dcd 100644
--- a/media/libeffects/lvm/wrapper/Android.mk
+++ b/media/libeffects/lvm/wrapper/Android.mk
@@ -1,35 +1,36 @@
-LOCAL_PATH:= $(call my-dir)
-
-# music bundle wrapper
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_ARM_MODE := arm
-
-LOCAL_SRC_FILES:= \
- Bundle/EffectBundle.cpp
-
-LOCAL_MODULE:= libbundlewrapper
-
-LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/soundfx
-
-LOCAL_PRELINK_MODULE := false
-
-LOCAL_STATIC_LIBRARIES += libmusicbundle
-
-LOCAL_SHARED_LIBRARIES := \
- libcutils
-
-ifeq ($(TARGET_SIMULATOR),true)
-LOCAL_LDLIBS += -ldl
-else
-LOCAL_SHARED_LIBRARIES += libdl
-endif
-
-LOCAL_C_INCLUDES += \
- $(LOCAL_PATH)/Bundle \
- $(LOCAL_PATH)/../lib/Common/lib/ \
- $(LOCAL_PATH)/../lib/Bundle/lib/
-
-
-include $(BUILD_SHARED_LIBRARY)
+LOCAL_PATH:= $(call my-dir)
+
+# music bundle wrapper
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_ARM_MODE := arm
+
+LOCAL_SRC_FILES:= \
+ Bundle/EffectBundle.cpp
+
+LOCAL_MODULE:= libbundlewrapper
+
+LOCAL_MODULE_PATH := $(TARGET_OUT_SHARED_LIBRARIES)/soundfx
+
+LOCAL_PRELINK_MODULE := false
+
+LOCAL_STATIC_LIBRARIES += libmusicbundle
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils \
+
+ifeq ($(TARGET_SIMULATOR),true)
+LOCAL_LDLIBS += -ldl
+else
+LOCAL_SHARED_LIBRARIES += libdl
+endif
+
+
+LOCAL_C_INCLUDES += \
+ $(LOCAL_PATH)/Bundle \
+ $(LOCAL_PATH)/../lib/Common/lib/ \
+ $(LOCAL_PATH)/../lib/Bundle/lib/
+
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
index 5e91974..4c3ebca 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.cpp
@@ -1625,7 +1625,7 @@ int BassBoost_getParameter(EffectContext *pContext,
//LOGV("\tBassBoost_getParameter start");
switch (param){
- case BASSBOOST_PARAM_STRENGTH_SUP:
+ case BASSBOOST_PARAM_STRENGTH_SUPPORTED:
case BASSBOOST_PARAM_STRENGTH:
if (*pValueSize != sizeof(int16_t)){
LOGV("\tLVM_ERROR : BassBoost_getParameter() invalid pValueSize2 %d", *pValueSize);
@@ -1640,10 +1640,10 @@ int BassBoost_getParameter(EffectContext *pContext,
}
switch (param){
- case BASSBOOST_PARAM_STRENGTH_SUP:
+ case BASSBOOST_PARAM_STRENGTH_SUPPORTED:
*(uint32_t *)pValue = 1;
- //LOGV("\tBassBoost_getParameter() BASSBOOST_PARAM_STRENGTH_SUP Value is %d",
+ //LOGV("\tBassBoost_getParameter() BASSBOOST_PARAM_STRENGTH_SUPPORTED Value is %d",
// *(uint32_t *)pValue);
break;
@@ -1735,7 +1735,7 @@ int Virtualizer_getParameter(EffectContext *pContext,
//LOGV("\tVirtualizer_getParameter start");
switch (param){
- case VIRTUALIZER_PARAM_STRENGTH_SUP:
+ case VIRTUALIZER_PARAM_STRENGTH_SUPPORTED:
case VIRTUALIZER_PARAM_STRENGTH:
if (*pValueSize != sizeof(int16_t)){
LOGV("\tLVM_ERROR : Virtualizer_getParameter() invalid pValueSize2 %d",*pValueSize);
@@ -1750,10 +1750,10 @@ int Virtualizer_getParameter(EffectContext *pContext,
}
switch (param){
- case VIRTUALIZER_PARAM_STRENGTH_SUP:
+ case VIRTUALIZER_PARAM_STRENGTH_SUPPORTED:
*(uint32_t *)pValue = 1;
- //LOGV("\tVirtualizer_getParameter() VIRTUALIZER_PARAM_STRENGTH_SUP Value is %d",
+ //LOGV("\tVirtualizer_getParameter() VIRTUALIZER_PARAM_STRENGTH_SUPPORTED Value is %d",
// *(uint32_t *)pValue);
break;
@@ -1876,6 +1876,14 @@ int Equalizer_getParameter(EffectContext *pContext,
case EQ_PARAM_GET_PRESET_NAME:
break;
+ case EQ_PARAM_PROPERTIES:
+ if (*pValueSize < (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t)) {
+ LOGV("\tLVM_ERROR : Equalizer_getParameter() invalid pValueSize 1 %d", *pValueSize);
+ return -EINVAL;
+ }
+ *pValueSize = (2 + FIVEBAND_NUMBANDS) * sizeof(uint16_t);
+ break;
+
default:
LOGV("\tLVM_ERROR : Equalizer_getParameter unknown param %d", param);
return -EINVAL;
@@ -1959,6 +1967,16 @@ int Equalizer_getParameter(EffectContext *pContext,
// param2, gEqualizerPresets[param2].name, *pValueSize);
break;
+ case EQ_PARAM_PROPERTIES: {
+ uint16_t *p = (uint16_t *)pValue;
+ LOGV("\tEqualizer_getParameter() EQ_PARAM_PROPERTIES");
+ p[0] = EqualizerGetPreset(pContext);
+ p[1] = FIVEBAND_NUMBANDS;
+ for (int i = 0; i < FIVEBAND_NUMBANDS; i++) {
+ p[2 + i] = EqualizerGetBandLevel(pContext, i);
+ }
+ } break;
+
default:
LOGV("\tLVM_ERROR : Equalizer_getParameter() invalid param %d", param);
status = -EINVAL;
@@ -2330,10 +2348,10 @@ extern "C" int Effect_process(effect_interface_t self,
/* Effect Control Interface Implementation: Command */
extern "C" int Effect_command(effect_interface_t self,
- int cmdCode,
- int cmdSize,
+ uint32_t cmdCode,
+ uint32_t cmdSize,
void *pCmdData,
- int *replySize,
+ uint32_t *replySize,
void *pReplyData){
EffectContext * pContext = (EffectContext *) self;
int retsize;
diff --git a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
index 029f843..d009bf9 100644
--- a/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
+++ b/media/libeffects/lvm/wrapper/Bundle/EffectBundle.h
@@ -17,7 +17,9 @@
#ifndef ANDROID_EFFECTBUNDLE_H_
#define ANDROID_EFFECTBUNDLE_H_
-#include <media/EffectApi.h>
+#include <media/EffectEqualizerApi.h>
+#include <media/EffectBassBoostApi.h>
+#include <media/EffectVirtualizerApi.h>
#include <LVM.h>
#if __cplusplus
@@ -29,22 +31,11 @@ extern "C" {
#define MAX_CALL_SIZE 256
//#define LVM_PCM
-//TODO: this should be included from each effect API include
-static const effect_uuid_t SL_IID_BASSBOOST_ = { 0x0634f220, 0xddd4, 0x11db, 0xa0fc,
- { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
-const effect_uuid_t * const SL_IID_BASSBOOST = &SL_IID_BASSBOOST_;
-
-static const effect_uuid_t SL_IID_EQUALIZER_ = { 0x0bed4300, 0xddd6, 0x11db, 0x8f34,
- { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
-const effect_uuid_t * const SL_IID_EQUALIZER = &SL_IID_EQUALIZER_;
-
-static const effect_uuid_t SL_IID_VIRTUALIZER_ = { 0x37cc2c00, 0xdddd, 0x11db, 0x8577,
- { 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
-const effect_uuid_t * const SL_IID_VIRTUALIZER = &SL_IID_VIRTUALIZER_;
-
+#ifndef OPENSL_ES_H_
static const effect_uuid_t SL_IID_VOLUME_ = { 0x09e8ede0, 0xddde, 0x11db, 0xb4f6,
{ 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b } };
const effect_uuid_t * const SL_IID_VOLUME = &SL_IID_VOLUME_;
+#endif //OPENSL_ES_H_
typedef enum
{
@@ -112,34 +103,6 @@ struct EffectContext{
BundledEffectContext *pBundledContext;
};
-//TODO: this should be included from each effect API include
-/* enumerated parameter settings for BassBoost effect */
-typedef enum
-{
- BASSBOOST_PARAM_STRENGTH_SUP, // type SLboolean = typedef SLuint32
- BASSBOOST_PARAM_STRENGTH // type SLpermille = typedef SLuint16
-} t_bassboost_params;
-
-/* enumerated parameter settings for Virtualizer effect */
-typedef enum
-{
- VIRTUALIZER_PARAM_STRENGTH_SUP, // type SLboolean = typedef SLuint32
- VIRTUALIZER_PARAM_STRENGTH // type SLpermille = typedef SLuint16
-} t_virtualizer_params;
-
-/* enumerated parameter settings for Equalizer effect */
-typedef enum
-{
- EQ_PARAM_NUM_BANDS, // Gets the number of frequency bands that the equalizer supports.
- EQ_PARAM_LEVEL_RANGE, // Returns the minimum and maximum band levels supported.
- EQ_PARAM_BAND_LEVEL, // Gets/Sets the gain set for the given equalizer band.
- EQ_PARAM_CENTER_FREQ, // Gets the center frequency of the given band.
- EQ_PARAM_BAND_FREQ_RANGE, // Gets the frequency range of the given frequency band.
- EQ_PARAM_GET_BAND, // Gets the band that has the most effect on the given frequency.
- EQ_PARAM_CUR_PRESET, // Gets/Sets the current preset.
- EQ_PARAM_GET_NUM_OF_PRESETS, // Gets the total number of presets the equalizer supports.
- EQ_PARAM_GET_PRESET_NAME // Gets the preset name based on the index.
-} t_equalizer_params;
/* enumerated parameter settings for Volume effect */
typedef enum
diff --git a/media/libeffects/testlibs/EffectEqualizer.cpp b/media/libeffects/testlibs/EffectEqualizer.cpp
index 0eb2bdf..a71f236 100644
--- a/media/libeffects/testlibs/EffectEqualizer.cpp
+++ b/media/libeffects/testlibs/EffectEqualizer.cpp
@@ -551,8 +551,8 @@ extern "C" int Equalizer_process(effect_interface_t self, audio_buffer_t *inBuff
return 0;
} // end Equalizer_process
-extern "C" int Equalizer_command(effect_interface_t self, int cmdCode, int cmdSize,
- void *pCmdData, int *replySize, void *pReplyData) {
+extern "C" int Equalizer_command(effect_interface_t self, uint32_t cmdCode, uint32_t cmdSize,
+ void *pCmdData, uint32_t *replySize, void *pReplyData) {
android::EqualizerContext * pContext = (android::EqualizerContext *) self;
int retsize;
diff --git a/media/libeffects/testlibs/EffectReverb.c b/media/libeffects/testlibs/EffectReverb.c
index 2ce7558..3eb8b2c 100644
--- a/media/libeffects/testlibs/EffectReverb.c
+++ b/media/libeffects/testlibs/EffectReverb.c
@@ -270,8 +270,8 @@ static int Reverb_Process(effect_interface_t self, audio_buffer_t *inBuffer, aud
}
-static int Reverb_Command(effect_interface_t self, int cmdCode, int cmdSize,
- void *pCmdData, int *replySize, void *pReplyData) {
+static int Reverb_Command(effect_interface_t self, uint32_t cmdCode, uint32_t cmdSize,
+ void *pCmdData, uint32_t *replySize, void *pReplyData) {
reverb_module_t *pRvbModule = (reverb_module_t *) self;
reverb_object_t *pReverb;
int retsize;
@@ -688,7 +688,7 @@ int Reverb_getParameter(reverb_object_t *pReverb, int32_t param, size_t *pSize,
void *pValue) {
int32_t *pValue32;
int16_t *pValue16;
- t_reverb_properties *pProperties;
+ t_reverb_settings *pProperties;
int32_t i;
int32_t temp;
int32_t temp2;
@@ -727,7 +727,7 @@ int Reverb_getParameter(reverb_object_t *pReverb, int32_t param, size_t *pSize,
break;
case REVERB_PARAM_PROPERTIES:
- size = sizeof(t_reverb_properties);
+ size = sizeof(t_reverb_settings);
break;
default:
@@ -740,7 +740,7 @@ int Reverb_getParameter(reverb_object_t *pReverb, int32_t param, size_t *pSize,
pValue32 = (int32_t *) pValue;
pValue16 = (int16_t *) pValue;
- pProperties = (t_reverb_properties *) pValue;
+ pProperties = (t_reverb_settings *) pValue;
switch (param) {
case REVERB_PARAM_BYPASS:
@@ -971,7 +971,7 @@ int Reverb_setParameter(reverb_object_t *pReverb, int32_t param, size_t size,
void *pValue) {
int32_t value32;
int16_t value16;
- t_reverb_properties *pProperties;
+ t_reverb_settings *pProperties;
int32_t i;
int32_t temp;
int32_t temp2;
@@ -1019,7 +1019,7 @@ int Reverb_setParameter(reverb_object_t *pReverb, int32_t param, size_t size,
break;
case REVERB_PARAM_PROPERTIES:
- paramSize = sizeof(t_reverb_properties);
+ paramSize = sizeof(t_reverb_settings);
break;
default:
@@ -1035,7 +1035,7 @@ int Reverb_setParameter(reverb_object_t *pReverb, int32_t param, size_t size,
} else if (paramSize == sizeof(int32_t)) {
value32 = *(int32_t *) pValue;
} else {
- pProperties = (t_reverb_properties *) pValue;
+ pProperties = (t_reverb_settings *) pValue;
}
pPreset = &pReverb->m_sPreset.m_sPreset[pReverb->m_nNextRoom];
diff --git a/media/libeffects/testlibs/EffectReverb.h b/media/libeffects/testlibs/EffectReverb.h
index ee8e390..dbcd192 100644
--- a/media/libeffects/testlibs/EffectReverb.h
+++ b/media/libeffects/testlibs/EffectReverb.h
@@ -301,12 +301,23 @@ typedef struct reverb_module_s {
*------------------------------------
*/
int EffectQueryNumberEffects(uint32_t *pNumEffects);
-int EffectQueryEffect(uint32_t index, effect_descriptor_t *pDescriptor);
-int EffectCreate(effect_uuid_t *effectUID, int32_t sessionId, int32_t ioId, effect_interface_t *pInterface);
+int EffectQueryEffect(uint32_t index,
+ effect_descriptor_t *pDescriptor);
+int EffectCreate(effect_uuid_t *effectUID,
+ int32_t sessionId,
+ int32_t ioId,
+ effect_interface_t *pInterface);
int EffectRelease(effect_interface_t interface);
-static int Reverb_Process(effect_interface_t self, audio_buffer_t *inBuffer, audio_buffer_t *outBuffer);
-static int Reverb_Command(effect_interface_t self, int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData);
+static int Reverb_Process(effect_interface_t self,
+ audio_buffer_t *inBuffer,
+ audio_buffer_t *outBuffer);
+static int Reverb_Command(effect_interface_t self,
+ uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *replySize,
+ void *pReplyData);
/*------------------------------------
diff --git a/media/libeffects/visualizer/EffectVisualizer.cpp b/media/libeffects/visualizer/EffectVisualizer.cpp
index ec13557..8ab57c93 100644
--- a/media/libeffects/visualizer/EffectVisualizer.cpp
+++ b/media/libeffects/visualizer/EffectVisualizer.cpp
@@ -272,8 +272,8 @@ extern "C" int Visualizer_process(
return 0;
} // end Visualizer_process
-extern "C" int Visualizer_command(effect_interface_t self, int cmdCode, int cmdSize,
- void *pCmdData, int *replySize, void *pReplyData) {
+extern "C" int Visualizer_command(effect_interface_t self, uint32_t cmdCode, uint32_t cmdSize,
+ void *pCmdData, uint32_t *replySize, void *pReplyData) {
android::VisualizerContext * pContext = (android::VisualizerContext *)self;
int retsize;
diff --git a/media/libmedia/AudioEffect.cpp b/media/libmedia/AudioEffect.cpp
index df0f73b..3cdf48a 100644
--- a/media/libmedia/AudioEffect.cpp
+++ b/media/libmedia/AudioEffect.cpp
@@ -221,7 +221,11 @@ status_t AudioEffect::setEnabled(bool enabled)
return INVALID_OPERATION;
}
-status_t AudioEffect::command(int32_t cmdCode, int32_t cmdSize, void *cmdData, int32_t *replySize, void *replyData)
+status_t AudioEffect::command(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *cmdData,
+ uint32_t *replySize,
+ void *replyData)
{
if (mStatus != NO_ERROR && mStatus != ALREADY_EXISTS) {
return INVALID_OPERATION;
@@ -241,8 +245,8 @@ status_t AudioEffect::setParameter(effect_param_t *param)
return BAD_VALUE;
}
- int size = sizeof(int);
- int psize = ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
+ uint32_t size = sizeof(int);
+ uint32_t psize = ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
LOGV("setParameter: param: %d, param2: %d", *(int *)param->data, (param->psize == 8) ? *((int *)param->data + 1): -1);
@@ -285,7 +289,7 @@ status_t AudioEffect::setParameterCommit()
if (mCblk->clientIndex == 0) {
return INVALID_OPERATION;
}
- int size = 0;
+ uint32_t size = 0;
return mIEffect->command(EFFECT_CMD_SET_PARAM_COMMIT, 0, NULL, &size, NULL);
}
@@ -301,7 +305,7 @@ status_t AudioEffect::getParameter(effect_param_t *param)
LOGV("getParameter: param: %d, param2: %d", *(int *)param->data, (param->psize == 8) ? *((int *)param->data + 1): -1);
- int psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
+ uint32_t psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
return mIEffect->command(EFFECT_CMD_GET_PARAM, sizeof(effect_param_t) + param->psize, param, &psize, param);
}
@@ -350,7 +354,11 @@ void AudioEffect::enableStatusChanged(bool enabled)
}
}
-void AudioEffect::commandExecuted(int cmdCode, int cmdSize, void *cmdData, int replySize, void *replyData)
+void AudioEffect::commandExecuted(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *cmdData,
+ uint32_t replySize,
+ void *replyData)
{
if (cmdData == NULL || replyData == NULL) {
return;
diff --git a/media/libmedia/IEffect.cpp b/media/libmedia/IEffect.cpp
index 8e3ac71..a945b97 100644
--- a/media/libmedia/IEffect.cpp
+++ b/media/libmedia/IEffect.cpp
@@ -59,7 +59,11 @@ public:
return reply.readInt32();
}
- status_t command(int cmdCode, int cmdSize, void *pCmdData, int *pReplySize, void *pReplyData)
+ status_t command(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *pReplySize,
+ void *pReplyData)
{
LOGV("command");
Parcel data, reply;
@@ -136,15 +140,15 @@ status_t BnEffect::onTransact(
case COMMAND: {
LOGV("COMMAND");
CHECK_INTERFACE(IEffect, data, reply);
- int cmdCode = data.readInt32();
- int cmdSize = data.readInt32();
+ uint32_t cmdCode = data.readInt32();
+ uint32_t cmdSize = data.readInt32();
char *cmd = NULL;
if (cmdSize) {
cmd = (char *)malloc(cmdSize);
data.read(cmd, cmdSize);
}
- int replySize = data.readInt32();
- int replySz = replySize;
+ uint32_t replySize = data.readInt32();
+ uint32_t replySz = replySize;
char *resp = NULL;
if (replySize) {
resp = (char *)malloc(replySize);
diff --git a/media/libmedia/IEffectClient.cpp b/media/libmedia/IEffectClient.cpp
index e7659ae..1fa9cbe 100644
--- a/media/libmedia/IEffectClient.cpp
+++ b/media/libmedia/IEffectClient.cpp
@@ -56,7 +56,11 @@ public:
remote()->transact(ENABLE_STATUS_CHANGED, data, &reply, IBinder::FLAG_ONEWAY);
}
- void commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData)
+ void commandExecuted(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t replySize,
+ void *pReplyData)
{
LOGV("commandExecuted");
Parcel data, reply;
@@ -108,14 +112,14 @@ status_t BnEffectClient::onTransact(
case COMMAND_EXECUTED: {
LOGV("COMMAND_EXECUTED");
CHECK_INTERFACE(IEffectClient, data, reply);
- int cmdCode = data.readInt32();
- int cmdSize = data.readInt32();
+ uint32_t cmdCode = data.readInt32();
+ uint32_t cmdSize = data.readInt32();
char *cmd = NULL;
if (cmdSize) {
cmd = (char *)malloc(cmdSize);
data.read(cmd, cmdSize);
}
- int replySize = data.readInt32();
+ uint32_t replySize = data.readInt32();
char *resp = NULL;
if (replySize) {
resp = (char *)malloc(replySize);
diff --git a/media/libmedia/Visualizer.cpp b/media/libmedia/Visualizer.cpp
index 47e96e5..32cdb49 100644
--- a/media/libmedia/Visualizer.cpp
+++ b/media/libmedia/Visualizer.cpp
@@ -184,7 +184,7 @@ status_t Visualizer::getWaveForm(uint8_t *waveform)
status_t status = NO_ERROR;
if (mEnabled) {
- int32_t replySize = mCaptureSize;
+ uint32_t replySize = mCaptureSize;
status_t status = command(VISU_CMD_CAPTURE, 0, NULL, &replySize, waveform);
if (replySize == 0) {
status = NOT_ENOUGH_DATA;
diff --git a/media/mtp/MtpClient.cpp b/media/mtp/MtpClient.cpp
index b53fe54..ceb6a43 100644
--- a/media/mtp/MtpClient.cpp
+++ b/media/mtp/MtpClient.cpp
@@ -38,6 +38,16 @@
namespace android {
+static bool isMtpDevice(uint16_t vendor, uint16_t product) {
+ // Sandisk Sansa Fuze
+ if (vendor == 0x0781 && product == 0x74c2)
+ return true;
+ // Samsung YP-Z5
+ if (vendor == 0x04e8 && product == 0x503c)
+ return true;
+ return false;
+}
+
class MtpClientThread : public Thread {
private:
MtpClient* mClient;
@@ -128,8 +138,32 @@ bool MtpClient::usbDeviceAdded(const char *devname) {
LOGD("Found MTP device: \"%s\" \"%s\"\n", usb_device_get_manufacturer_name(device),
usb_device_get_product_name(device));
} else {
- // not an MTP or PTP device
- continue;
+ // look for special cased devices based on vendor/product ID
+ // we are doing this mainly for testing purposes
+ uint16_t vendor = usb_device_get_vendor_id(device);
+ uint16_t product = usb_device_get_product_id(device);
+ if (!isMtpDevice(vendor, product)) {
+ // not an MTP or PTP device
+ continue;
+ }
+ // request MTP OS string and descriptor
+ // some music players need to see this before entering MTP mode.
+ char buffer[256];
+ memset(buffer, 0, sizeof(buffer));
+ int ret = usb_device_send_control(device,
+ USB_DIR_IN|USB_RECIP_DEVICE|USB_TYPE_STANDARD,
+ USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING << 8) | 0xEE,
+ 0, sizeof(buffer), buffer);
+ printf("usb_device_send_control returned %d errno: %d\n", ret, errno);
+ if (ret > 0) {
+ printf("got MTP string %s\n", buffer);
+ ret = usb_device_send_control(device,
+ USB_DIR_IN|USB_RECIP_DEVICE|USB_TYPE_VENDOR, 1,
+ 0, 4, sizeof(buffer), buffer);
+ printf("OS descriptor got %d\n", ret);
+ } else {
+ printf("no MTP string\n");
+ }
}
// if we got here, then we have a likely MTP or PTP device
@@ -165,7 +199,7 @@ bool MtpClient::usbDeviceAdded(const char *devname) {
struct usb_endpoint *ep_intr = usb_endpoint_open(device, ep_intr_desc);
if (usb_device_claim_interface(device, interface->bInterfaceNumber)) {
- LOGE("usb_device_claim_interface failed\n");
+ LOGE("usb_device_claim_interface failed errno: %d\n", errno);
usb_endpoint_close(ep_in);
usb_endpoint_close(ep_out);
usb_endpoint_close(ep_intr);
diff --git a/media/mtp/MtpCursor.cpp b/media/mtp/MtpCursor.cpp
index 5b6672a..3ba07cc 100644
--- a/media/mtp/MtpCursor.cpp
+++ b/media/mtp/MtpCursor.cpp
@@ -367,7 +367,7 @@ bool MtpCursor::fillObject(CursorWindow* window, MtpDevice* device,
goto fail;
break;
case OBJECT_THUMB:
- if (!putThumbnail(window, objectID, row, i))
+ if (!putThumbnail(window, objectID, objectInfo->mFormat, row, i))
goto fail;
break;
default:
@@ -427,19 +427,25 @@ bool MtpCursor::putString(CursorWindow* window, const char* text, int row, int c
return true;
}
-bool MtpCursor::putThumbnail(CursorWindow* window, int objectID, int row, int column) {
+bool MtpCursor::putThumbnail(CursorWindow* window, int objectID, int format, int row, int column) {
MtpDevice* device = mClient->getDevice(mDeviceID);
- int size;
- void* thumbnail = device->getThumbnail(objectID, size);
-
- LOGD("putThumbnail: %p, size: %d\n", thumbnail, size);
- int offset = window->alloc(size);
- if (!offset) {
- window->freeLastRow();
- LOGE("Failed allocating %u bytes for thumbnail", size);
- return false;
+ void* thumbnail;
+ int size, offset;
+ if (format == MTP_FORMAT_ASSOCIATION) {
+ thumbnail = NULL;
+ size = offset = 0;
+ } else {
+ thumbnail = device->getThumbnail(objectID, size);
+
+ LOGV("putThumbnail: %p, size: %d\n", thumbnail, size);
+ offset = window->alloc(size);
+ if (!offset) {
+ window->freeLastRow();
+ LOGE("Failed allocating %u bytes for thumbnail", size);
+ return false;
+ }
}
- if (size > 0)
+ if (thumbnail)
window->copyIn(offset, (const uint8_t*)thumbnail, size);
// This must be updated after the call to alloc(), since that
diff --git a/media/mtp/MtpCursor.h b/media/mtp/MtpCursor.h
index d51c052..3f84753 100644
--- a/media/mtp/MtpCursor.h
+++ b/media/mtp/MtpCursor.h
@@ -68,7 +68,7 @@ private:
bool prepareRow(CursorWindow* window);
bool putLong(CursorWindow* window, int value, int row, int column);
bool putString(CursorWindow* window, const char* text, int row, int column);
- bool putThumbnail(CursorWindow* window, int objectID, int row, int column);
+ bool putThumbnail(CursorWindow* window, int objectID, int format, int row, int column);
};
}; // namespace android
diff --git a/media/mtp/MtpDataPacket.cpp b/media/mtp/MtpDataPacket.cpp
index ebe764a..c159e20 100644
--- a/media/mtp/MtpDataPacket.cpp
+++ b/media/mtp/MtpDataPacket.cpp
@@ -20,6 +20,8 @@
#include <sys/types.h>
#include <fcntl.h>
+#include <usbhost/usbhost.h>
+
#include "MtpDataPacket.h"
#include "MtpStringBuffer.h"
@@ -391,6 +393,35 @@ int MtpDataPacket::read(struct usb_endpoint *ep) {
return length;
}
+int MtpDataPacket::readData(struct usb_endpoint *ep, void* buffer, int length) {
+ int packetSize = usb_endpoint_max_packet(ep);
+ int read = 0;
+ while (read < length) {
+ int ret = transfer(ep, (char *)buffer + read, packetSize);
+ if (ret < 0) {
+printf("MtpDataPacket::readData returning %d\n", ret);
+ return ret;
+ }
+ read += ret;
+ }
+printf("MtpDataPacket::readData returning %d\n", read);
+ return read;
+}
+
+int MtpDataPacket::readDataHeader(struct usb_endpoint *ep) {
+ int length = transfer(ep, mBuffer, usb_endpoint_max_packet(ep));
+ if (length >= 0)
+ mPacketSize = length;
+ return length;
+}
+
+int MtpDataPacket::writeDataHeader(struct usb_endpoint *ep, uint32_t length) {
+ MtpPacket::putUInt32(MTP_CONTAINER_LENGTH_OFFSET, length);
+ MtpPacket::putUInt16(MTP_CONTAINER_TYPE_OFFSET, MTP_CONTAINER_TYPE_DATA);
+ int ret = transfer(ep, mBuffer, MTP_CONTAINER_HEADER_SIZE);
+ return (ret < 0 ? ret : 0);
+}
+
int MtpDataPacket::write(struct usb_endpoint *ep) {
MtpPacket::putUInt32(MTP_CONTAINER_LENGTH_OFFSET, mPacketSize);
MtpPacket::putUInt16(MTP_CONTAINER_TYPE_OFFSET, MTP_CONTAINER_TYPE_DATA);
@@ -403,6 +434,19 @@ int MtpDataPacket::write(struct usb_endpoint *ep) {
return (ret < 0 ? ret : 0);
}
+int MtpDataPacket::write(struct usb_endpoint *ep, void* buffer, uint32_t length) {
+ int ret = 0;
+ int packetSize = usb_endpoint_max_packet(ep);
+ while (length > 0) {
+ int write = (length > packetSize ? packetSize : length);
+ int ret = transfer(ep, buffer, write);
+ if (ret < 0)
+ break;
+ length -= ret;
+ }
+ return (ret < 0 ? ret : 0);
+}
+
#endif // MTP_HOST
void* MtpDataPacket::getData(int& outLength) const {
diff --git a/media/mtp/MtpDataPacket.h b/media/mtp/MtpDataPacket.h
index 9a24d61..e8314d7 100644
--- a/media/mtp/MtpDataPacket.h
+++ b/media/mtp/MtpDataPacket.h
@@ -98,7 +98,12 @@ public:
#ifdef MTP_HOST
int read(struct usb_endpoint *ep);
+ int readData(struct usb_endpoint *ep, void* buffer, int length);
+ int readDataHeader(struct usb_endpoint *ep);
+
+ int writeDataHeader(struct usb_endpoint *ep, uint32_t length);
int write(struct usb_endpoint *ep);
+ int write(struct usb_endpoint *ep, void* buffer, uint32_t length);
#endif
inline bool hasData() const { return mPacketSize > MTP_CONTAINER_HEADER_SIZE; }
diff --git a/media/mtp/MtpDebug.h b/media/mtp/MtpDebug.h
index 86f601a..87eff74 100644
--- a/media/mtp/MtpDebug.h
+++ b/media/mtp/MtpDebug.h
@@ -17,7 +17,7 @@
#ifndef _MTP_DEBUG_H
#define _MTP_DEBUG_H
-#define LOG_NDEBUG 0
+// #define LOG_NDEBUG 0
#include <utils/Log.h>
#include "MtpTypes.h"
diff --git a/media/mtp/MtpDevice.cpp b/media/mtp/MtpDevice.cpp
index 3ceb9b4..bd68f75 100644
--- a/media/mtp/MtpDevice.cpp
+++ b/media/mtp/MtpDevice.cpp
@@ -23,6 +23,7 @@
#include "MtpProperty.h"
#include "MtpStorageInfo.h"
#include "MtpStringBuffer.h"
+#include "MtpUtils.h"
#include <stdio.h>
#include <stdlib.h>
@@ -31,6 +32,7 @@
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
+#include <endian.h>
#include <usbhost/usbhost.h>
@@ -93,6 +95,8 @@ const char* MtpDevice::getDeviceName() {
}
bool MtpDevice::openSession() {
+ Mutex::Autolock autoLock(mMutex);
+
mSessionID = 0;
mTransactionID = 0;
MtpSessionID newSession = 1;
@@ -117,6 +121,8 @@ bool MtpDevice::closeSession() {
}
MtpDeviceInfo* MtpDevice::getDeviceInfo() {
+ Mutex::Autolock autoLock(mMutex);
+
mRequest.reset();
if (!sendRequest(MTP_OPERATION_GET_DEVICE_INFO))
return NULL;
@@ -132,6 +138,8 @@ MtpDeviceInfo* MtpDevice::getDeviceInfo() {
}
MtpStorageIDList* MtpDevice::getStorageIDs() {
+ Mutex::Autolock autoLock(mMutex);
+
mRequest.reset();
if (!sendRequest(MTP_OPERATION_GET_STORAGE_IDS))
return NULL;
@@ -145,6 +153,8 @@ MtpStorageIDList* MtpDevice::getStorageIDs() {
}
MtpStorageInfo* MtpDevice::getStorageInfo(MtpStorageID storageID) {
+ Mutex::Autolock autoLock(mMutex);
+
mRequest.reset();
mRequest.setParameter(1, storageID);
if (!sendRequest(MTP_OPERATION_GET_STORAGE_INFO))
@@ -162,6 +172,8 @@ MtpStorageInfo* MtpDevice::getStorageInfo(MtpStorageID storageID) {
MtpObjectHandleList* MtpDevice::getObjectHandles(MtpStorageID storageID,
MtpObjectFormat format, MtpObjectHandle parent) {
+ Mutex::Autolock autoLock(mMutex);
+
mRequest.reset();
mRequest.setParameter(1, storageID);
mRequest.setParameter(2, format);
@@ -178,6 +190,8 @@ MtpObjectHandleList* MtpDevice::getObjectHandles(MtpStorageID storageID,
}
MtpObjectInfo* MtpDevice::getObjectInfo(MtpObjectHandle handle) {
+ Mutex::Autolock autoLock(mMutex);
+
// FIXME - we might want to add some caching here
mRequest.reset();
@@ -196,6 +210,8 @@ MtpObjectInfo* MtpDevice::getObjectInfo(MtpObjectHandle handle) {
}
void* MtpDevice::getThumbnail(MtpObjectHandle handle, int& outLength) {
+ Mutex::Autolock autoLock(mMutex);
+
mRequest.reset();
mRequest.setParameter(1, handle);
if (sendRequest(MTP_OPERATION_GET_THUMB) && readData()) {
@@ -208,7 +224,86 @@ void* MtpDevice::getThumbnail(MtpObjectHandle handle, int& outLength) {
return NULL;
}
+MtpObjectHandle MtpDevice::sendObjectInfo(MtpObjectInfo* info) {
+ Mutex::Autolock autoLock(mMutex);
+
+ mRequest.reset();
+ MtpObjectHandle parent = info->mParent;
+ if (parent == 0)
+ parent = MTP_PARENT_ROOT;
+
+ mRequest.setParameter(1, info->mStorageID);
+ mRequest.setParameter(2, info->mParent);
+
+ mData.putUInt32(info->mStorageID);
+ mData.putUInt16(info->mFormat);
+ mData.putUInt16(info->mProtectionStatus);
+ mData.putUInt32(info->mCompressedSize);
+ mData.putUInt16(info->mThumbFormat);
+ mData.putUInt32(info->mThumbCompressedSize);
+ mData.putUInt32(info->mThumbPixWidth);
+ mData.putUInt32(info->mThumbPixHeight);
+ mData.putUInt32(info->mImagePixWidth);
+ mData.putUInt32(info->mImagePixHeight);
+ mData.putUInt32(info->mImagePixDepth);
+ mData.putUInt32(info->mParent);
+ mData.putUInt16(info->mAssociationType);
+ mData.putUInt32(info->mAssociationDesc);
+ mData.putUInt32(info->mSequenceNumber);
+ mData.putString(info->mName);
+
+ char created[100], modified[100];
+ formatDateTime(info->mDateCreated, created, sizeof(created));
+ formatDateTime(info->mDateModified, modified, sizeof(modified));
+
+ mData.putString(created);
+ mData.putString(modified);
+ if (info->mKeywords)
+ mData.putString(info->mKeywords);
+ else
+ mData.putEmptyString();
+
+ if (sendRequest(MTP_OPERATION_SEND_OBJECT_INFO) && sendData()) {
+ MtpResponseCode ret = readResponse();
+ if (ret == MTP_RESPONSE_OK) {
+ info->mStorageID = mResponse.getParameter(1);
+ info->mParent = mResponse.getParameter(2);
+ info->mHandle = mResponse.getParameter(3);
+ return info->mHandle;
+ }
+ }
+ return (MtpObjectHandle)-1;
+}
+
+bool MtpDevice::sendObject(MtpObjectInfo* info, int srcFD) {
+ Mutex::Autolock autoLock(mMutex);
+
+ int remaining = info->mCompressedSize;
+ mRequest.reset();
+ mRequest.setParameter(1, info->mHandle);
+ if (sendRequest(MTP_OPERATION_SEND_OBJECT)) {
+ // send data header
+ writeDataHeader(MTP_OPERATION_SEND_OBJECT, remaining);
+
+ char buffer[65536];
+ while (remaining > 0) {
+ int count = read(srcFD, buffer, sizeof(buffer));
+ if (count > 0) {
+ int written = mData.write(mEndpointOut, buffer, count);
+ // FIXME check error
+ remaining -= count;
+ } else {
+ break;
+ }
+ }
+ }
+ MtpResponseCode ret = readResponse();
+ return (remaining == 0 && ret == MTP_RESPONSE_OK);
+}
+
bool MtpDevice::deleteObject(MtpObjectHandle handle) {
+ Mutex::Autolock autoLock(mMutex);
+
mRequest.reset();
mRequest.setParameter(1, handle);
if (sendRequest(MTP_OPERATION_DELETE_OBJECT)) {
@@ -236,6 +331,8 @@ MtpObjectHandle MtpDevice::getStorageID(MtpObjectHandle handle) {
}
MtpProperty* MtpDevice::getDevicePropDesc(MtpDeviceProperty code) {
+ Mutex::Autolock autoLock(mMutex);
+
mRequest.reset();
mRequest.setParameter(1, code);
if (!sendRequest(MTP_OPERATION_GET_DEVICE_PROP_DESC))
@@ -251,9 +348,101 @@ MtpProperty* MtpDevice::getDevicePropDesc(MtpDeviceProperty code) {
return NULL;
}
+class ReadObjectThread : public Thread {
+private:
+ MtpDevice* mDevice;
+ MtpObjectHandle mHandle;
+ int mObjectSize;
+ void* mInitialData;
+ int mInitialDataLength;
+ int mFD;
+
+public:
+ ReadObjectThread(MtpDevice* device, MtpObjectHandle handle, int objectSize)
+ : mDevice(device),
+ mHandle(handle),
+ mObjectSize(objectSize),
+ mInitialData(NULL),
+ mInitialDataLength(0)
+ {
+ }
+
+ virtual ~ReadObjectThread() {
+ if (mFD >= 0)
+ close(mFD);
+ free(mInitialData);
+ }
+
+ // returns file descriptor
+ int init() {
+ mDevice->mRequest.reset();
+ mDevice->mRequest.setParameter(1, mHandle);
+ if (mDevice->sendRequest(MTP_OPERATION_GET_OBJECT)
+ && mDevice->mData.readDataHeader(mDevice->mEndpointIn)) {
+
+ // mData will contain header and possibly the beginning of the object data
+ mInitialData = mDevice->mData.getData(mInitialDataLength);
+
+ // create a pipe for the client to read from
+ int pipefd[2];
+ if (pipe(pipefd) < 0) {
+ LOGE("pipe failed (%s)", strerror(errno));
+ return -1;
+ }
+
+ mFD = pipefd[1];
+ return pipefd[0];
+ } else {
+ return -1;
+ }
+ }
+
+ virtual bool threadLoop() {
+ int remaining = mObjectSize;
+ if (mInitialData) {
+ write(mFD, mInitialData, mInitialDataLength);
+ remaining -= mInitialDataLength;
+ free(mInitialData);
+ mInitialData = NULL;
+ }
+
+ char buffer[16384];
+ while (remaining > 0) {
+ int readSize = (remaining > sizeof(buffer) ? sizeof(buffer) : remaining);
+ int count = mDevice->mData.readData(mDevice->mEndpointIn, buffer, readSize);
+ int written;
+ if (count >= 0) {
+ int written = write(mFD, buffer, count);
+ // FIXME check error
+ remaining -= count;
+ } else {
+ break;
+ }
+ }
+
+ MtpResponseCode ret = mDevice->readResponse();
+ mDevice->mMutex.unlock();
+ return false;
+ }
+};
+
+ // returns the file descriptor for a pipe to read the object's data
+int MtpDevice::readObject(MtpObjectHandle handle, int objectSize) {
+ mMutex.lock();
+
+ ReadObjectThread* thread = new ReadObjectThread(this, handle, objectSize);
+ int fd = thread->init();
+ if (fd < 0) {
+ delete thread;
+ mMutex.unlock();
+ } else {
+ thread->run("ReadObjectThread");
+ }
+ return fd;
+}
bool MtpDevice::sendRequest(MtpOperationCode operation) {
- LOGD("sendRequest: %s\n", MtpDebug::getOperationCodeName(operation));
+ LOGV("sendRequest: %s\n", MtpDebug::getOperationCodeName(operation));
mRequest.setOperationCode(operation);
if (mTransactionID > 0)
mRequest.setTransactionID(mTransactionID++);
@@ -262,8 +451,8 @@ bool MtpDevice::sendRequest(MtpOperationCode operation) {
return (ret > 0);
}
-bool MtpDevice::sendData(MtpOperationCode operation) {
- LOGD("sendData\n");
+bool MtpDevice::sendData() {
+ LOGV("sendData\n");
mData.setOperationCode(mRequest.getOperationCode());
mData.setTransactionID(mRequest.getTransactionID());
int ret = mData.write(mEndpointOut);
@@ -274,19 +463,25 @@ bool MtpDevice::sendData(MtpOperationCode operation) {
bool MtpDevice::readData() {
mData.reset();
int ret = mData.read(mEndpointIn);
- LOGD("readData returned %d\n", ret);
+ LOGV("readData returned %d\n", ret);
if (ret >= MTP_CONTAINER_HEADER_SIZE) {
mData.dump();
return true;
}
else {
- LOGD("readResponse failed\n");
+ LOGV("readResponse failed\n");
return false;
}
}
+bool MtpDevice::writeDataHeader(MtpOperationCode operation, int dataLength) {
+ mData.setOperationCode(operation);
+ mData.setTransactionID(mRequest.getTransactionID());
+ return (!mData.writeDataHeader(mEndpointOut, dataLength));
+}
+
MtpResponseCode MtpDevice::readResponse() {
- LOGD("readResponse\n");
+ LOGV("readResponse\n");
int ret = mResponse.read(mEndpointIn);
if (ret >= MTP_CONTAINER_HEADER_SIZE) {
mResponse.dump();
diff --git a/media/mtp/MtpDevice.h b/media/mtp/MtpDevice.h
index e41a872..57f492f 100644
--- a/media/mtp/MtpDevice.h
+++ b/media/mtp/MtpDevice.h
@@ -22,6 +22,8 @@
#include "MtpResponsePacket.h"
#include "MtpTypes.h"
+#include <utils/threads.h>
+
struct usb_device;
namespace android {
@@ -52,6 +54,9 @@ private:
MtpDataPacket mData;
MtpResponsePacket mResponse;
+ // to ensure only one MTP transaction at a time
+ Mutex mMutex;
+
public:
MtpDevice(struct usb_device* device, int interface,
struct usb_endpoint *ep_in, struct usb_endpoint *ep_out,
@@ -73,16 +78,24 @@ public:
MtpObjectHandleList* getObjectHandles(MtpStorageID storageID, MtpObjectFormat format, MtpObjectHandle parent);
MtpObjectInfo* getObjectInfo(MtpObjectHandle handle);
void* getThumbnail(MtpObjectHandle handle, int& outLength);
+ MtpObjectHandle sendObjectInfo(MtpObjectInfo* info);
+ bool sendObject(MtpObjectInfo* info, int srcFD);
bool deleteObject(MtpObjectHandle handle);
MtpObjectHandle getParent(MtpObjectHandle handle);
MtpObjectHandle getStorageID(MtpObjectHandle handle);
MtpProperty* getDevicePropDesc(MtpDeviceProperty code);
+ // returns the file descriptor for a pipe to read the object's data
+ int readObject(MtpObjectHandle handle, int objectSize);
+
private:
+ friend class ReadObjectThread;
+
bool sendRequest(MtpOperationCode operation);
- bool sendData(MtpOperationCode operation);
+ bool sendData();
bool readData();
+ bool writeDataHeader(MtpOperationCode operation, int dataLength);
MtpResponseCode readResponse();
};
diff --git a/media/mtp/MtpDeviceInfo.cpp b/media/mtp/MtpDeviceInfo.cpp
index 025b8eb..5a9322e 100644
--- a/media/mtp/MtpDeviceInfo.cpp
+++ b/media/mtp/MtpDeviceInfo.cpp
@@ -88,9 +88,9 @@ void MtpDeviceInfo::read(MtpDataPacket& packet) {
}
void MtpDeviceInfo::print() {
- LOGD("Device Info:\n\tmStandardVersion: %d\n\tmVendorExtensionID: %d\n\tmVendorExtensionVersiony: %d\n",
+ LOGV("Device Info:\n\tmStandardVersion: %d\n\tmVendorExtensionID: %d\n\tmVendorExtensionVersiony: %d\n",
mStandardVersion, mVendorExtensionID, mVendorExtensionVersion);
- LOGD("\tmVendorExtensionDesc: %s\n\tmFunctionalCode: %d\n\tmManufacturer: %s\n\tmModel: %s\n\tmVersion: %s\n\tmSerial: %s\n",
+ LOGV("\tmVendorExtensionDesc: %s\n\tmFunctionalCode: %d\n\tmManufacturer: %s\n\tmModel: %s\n\tmVersion: %s\n\tmSerial: %s\n",
mVendorExtensionDesc, mFunctionalCode, mManufacturer, mModel, mVersion, mSerial);
}
diff --git a/media/mtp/MtpProperty.cpp b/media/mtp/MtpProperty.cpp
index 9eb8a5d..d6beb8a 100644
--- a/media/mtp/MtpProperty.cpp
+++ b/media/mtp/MtpProperty.cpp
@@ -191,9 +191,9 @@ void MtpProperty::write(MtpDataPacket& packet) {
}
void MtpProperty::print() {
- LOGD("MtpProperty %04X\n", mCode);
- LOGD(" type %04X\n", mType);
- LOGD(" writeable %s\n", (mWriteable ? "true" : "false"));
+ LOGV("MtpProperty %04X\n", mCode);
+ LOGV(" type %04X\n", mType);
+ LOGV(" writeable %s\n", (mWriteable ? "true" : "false"));
}
void MtpProperty::readValue(MtpDataPacket& packet, MtpPropertyValue& value) {
diff --git a/media/tests/CameraBrowser/Android.mk b/media/tests/CameraBrowser/Android.mk
index 1d81129..33d2976 100644
--- a/media/tests/CameraBrowser/Android.mk
+++ b/media/tests/CameraBrowser/Android.mk
@@ -1,8 +1,6 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
-LOCAL_MODULE_TAGS := tests
-
LOCAL_SRC_FILES := $(call all-subdir-java-files)
LOCAL_PACKAGE_NAME := CameraBrowser
diff --git a/media/tests/CameraBrowser/AndroidManifest.xml b/media/tests/CameraBrowser/AndroidManifest.xml
index dbbd62a..5a71179 100644
--- a/media/tests/CameraBrowser/AndroidManifest.xml
+++ b/media/tests/CameraBrowser/AndroidManifest.xml
@@ -1,6 +1,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.camerabrowser">
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+
<application android:label="@string/app_label">
<activity android:name="CameraBrowser" android:label="Camera Browser">
<intent-filter>
diff --git a/media/tests/CameraBrowser/res/menu/object_menu.xml b/media/tests/CameraBrowser/res/menu/object_menu.xml
index caea4ab..a0865f0 100644
--- a/media/tests/CameraBrowser/res/menu/object_menu.xml
+++ b/media/tests/CameraBrowser/res/menu/object_menu.xml
@@ -16,6 +16,8 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:id="@+id/save"
+ android:title="@string/save_item" />
<item android:id="@+id/delete"
android:title="@string/delete_item" />
</menu>
diff --git a/media/tests/CameraBrowser/res/values/strings.xml b/media/tests/CameraBrowser/res/values/strings.xml
index 8f94e6c..56c5111 100644
--- a/media/tests/CameraBrowser/res/values/strings.xml
+++ b/media/tests/CameraBrowser/res/values/strings.xml
@@ -32,9 +32,12 @@
<string name="keywords_label">Keywords: </string>
<!-- menu items -->
+ <string name="save_item">Save</string>
<string name="delete_item">Delete</string>
<!-- toasts -->
+ <string name="object_saved_message">Object saved</string>
+ <string name="save_failed_message">Could not save object</string>
<string name="object_deleted_message">Object deleted</string>
<string name="delete_failed_message">Could not delete object</string>
diff --git a/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectBrowser.java b/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectBrowser.java
index 34f8fff..a002028 100644
--- a/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectBrowser.java
+++ b/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectBrowser.java
@@ -26,16 +26,12 @@ import android.net.Uri;
import android.os.Bundle;
import android.provider.Mtp;
import android.util.Log;
-import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
-import android.widget.Toast;
/**
* A list view displaying all objects within a container (folder or storage unit).
@@ -119,47 +115,6 @@ public class ObjectBrowser extends ListActivity {
}
}
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.object_menu, menu);
- return true;
- }
-
- @Override
- public boolean onPrepareOptionsMenu(Menu menu) {
- int position = mList.getSelectedItemPosition();
- MenuItem item = menu.findItem(R.id.delete);
- item.setEnabled(position != AdapterView.INVALID_POSITION);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.delete:
- deleteSelected();
- return true;
- }
- return false;
- }
-
- private void deleteSelected() {
- int position = mList.getSelectedItemPosition();
- int rowID = (int)mAdapter.getItemId(position);
- Uri uri = Mtp.Object.getContentUri(mDeviceID, rowID);
-
- Log.d(TAG, "deleting " + uri);
-
- int result = getContentResolver().delete(uri, null, null);
- if (result > 0) {
- Toast.makeText(this, R.string.object_deleted_message, Toast.LENGTH_SHORT).show();
- mCursor.requery();
- } else {
- Toast.makeText(this, R.string.delete_failed_message, Toast.LENGTH_SHORT).show();
- }
- }
-
private class ObjectCursorAdapter extends ResourceCursorAdapter {
public ObjectCursorAdapter(Context context, Cursor c) {
diff --git a/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectViewer.java b/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectViewer.java
index 3033c54..aa49cd8 100644
--- a/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectViewer.java
+++ b/media/tests/CameraBrowser/src/com/android/camerabrowser/ObjectViewer.java
@@ -22,12 +22,25 @@ import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
+import android.os.Environment;
+import android.os.FileUtils;
+import android.os.ParcelFileDescriptor;
+import android.os.Process;
import android.provider.Mtp;
import android.util.Log;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
+import android.widget.Toast;
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.util.Calendar;
import java.util.Date;
/**
@@ -106,18 +119,134 @@ public class ObjectViewer extends Activity {
view.setText(c.getString(12));
byte[] thumbnail = c.getBlob(13);
if (thumbnail != null) {
- Log.d(TAG, "got thumbnail, length: " + thumbnail.length);
- for (int i = 0; i < 50; i++) {
- Log.d(TAG, " " + Integer.toHexString(thumbnail[i]));
- }
-
ImageView thumbView = (ImageView)findViewById(R.id.thumbnail);
Bitmap bitmap = BitmapFactory.decodeByteArray(thumbnail, 0, thumbnail.length);
- Log.d(TAG, "bitmap: " + bitmap);
if (bitmap != null) {
thumbView.setImageBitmap(bitmap);
}
}
}
}
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ MenuInflater inflater = getMenuInflater();
+ inflater.inflate(R.menu.object_menu, menu);
+ return true;
+ }
+
+ @Override
+ public boolean onPrepareOptionsMenu(Menu menu) {
+ MenuItem item = menu.findItem(R.id.save);
+ item.setEnabled(true);
+ item = menu.findItem(R.id.delete);
+ item.setEnabled(true);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case R.id.save:
+ save();
+ return true;
+ case R.id.delete:
+ delete();
+ return true;
+ }
+ return false;
+ }
+
+ private static String getTimestamp() {
+ Calendar c = Calendar.getInstance();
+ c.setTimeInMillis(System.currentTimeMillis());
+ return String.format("%tY-%tm-%td-%tH-%tM-%tS", c, c, c, c, c, c);
+ }
+
+ private void save() {
+ boolean success = false;
+ Uri uri = Mtp.Object.getContentUri(mDeviceID, mObjectID);
+ File destFile = null;
+ ParcelFileDescriptor pfd = null;
+ FileInputStream fis = null;
+ FileOutputStream fos = null;
+
+ try {
+ pfd = getContentResolver().openFileDescriptor(uri, "r");
+ Log.d(TAG, "save got pfd " + pfd);
+ if (pfd != null) {
+ fis = new FileInputStream(pfd.getFileDescriptor());
+ Log.d(TAG, "save got fis " + fis);
+ File destDir = Environment.getExternalStoragePublicDirectory(
+ Environment.DIRECTORY_DCIM);
+ destDir.mkdirs();
+ destFile = new File(destDir, "CameraBrowser-" + getTimestamp() + ".jpeg");
+
+
+ Log.d(TAG, "save got destFile " + destFile);
+
+ if (destFile.exists()) {
+ destFile.delete();
+ }
+ fos = new FileOutputStream(destFile);
+
+ byte[] buffer = new byte[65536];
+ int bytesRead;
+ while ((bytesRead = fis.read(buffer)) >= 0) {
+ fos.write(buffer, 0, bytesRead);
+ }
+
+ // temporary workaround until we straighten out permissions in /data/media
+ // 1015 is AID_SDCARD_RW
+ FileUtils.setPermissions(destDir.getPath(), 0775, Process.myUid(), 1015);
+ FileUtils.setPermissions(destFile.getPath(), 0664, Process.myUid(), 1015);
+
+ success = true;
+ }
+ } catch (Exception e) {
+ Log.e(TAG, "Exception in ObjectView.save", e);
+ } finally {
+ if (fis != null) {
+ try {
+ fis.close();
+ } catch (Exception e) {
+ }
+ }
+ if (fos != null) {
+ try {
+ fos.close();
+ } catch (Exception e) {
+ }
+ }
+ if (pfd != null) {
+ try {
+ pfd.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+
+ if (success) {
+ Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
+ intent.setData(Uri.fromFile(destFile));
+ sendBroadcast(intent);
+ Toast.makeText(this, R.string.object_saved_message, Toast.LENGTH_SHORT).show();
+ } else {
+ Toast.makeText(this, R.string.save_failed_message, Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ private void delete() {
+ Uri uri = Mtp.Object.getContentUri(mDeviceID, mObjectID);
+
+ Log.d(TAG, "deleting " + uri);
+
+ int result = getContentResolver().delete(uri, null, null);
+ if (result > 0) {
+ Toast.makeText(this, R.string.object_deleted_message, Toast.LENGTH_SHORT).show();
+ finish();
+ } else {
+ Toast.makeText(this, R.string.delete_failed_message, Toast.LENGTH_SHORT).show();
+ }
+ }
}
diff --git a/media/tests/mtp/Android.mk b/media/tests/mtp/Android.mk
new file mode 100644
index 0000000..a9074ed
--- /dev/null
+++ b/media/tests/mtp/Android.mk
@@ -0,0 +1,61 @@
+LOCAL_PATH:= $(call my-dir)
+
+ifneq ($(TARGET_SIMULATOR),true)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+ mtp.cpp \
+ MtpFile.cpp \
+
+LOCAL_C_INCLUDES += \
+ frameworks/base/media/mtp \
+
+LOCAL_CFLAGS := -DMTP_HOST
+
+LOCAL_MODULE := mtp
+
+LOCAL_STATIC_LIBRARIES := libmtp libusbhost libutils libcutils
+
+include $(BUILD_EXECUTABLE)
+
+endif
+
+ifeq ($(HOST_OS),linux)
+
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := \
+ mtp.cpp \
+ MtpFile.cpp \
+ ../../../libs/utils/RefBase.cpp \
+ ../../../libs/utils/SharedBuffer.cpp \
+ ../../../libs/utils/Threads.cpp \
+ ../../../libs/utils/VectorImpl.cpp \
+
+LOCAL_C_INCLUDES += \
+ frameworks/base/media/mtp \
+
+LOCAL_CFLAGS := -DMTP_HOST -g -O0
+
+have_readline := $(wildcard /usr/include/readline/readline.h)
+have_history := $(wildcard /usr/lib/libhistory*)
+ifneq ($(strip $(have_readline)),)
+LOCAL_CFLAGS += -DHAVE_READLINE=1
+endif
+
+LOCAL_LDLIBS += -lpthread
+ifneq ($(strip $(have_readline)),)
+LOCAL_LDLIBS += -lreadline -lncurses
+endif
+ifneq ($(strip $(have_history)),)
+LOCAL_LDLIBS += -lhistory
+endif
+
+LOCAL_MODULE := mtp
+
+LOCAL_STATIC_LIBRARIES := libmtp libusbhost libcutils
+
+include $(BUILD_HOST_EXECUTABLE)
+
+endif
diff --git a/media/tests/mtp/MtpFile.cpp b/media/tests/mtp/MtpFile.cpp
new file mode 100644
index 0000000..00d328e
--- /dev/null
+++ b/media/tests/mtp/MtpFile.cpp
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#include "MtpClient.h"
+#include "MtpDevice.h"
+#include "MtpDeviceInfo.h"
+#include "MtpObjectInfo.h"
+#include "MtpStorage.h"
+#include "MtpUtils.h"
+
+#include "MtpFile.h"
+
+namespace android {
+
+MtpClient* MtpFile::sClient = NULL;
+
+MtpFile::MtpFile(MtpDevice* device)
+ : mDevice(device),
+ mStorage(0),
+ mHandle(0)
+{
+}
+
+MtpFile::MtpFile(MtpDevice* device, MtpStorageID storage)
+ : mDevice(device),
+ mStorage(storage),
+ mHandle(0)
+{
+}
+
+MtpFile::MtpFile(MtpDevice* device, MtpStorageID storage, MtpObjectHandle handle)
+ : mDevice(device),
+ mStorage(storage),
+ mHandle(handle)
+{
+}
+
+MtpFile::MtpFile(MtpFile* file)
+ : mDevice(file->mDevice),
+ mStorage(file->mStorage),
+ mHandle(file->mHandle)
+{
+}
+
+MtpFile::~MtpFile() {
+}
+
+void MtpFile::print() {
+ if (mHandle) {
+
+ } else if (mStorage) {
+ printf("%x\n", mStorage);
+ } else {
+ int id = mDevice->getID();
+ MtpDeviceInfo* info = mDevice->getDeviceInfo();
+ if (info)
+ printf("%d\t%s %s %s\n", id, info->mManufacturer, info->mModel, info->mSerial);
+ else
+ printf("%d\t(no device info available)\n", id);
+ delete info;
+ }
+}
+
+MtpObjectInfo* MtpFile::getObjectInfo() {
+ return mDevice->getObjectInfo(mHandle);
+}
+
+void MtpFile::list() {
+ if (mStorage) {
+ MtpObjectHandleList* handles = mDevice->getObjectHandles(mStorage, 0,
+ (mHandle ? mHandle : -1));
+ if (handles) {
+ for (int i = 0; i < handles->size(); i++) {
+ MtpObjectHandle handle = (*handles)[i];
+ MtpObjectInfo* info = mDevice->getObjectInfo(handle);
+ if (info) {
+ char modified[100];
+ struct tm tm;
+
+ gmtime_r(&info->mDateModified, &tm);
+ strftime(modified, sizeof(modified), "%a %b %e %H:%M:%S GMT %Y", &tm);
+ printf("%s Handle: %d Format: %04X Size: %d Modified: %s\n",
+ info->mName, handle, info->mFormat, info->mCompressedSize, modified);
+ delete info;
+ }
+ }
+ delete handles;
+ }
+ } else {
+ // list storage units for device
+ MtpStorageIDList* storageList = mDevice->getStorageIDs();
+ for (int i = 0; i < storageList->size(); i++) {
+ MtpStorageID storageID = (*storageList)[i];
+ printf("%x\n", storageID);
+ }
+ }
+}
+
+void MtpFile::init(MtpClient* client) {
+ sClient = client;
+}
+
+MtpFile* MtpFile::parsePath(MtpFile* base, char* path) {
+ MtpDevice* device = NULL;
+ MtpStorageID storage = 0;
+ MtpObjectHandle handle = 0;
+
+ if (path[0] != '/' && base) {
+ device = base->mDevice;
+ storage = base->mStorage;
+ handle = base->mHandle;
+ }
+
+ // parse an absolute path
+ if (path[0] == '/')
+ path++;
+ char* tok = strtok(path, "/");
+ while (tok) {
+ if (storage) {
+ // find child of current handle
+ MtpObjectHandleList* handles = device->getObjectHandles(storage, 0,
+ (handle ? handle : -1));
+ MtpObjectHandle childHandle = 0;
+
+ if (handles) {
+ for (int i = 0; i < handles->size() && !childHandle; i++) {
+ MtpObjectHandle handle = (*handles)[i];
+ MtpObjectInfo* info = device->getObjectInfo(handle);
+ if (info && !strcmp(tok, info->mName))
+ childHandle = handle;
+ delete info;
+ }
+ delete handles;
+ }
+ if (childHandle)
+ handle = childHandle;
+ else
+ return NULL;
+ } else if (device) {
+ unsigned int id;
+ // find storage for the device
+ if (sscanf(tok, "%x", &id) == 1) {
+ MtpStorageIDList* storageList = device->getStorageIDs();
+ bool found = false;
+ for (int i = 0; i < storageList->size(); i++) {
+ if ((*storageList)[i] == id) {
+ found = true;
+ break;
+ }
+ }
+ if (found)
+ storage = id;
+ else
+ return NULL;
+ }
+ } else {
+ // find device
+ unsigned int id;
+ if (sscanf(tok, "%d", &id) == 1)
+ device = sClient->getDevice(id);
+ if (!device)
+ return NULL;
+ }
+
+ tok = strtok(NULL, "/");
+ }
+
+ if (device)
+ return new MtpFile(device, storage, handle);
+ else
+ return NULL;
+}
+
+}
diff --git a/media/tests/mtp/MtpFile.h b/media/tests/mtp/MtpFile.h
new file mode 100644
index 0000000..ab8762b
--- /dev/null
+++ b/media/tests/mtp/MtpFile.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#ifndef _MTP_FILE_H
+#define _MTP_FILE_H
+
+#include "MtpTypes.h"
+
+namespace android {
+
+class MtpClient;
+class MtpDevice;
+class MtpObjectInfo;
+
+// File-like abstraction for the interactive shell.
+// This can be used to represent an MTP device, storage unit or object
+// (either file or association).
+class MtpFile {
+private:
+ MtpDevice* mDevice;
+ MtpStorageID mStorage;
+ MtpObjectHandle mHandle;
+ static MtpClient* sClient;
+
+public:
+ MtpFile(MtpDevice* device);
+ MtpFile(MtpDevice* device, MtpStorageID storage);
+ MtpFile(MtpDevice* device, MtpStorageID storage, MtpObjectHandle handle);
+ MtpFile(MtpFile* file);
+ virtual ~MtpFile();
+
+ MtpObjectInfo* getObjectInfo();
+ void print();
+ void list();
+
+ inline MtpDevice* getDevice() const { return mDevice; }
+
+ static void init(MtpClient* client);
+ static MtpFile* parsePath(MtpFile* base, char* path);
+};
+
+}
+
+#endif // _MTP_DIRECTORY_H
diff --git a/media/tests/mtp/mtp.cpp b/media/tests/mtp/mtp.cpp
new file mode 100644
index 0000000..2c5e23b
--- /dev/null
+++ b/media/tests/mtp/mtp.cpp
@@ -0,0 +1,370 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#if HAVE_READLINE
+#include <readline/readline.h>
+#include <readline/history.h>
+#endif
+
+#include "MtpClient.h"
+#include "MtpDevice.h"
+#include "MtpObjectInfo.h"
+
+#include "MtpFile.h"
+
+#define PROMPT "mtp> "
+
+using namespace android;
+
+static MtpClient* sClient = NULL;
+
+// current working directory information for interactive shell
+static MtpFile* sCurrentDirectory = NULL;
+
+static MtpFile* parse_path(char* path) {
+ return MtpFile::parsePath(sCurrentDirectory, path);
+}
+
+class MyClient : public MtpClient {
+private:
+ virtual void deviceAdded(MtpDevice *device) {
+ }
+
+ virtual void deviceRemoved(MtpDevice *device) {
+ }
+
+public:
+};
+
+static void init() {
+ sClient = new MyClient;
+ sClient->start();
+ MtpFile::init(sClient);
+}
+
+static int set_cwd(int argc, char* argv[]) {
+ if (argc != 1) {
+ fprintf(stderr, "cd should have one argument\n");
+ return -1;
+ }
+ if (!strcmp(argv[0], "/")) {
+ delete sCurrentDirectory;
+ sCurrentDirectory = NULL;
+ }
+ else {
+ MtpFile* file = parse_path(argv[0]);
+ if (file) {
+ delete sCurrentDirectory;
+ sCurrentDirectory = file;
+ } else {
+ fprintf(stderr, "could not find %s\n", argv[0]);
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static void list_devices() {
+ // TODO - need to make sure the list will not change while iterating
+ MtpDeviceList& devices = sClient->getDeviceList();
+ for (int i = 0; i < devices.size(); i++) {
+ MtpDevice* device = devices[i];
+ MtpFile* file = new MtpFile(device);
+ file->print();
+ delete file;
+ }
+}
+
+static int list(int argc, char* argv[]) {
+ if (argc == 0) {
+ // list cwd
+ if (sCurrentDirectory) {
+ sCurrentDirectory->list();
+ } else {
+ list_devices();
+ }
+ }
+
+ for (int i = 0; i < argc; i++) {
+ char* path = argv[i];
+ if (!strcmp(path, "/")) {
+ list_devices();
+ } else {
+ MtpFile* file = parse_path(path);
+ if (!file) {
+ fprintf(stderr, "could not find %s\n", path);
+ return -1;
+ }
+ file->list();
+ }
+ }
+
+ return 0;
+}
+
+static int get_file(int argc, char* argv[]) {
+ int ret = -1;
+ int srcFD = -1;
+ int destFD = -1;
+ MtpFile* srcFile = NULL;
+ MtpObjectInfo* info = NULL;
+ char* dest;
+
+ if (argc < 1) {
+ fprintf(stderr, "not enough arguments\n");
+ return -1;
+ } else if (argc > 2) {
+ fprintf(stderr, "too many arguments\n");
+ return -1;
+ }
+
+ // find source object
+ char* src = argv[0];
+ srcFile = parse_path(src);
+ if (!srcFile) {
+ fprintf(stderr, "could not find %s\n", src);
+ return -1;
+ }
+ info = srcFile->getObjectInfo();
+ if (!info) {
+ fprintf(stderr, "could not find object info for %s\n", src);
+ goto fail;
+ }
+ if (info->mFormat == MTP_FORMAT_ASSOCIATION) {
+ fprintf(stderr, "copying directories not implemented yet\n");
+ goto fail;
+ }
+
+ dest = (argc > 1 ? argv[1] : info->mName);
+ destFD = open(dest, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
+ if (destFD < 0) {
+ fprintf(stderr, "could not create %s\n", dest);
+ goto fail;
+ }
+ srcFD = srcFile->getDevice()->readObject(info->mHandle, info->mCompressedSize);
+ if (srcFD < 0)
+ goto fail;
+
+ char buffer[65536];
+ while (1) {
+ int count = read(srcFD, buffer, sizeof(buffer));
+ if (count <= 0)
+ break;
+ write(destFD, buffer, count);
+ }
+ // FIXME - error checking and reporting
+ ret = 0;
+
+fail:
+ delete srcFile;
+ delete info;
+ if (srcFD >= 0)
+ close(srcFD);
+ if (destFD >= 0)
+ close(destFD);
+ return ret;
+}
+
+static int put_file(int argc, char* argv[]) {
+ int ret = -1;
+ int srcFD = -1;
+ MtpFile* destFile = NULL;
+ MtpObjectInfo* srcInfo = NULL;
+ MtpObjectInfo* destInfo = NULL;
+ MtpObjectHandle handle;
+ struct stat statbuf;
+ const char* lastSlash;
+
+ if (argc < 1) {
+ fprintf(stderr, "not enough arguments\n");
+ return -1;
+ } else if (argc > 2) {
+ fprintf(stderr, "too many arguments\n");
+ return -1;
+ }
+ const char* src = argv[0];
+ srcFD = open(src, O_RDONLY);
+ if (srcFD < 0) {
+ fprintf(stderr, "could not open %s\n", src);
+ goto fail;
+ }
+ if (argc == 2) {
+ char* dest = argv[1];
+ destFile = parse_path(dest);
+ if (!destFile) {
+ fprintf(stderr, "could not find %s\n", dest);
+ goto fail;
+ }
+ } else {
+ if (!sCurrentDirectory) {
+ fprintf(stderr, "current working directory not set\n");
+ goto fail;
+ }
+ destFile = new MtpFile(sCurrentDirectory);
+ }
+
+ destInfo = destFile->getObjectInfo();
+ if (!destInfo) {
+ fprintf(stderr, "could not find object info destination directory\n");
+ goto fail;
+ }
+ if (destInfo->mFormat != MTP_FORMAT_ASSOCIATION) {
+ fprintf(stderr, "destination not a directory\n");
+ goto fail;
+ }
+
+ if (fstat(srcFD, &statbuf))
+ goto fail;
+
+ srcInfo = new MtpObjectInfo(0);
+ srcInfo->mStorageID = destInfo->mStorageID;
+ srcInfo->mFormat = MTP_FORMAT_EXIF_JPEG; // FIXME
+ srcInfo->mCompressedSize = statbuf.st_size;
+ srcInfo->mParent = destInfo->mHandle;
+ lastSlash = strrchr(src, '/');
+ srcInfo->mName = strdup(lastSlash ? lastSlash + 1 : src);
+ srcInfo->mDateModified = statbuf.st_mtime;
+ handle = destFile->getDevice()->sendObjectInfo(srcInfo);
+ if (handle <= 0) {
+ printf("sendObjectInfo returned %04X\n", handle);
+ goto fail;
+ }
+ if (destFile->getDevice()->sendObject(srcInfo, srcFD))
+ ret = 0;
+
+fail:
+ delete destFile;
+ delete srcInfo;
+ delete destInfo;
+ if (srcFD >= 0)
+ close(srcFD);
+ printf("returning %d\n", ret);
+ return ret;
+}
+
+typedef int (* command_func)(int argc, char* argv[]);
+
+struct command_table_entry {
+ const char* name;
+ command_func func;
+};
+
+const command_table_entry command_list[] = {
+ { "cd", set_cwd },
+ { "ls", list },
+ { "get", get_file },
+ { "put", put_file },
+ { NULL, NULL },
+};
+
+
+static int do_command(int argc, char* argv[]) {
+ const command_table_entry* command = command_list;
+ const char* name = *argv++;
+ argc--;
+
+ while (command->name) {
+ if (!strcmp(command->name, name))
+ return command->func(argc, argv);
+ else
+ command++;
+ }
+ fprintf(stderr, "unknown command %s\n", name);
+ return -1;
+}
+
+static int shell() {
+ int argc;
+ int result = 0;
+#define MAX_ARGS 100
+ char* argv[MAX_ARGS];
+
+#if HAVE_READLINE
+ using_history();
+#endif
+
+ while (1) {
+#if HAVE_READLINE
+ char* line = readline(PROMPT);
+ if (!line) {
+ printf("\n");
+ exit(0);
+ }
+#else
+ char buffer[1000];
+ printf("%s", PROMPT);
+ char* line = NULL;
+ size_t length = 0;
+
+ buffer[0] = 0;
+ fgets(buffer, sizeof(buffer), stdin);
+ int count = strlen(buffer);
+ if (count > 0 && buffer[0] == EOF) {
+ printf("\n");
+ exit(0);
+ }
+ if (count > 0 && line[count - 1] == '\n')
+ line[count - 1] == 0;
+#endif
+ char* tok = strtok(line, " \t\n\r");
+ if (!tok)
+ continue;
+ if (!strcmp(tok, "quit") || !strcmp(tok, "exit")) {
+ exit(0);
+ }
+#if HAVE_READLINE
+ add_history(line);
+#endif
+ argc = 0;
+ while (tok) {
+ if (argc + 1 == MAX_ARGS) {
+ fprintf(stderr, "too many arguments\n");
+ result = -1;
+ goto bottom_of_loop;
+ }
+
+ argv[argc++] = strdup(tok);
+ tok = strtok(NULL, " \t\n\r");
+ }
+
+ result = do_command(argc, argv);
+
+bottom_of_loop:
+ for (int i = 0; i < argc; i++)
+ free(argv[i]);
+ free(line);
+ }
+
+ return result;
+}
+
+int main(int argc, char* argv[]) {
+ init();
+
+ if (argc == 1)
+ return shell();
+ else
+ return do_command(argc - 1, argv + 1);
+}
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index cc91f31..458ac9d 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -24,12 +24,14 @@ import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
import com.android.internal.view.BaseSurfaceHolder;
import com.android.internal.view.RootViewSurfaceTaker;
+import com.android.internal.view.StandaloneActionMode;
import com.android.internal.view.menu.ContextMenuBuilder;
import com.android.internal.view.menu.MenuBuilder;
import com.android.internal.view.menu.MenuDialogHelper;
import com.android.internal.view.menu.MenuPopupHelper;
import com.android.internal.view.menu.MenuView;
import com.android.internal.view.menu.SubMenuBuilder;
+import com.android.internal.widget.ActionBarContextView;
import com.android.internal.widget.ActionBarView;
import android.app.KeyguardManager;
@@ -55,6 +57,7 @@ import android.util.Config;
import android.util.EventLog;
import android.util.Log;
import android.util.SparseArray;
+import android.view.ActionMode;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.InputQueue;
@@ -78,12 +81,9 @@ import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
-import android.widget.ListPopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
-import java.lang.ref.WeakReference;
-
/**
* Android-specific Window.
* <p>
@@ -198,9 +198,6 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
/* Custom title feature is enabled and the user is trying to enable another feature */
throw new AndroidRuntimeException("You cannot combine custom titles with other title features");
}
- if (featureId == FEATURE_OPENGL) {
- getAttributes().memoryType = WindowManager.LayoutParams.MEMORY_TYPE_GPU;
- }
return super.requestFeature(featureId);
}
@@ -1643,6 +1640,9 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
private boolean mWatchingForMenu;
private int mDownY;
+ private ActionMode mActionMode;
+ private ActionBarContextView mActionModeView;
+
public DecorView(Context context, int featureId) {
super(context);
mFeatureId = featureId;
@@ -1930,6 +1930,45 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
return mContextMenuHelper != null;
}
+ @Override
+ public ActionMode startActionModeForChild(View originalView,
+ ActionMode.Callback callback) {
+ // originalView can be used here to be sure that we don't obscure
+ // relevant content with the context mode UI.
+ return startActionMode(callback);
+ }
+
+ @Override
+ public ActionMode startActionMode(ActionMode.Callback callback) {
+ if (mActionMode != null) {
+ mActionMode.finish();
+ }
+
+ ActionMode mode = getCallback().onStartActionMode(callback);
+ if (mode != null) {
+ mActionMode = mode;
+ } else {
+ if (mActionModeView == null) {
+ mActionModeView = (ActionBarContextView) findViewById(
+ com.android.internal.R.id.action_mode_bar);
+ }
+
+ if (mActionModeView != null) {
+ mode = new StandaloneActionMode(getContext(), mActionModeView,
+ new ActionModeCallbackWrapper(callback));
+ if (callback.onCreateActionMode(mode, mode.getMenu())) {
+ mode.invalidate();
+ mActionModeView.initForMode(mode);
+ mActionModeView.setVisibility(View.VISIBLE);
+ mActionMode = mode;
+ } else {
+ mActionMode = null;
+ }
+ }
+ }
+ return mActionMode;
+ }
+
public void startChanging() {
mChanging = true;
}
@@ -2109,6 +2148,35 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
+
+ /**
+ * Clears out internal reference when the action mode is destroyed.
+ */
+ private class ActionModeCallbackWrapper implements ActionMode.Callback {
+ private ActionMode.Callback mWrapped;
+
+ public ActionModeCallbackWrapper(ActionMode.Callback wrapped) {
+ mWrapped = wrapped;
+ }
+
+ public boolean onCreateActionMode(ActionMode mode, Menu menu) {
+ return mWrapped.onCreateActionMode(mode, menu);
+ }
+
+ public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
+ return mWrapped.onPrepareActionMode(mode, menu);
+ }
+
+ public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
+ return mWrapped.onActionItemClicked(mode, item);
+ }
+
+ public void onDestroyActionMode(ActionMode mode) {
+ mWrapped.onDestroyActionMode(mode);
+ mActionModeView.removeAllViews();
+ mActionMode = null;
+ }
+ }
}
protected DecorView generateDecor() {
@@ -2162,6 +2230,10 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
requestFeature(FEATURE_ACTION_BAR);
}
+ if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) {
+ requestFeature(FEATURE_ACTION_MODE_OVERLAY);
+ }
+
if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags()));
}
@@ -2244,13 +2316,7 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
if (mIsFloating) {
layoutResource = com.android.internal.R.layout.dialog_title;
} else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
- Configuration config = getContext().getResources().getConfiguration();
- if ((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_XLARGE) ==
- Configuration.SCREENLAYOUT_SIZE_XLARGE) {
- layoutResource = com.android.internal.R.layout.screen_xlarge_action_bar;
- } else {
- layoutResource = com.android.internal.R.layout.screen_action_bar;
- }
+ layoutResource = com.android.internal.R.layout.screen_action_bar;
} else {
layoutResource = com.android.internal.R.layout.screen_title;
}
diff --git a/services/audioflinger/AudioFlinger.cpp b/services/audioflinger/AudioFlinger.cpp
index b88e69d..3572d10 100644
--- a/services/audioflinger/AudioFlinger.cpp
+++ b/services/audioflinger/AudioFlinger.cpp
@@ -5408,8 +5408,13 @@ status_t AudioFlinger::EffectModule::configure()
this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount);
status_t cmdStatus;
- int size = sizeof(int);
- status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_CONFIGURE, sizeof(effect_config_t), &mConfig, &size, &cmdStatus);
+ uint32_t size = sizeof(int);
+ status_t status = (*mEffectInterface)->command(mEffectInterface,
+ EFFECT_CMD_CONFIGURE,
+ sizeof(effect_config_t),
+ &mConfig,
+ &size,
+ &cmdStatus);
if (status == 0) {
status = cmdStatus;
}
@@ -5427,8 +5432,13 @@ status_t AudioFlinger::EffectModule::init()
return NO_INIT;
}
status_t cmdStatus;
- int size = sizeof(status_t);
- status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_INIT, 0, NULL, &size, &cmdStatus);
+ uint32_t size = sizeof(status_t);
+ status_t status = (*mEffectInterface)->command(mEffectInterface,
+ EFFECT_CMD_INIT,
+ 0,
+ NULL,
+ &size,
+ &cmdStatus);
if (status == 0) {
status = cmdStatus;
}
@@ -5441,8 +5451,13 @@ status_t AudioFlinger::EffectModule::start_l()
return NO_INIT;
}
status_t cmdStatus;
- int size = sizeof(status_t);
- status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_ENABLE, 0, NULL, &size, &cmdStatus);
+ uint32_t size = sizeof(status_t);
+ status_t status = (*mEffectInterface)->command(mEffectInterface,
+ EFFECT_CMD_ENABLE,
+ 0,
+ NULL,
+ &size,
+ &cmdStatus);
if (status == 0) {
status = cmdStatus;
}
@@ -5455,15 +5470,24 @@ status_t AudioFlinger::EffectModule::stop_l()
return NO_INIT;
}
status_t cmdStatus;
- int size = sizeof(status_t);
- status_t status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_DISABLE, 0, NULL, &size, &cmdStatus);
+ uint32_t size = sizeof(status_t);
+ status_t status = (*mEffectInterface)->command(mEffectInterface,
+ EFFECT_CMD_DISABLE,
+ 0,
+ NULL,
+ &size,
+ &cmdStatus);
if (status == 0) {
status = cmdStatus;
}
return status;
}
-status_t AudioFlinger::EffectModule::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
+status_t AudioFlinger::EffectModule::command(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *replySize,
+ void *pReplyData)
{
Mutex::Autolock _l(mLock);
// LOGV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface);
@@ -5471,9 +5495,14 @@ status_t AudioFlinger::EffectModule::command(int cmdCode, int cmdSize, void *pCm
if (mEffectInterface == NULL) {
return NO_INIT;
}
- status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData);
+ status_t status = (*mEffectInterface)->command(mEffectInterface,
+ cmdCode,
+ cmdSize,
+ pCmdData,
+ replySize,
+ pReplyData);
if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) {
- int size = (replySize == NULL) ? 0 : *replySize;
+ uint32_t size = (replySize == NULL) ? 0 : *replySize;
for (size_t i = 1; i < mHandles.size(); i++) {
sp<EffectHandle> h = mHandles[i].promote();
if (h != 0) {
@@ -5549,13 +5578,18 @@ status_t AudioFlinger::EffectModule::setVolume(uint32_t *left, uint32_t *right,
status_t cmdStatus;
uint32_t volume[2];
uint32_t *pVolume = NULL;
- int size = sizeof(volume);
+ uint32_t size = sizeof(volume);
volume[0] = *left;
volume[1] = *right;
if (controller) {
pVolume = volume;
}
- status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_VOLUME, size, volume, &size, pVolume);
+ status = (*mEffectInterface)->command(mEffectInterface,
+ EFFECT_CMD_SET_VOLUME,
+ size,
+ volume,
+ &size,
+ pVolume);
if (controller && status == NO_ERROR && size == sizeof(volume)) {
*left = volume[0];
*right = volume[1];
@@ -5575,8 +5609,13 @@ status_t AudioFlinger::EffectModule::setDevice(uint32_t device)
return BAD_VALUE;
}
status_t cmdStatus;
- int size = sizeof(status_t);
- status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_DEVICE, sizeof(uint32_t), &device, &size, &cmdStatus);
+ uint32_t size = sizeof(status_t);
+ status = (*mEffectInterface)->command(mEffectInterface,
+ EFFECT_CMD_SET_DEVICE,
+ sizeof(uint32_t),
+ &device,
+ &size,
+ &cmdStatus);
if (status == NO_ERROR) {
status = cmdStatus;
}
@@ -5595,8 +5634,13 @@ status_t AudioFlinger::EffectModule::setMode(uint32_t mode)
return BAD_VALUE;
}
status_t cmdStatus;
- int size = sizeof(status_t);
- status = (*mEffectInterface)->command(mEffectInterface, EFFECT_CMD_SET_AUDIO_MODE, sizeof(int), &effectMode, &size, &cmdStatus);
+ uint32_t size = sizeof(status_t);
+ status = (*mEffectInterface)->command(mEffectInterface,
+ EFFECT_CMD_SET_AUDIO_MODE,
+ sizeof(int),
+ &effectMode,
+ &size,
+ &cmdStatus);
if (status == NO_ERROR) {
status = cmdStatus;
}
@@ -5805,9 +5849,14 @@ void AudioFlinger::EffectHandle::disconnect()
}
}
-status_t AudioFlinger::EffectHandle::command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData)
+status_t AudioFlinger::EffectHandle::command(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *replySize,
+ void *pReplyData)
{
-// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p", cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
+// LOGV("command(), cmdCode: %d, mHasControl: %d, mEffect: %p",
+// cmdCode, mHasControl, (mEffect == 0) ? 0 : mEffect.get());
// only get parameter command is permitted for applications not controlling the effect
if (!mHasControl && cmdCode != EFFECT_CMD_GET_PARAM) {
@@ -5829,7 +5878,7 @@ status_t AudioFlinger::EffectHandle::command(int cmdCode, int cmdSize, void *pCm
status_t status = NO_ERROR;
while (mCblk->serverIndex < mCblk->clientIndex) {
int reply;
- int rsize = sizeof(int);
+ uint32_t rsize = sizeof(int);
int *p = (int *)(mBuffer + mCblk->serverIndex);
int size = *p++;
if (((uint8_t *)p + size) > mBuffer + mCblk->clientIndex) {
@@ -5842,8 +5891,14 @@ status_t AudioFlinger::EffectHandle::command(int cmdCode, int cmdSize, void *pCm
mCblk->serverIndex += size;
continue;
}
- int psize = sizeof(effect_param_t) + ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) + param->vsize;
- status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM, psize, p, &rsize, &reply);
+ uint32_t psize = sizeof(effect_param_t) +
+ ((param->psize - 1) / sizeof(int) + 1) * sizeof(int) +
+ param->vsize;
+ status_t ret = mEffect->command(EFFECT_CMD_SET_PARAM,
+ psize,
+ p,
+ &rsize,
+ &reply);
if (ret == NO_ERROR) {
if (reply != NO_ERROR) {
status = reply;
@@ -5879,7 +5934,11 @@ void AudioFlinger::EffectHandle::setControl(bool hasControl, bool signal)
}
}
-void AudioFlinger::EffectHandle::commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData)
+void AudioFlinger::EffectHandle::commandExecuted(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t replySize,
+ void *pReplyData)
{
if (mEffectClient != 0) {
mEffectClient->commandExecuted(cmdCode, cmdSize, pCmdData, replySize, pReplyData);
diff --git a/services/audioflinger/AudioFlinger.h b/services/audioflinger/AudioFlinger.h
index a8c9a92..8f667a3 100644
--- a/services/audioflinger/AudioFlinger.h
+++ b/services/audioflinger/AudioFlinger.h
@@ -933,7 +933,11 @@ private:
int id() { return mId; }
void process();
void updateState();
- status_t command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData);
+ status_t command(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *replySize,
+ void *pReplyData);
void reset_l();
status_t configure();
@@ -1023,7 +1027,11 @@ private:
// IEffect
virtual status_t enable();
virtual status_t disable();
- virtual status_t command(int cmdCode, int cmdSize, void *pCmdData, int *replySize, void *pReplyData);
+ virtual status_t command(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t *replySize,
+ void *pReplyData);
virtual void disconnect();
virtual sp<IMemory> getCblk() const;
virtual status_t onTransact(uint32_t code, const Parcel& data,
@@ -1032,7 +1040,11 @@ private:
// Give or take control of effect module
void setControl(bool hasControl, bool signal);
- void commandExecuted(int cmdCode, int cmdSize, void *pCmdData, int replySize, void *pReplyData);
+ void commandExecuted(uint32_t cmdCode,
+ uint32_t cmdSize,
+ void *pCmdData,
+ uint32_t replySize,
+ void *pReplyData);
void setEnabled(bool enabled);
// Getters
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 9c504fe..311efc8 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -88,6 +88,8 @@ public class ConnectivityService extends IConnectivityManager.Stub {
*/
private List mNetRequestersPids[];
+ private WifiWatchdogService mWifiWatchdogService;
+
// priority order of the nettrackers
// (excluding dynamically set mNetworkPreference)
// TODO - move mNetworkTypePreference into this
@@ -318,6 +320,9 @@ public class ConnectivityService extends IConnectivityManager.Stub {
mNetTrackers[ConnectivityManager.TYPE_WIFI] = wst;
wst.startMonitoring();
+ //TODO: as part of WWS refactor, create only when needed
+ mWifiWatchdogService = new WifiWatchdogService(context, wst);
+
break;
case ConnectivityManager.TYPE_MOBILE:
mNetTrackers[netType] = new MobileDataStateTracker(context, mHandler,
diff --git a/services/java/com/android/server/CountryDetectorService.java b/services/java/com/android/server/CountryDetectorService.java
new file mode 100644
index 0000000..3081ebe
--- /dev/null
+++ b/services/java/com/android/server/CountryDetectorService.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package com.android.server;
+
+import java.util.HashMap;
+
+import com.android.server.location.ComprehensiveCountryDetector;
+
+import android.content.Context;
+import android.location.Country;
+import android.location.CountryListener;
+import android.location.ICountryDetector;
+import android.location.ICountryListener;
+import android.os.Handler;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.Process;
+import android.os.RemoteException;
+import android.util.Slog;
+
+/**
+ * This class detects the country that the user is in through
+ * {@link ComprehensiveCountryDetector}.
+ *
+ * @hide
+ */
+public class CountryDetectorService extends ICountryDetector.Stub implements Runnable {
+
+ /**
+ * The class represents the remote listener, it will also removes itself
+ * from listener list when the remote process was died.
+ */
+ private final class Receiver implements IBinder.DeathRecipient {
+ private final ICountryListener mListener;
+ private final IBinder mKey;
+
+ public Receiver(ICountryListener listener) {
+ mListener = listener;
+ mKey = listener.asBinder();
+ }
+
+ public void binderDied() {
+ removeListener(mKey);
+ }
+
+ @Override
+ public boolean equals(Object otherObj) {
+ if (otherObj instanceof Receiver) {
+ return mKey.equals(((Receiver) otherObj).mKey);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return mKey.hashCode();
+ }
+
+ public ICountryListener getListener() {
+ return mListener;
+ }
+ }
+
+ private final static String TAG = "CountryDetectorService";
+
+ private final HashMap<IBinder, Receiver> mReceivers;
+ private final Context mContext;
+ private ComprehensiveCountryDetector mCountryDetector;
+ private boolean mSystemReady;
+ private Handler mHandler;
+ private CountryListener mLocationBasedDetectorListener;
+
+ public CountryDetectorService(Context context) {
+ super();
+ mReceivers = new HashMap<IBinder, Receiver>();
+ mContext = context;
+ }
+
+ @Override
+ public Country detectCountry() throws RemoteException {
+ if (!mSystemReady) {
+ throw new RemoteException();
+ }
+ return mCountryDetector.detectCountry();
+ }
+
+ /**
+ * Add the ICountryListener into the listener list.
+ */
+ @Override
+ public void addCountryListener(ICountryListener listener) throws RemoteException {
+ if (!mSystemReady) {
+ throw new RemoteException();
+ }
+ addListener(listener);
+ }
+
+ /**
+ * Remove the ICountryListener from the listener list.
+ */
+ @Override
+ public void removeCountryListener(ICountryListener listener) throws RemoteException {
+ if (!mSystemReady) {
+ throw new RemoteException();
+ }
+ removeListener(listener.asBinder());
+ }
+
+ private void addListener(ICountryListener listener) {
+ synchronized (mReceivers) {
+ Receiver r = new Receiver(listener);
+ try {
+ listener.asBinder().linkToDeath(r, 0);
+ mReceivers.put(listener.asBinder(), r);
+ if (mReceivers.size() == 1) {
+ Slog.d(TAG, "The first listener is added");
+ setCountryListener(mLocationBasedDetectorListener);
+ }
+ } catch (RemoteException e) {
+ Slog.e(TAG, "linkToDeath failed:", e);
+ }
+ }
+ }
+
+ private void removeListener(IBinder key) {
+ synchronized (mReceivers) {
+ mReceivers.remove(key);
+ if (mReceivers.isEmpty()) {
+ setCountryListener(null);
+ Slog.d(TAG, "No listener is left");
+ }
+ }
+ }
+
+
+ protected void notifyReceivers(Country country) {
+ synchronized(mReceivers) {
+ for (Receiver receiver : mReceivers.values()) {
+ try {
+ receiver.getListener().onCountryDetected(country);
+ } catch (RemoteException e) {
+ // TODO: Shall we remove the receiver?
+ Slog.e(TAG, "notifyReceivers failed:", e);
+ }
+ }
+ }
+ }
+
+ void systemReady() {
+ // Shall we wait for the initialization finish.
+ Thread thread = new Thread(this, "CountryDetectorService");
+ thread.start();
+ }
+
+ private void initialize() {
+ mCountryDetector = new ComprehensiveCountryDetector(mContext);
+ mLocationBasedDetectorListener = new CountryListener() {
+ public void onCountryDetected(final Country country) {
+ mHandler.post(new Runnable() {
+ public void run() {
+ notifyReceivers(country);
+ }
+ });
+ }
+ };
+ }
+
+ public void run() {
+ Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
+ Looper.prepare();
+ mHandler = new Handler();
+ initialize();
+ mSystemReady = true;
+ Looper.loop();
+ }
+
+ protected void setCountryListener(final CountryListener listener) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mCountryDetector.setCountryListener(listener);
+ }
+ });
+ }
+
+ // For testing
+ boolean isSystemReady() {
+ return mSystemReady;
+ }
+}
diff --git a/services/java/com/android/server/DropBoxManagerService.java b/services/java/com/android/server/DropBoxManagerService.java
index 0de11c6..14b7d3e 100644
--- a/services/java/com/android/server/DropBoxManagerService.java
+++ b/services/java/com/android/server/DropBoxManagerService.java
@@ -690,8 +690,6 @@ public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
// was lost. Tombstones are expunged by age (see above).
if (mAllFiles.blocks > mCachedQuotaBlocks) {
- Slog.i(TAG, "Usage (" + mAllFiles.blocks + ") > Quota (" + mCachedQuotaBlocks + ")");
-
// Find a fair share amount of space to limit each tag
int unsqueezed = mAllFiles.blocks, squeezed = 0;
TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
diff --git a/services/java/com/android/server/PowerManagerService.java b/services/java/com/android/server/PowerManagerService.java
index e9d5efc..2fb481c 100644
--- a/services/java/com/android/server/PowerManagerService.java
+++ b/services/java/com/android/server/PowerManagerService.java
@@ -1030,36 +1030,71 @@ class PowerManagerService extends IPowerManager.Stub
}
}
- private void setTimeoutLocked(long now, int nextState)
- {
+ private void setTimeoutLocked(long now, int nextState) {
+ setTimeoutLocked(now, -1, nextState);
+ }
+
+ // If they gave a timeoutOverride it is the number of seconds
+ // to screen-off. Figure out where in the countdown cycle we
+ // should jump to.
+ private void setTimeoutLocked(long now, long timeoutOverride, int nextState) {
if (mBootCompleted) {
- mHandler.removeCallbacks(mTimeoutTask);
- mTimeoutTask.nextState = nextState;
- long when = now;
- switch (nextState)
- {
- case SCREEN_BRIGHT:
- when += mKeylightDelay;
- break;
- case SCREEN_DIM:
- if (mDimDelay >= 0) {
- when += mDimDelay;
- break;
- } else {
- Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
+ synchronized (mLocks) {
+ mHandler.removeCallbacks(mTimeoutTask);
+ mTimeoutTask.nextState = nextState;
+ long when = 0;
+ if (timeoutOverride <= 0) {
+ switch (nextState)
+ {
+ case SCREEN_BRIGHT:
+ when = now + mKeylightDelay;
+ break;
+ case SCREEN_DIM:
+ if (mDimDelay >= 0) {
+ when = now + mDimDelay;
+ break;
+ } else {
+ Slog.w(TAG, "mDimDelay=" + mDimDelay + " while trying to dim");
+ }
+ case SCREEN_OFF:
+ synchronized (mLocks) {
+ when = now + mScreenOffDelay;
+ }
+ break;
+ default:
+ when = now;
+ break;
}
- case SCREEN_OFF:
- synchronized (mLocks) {
- when += mScreenOffDelay;
+ } else {
+ override: {
+ if (timeoutOverride <= mScreenOffDelay) {
+ when = now + timeoutOverride;
+ nextState = SCREEN_OFF;
+ break override;
+ }
+ timeoutOverride -= mScreenOffDelay;
+
+ if (mDimDelay >= 0) {
+ if (timeoutOverride <= mDimDelay) {
+ when = now + timeoutOverride;
+ nextState = SCREEN_DIM;
+ break override;
+ }
+ timeoutOverride -= mDimDelay;
+ }
+
+ when = now + timeoutOverride;
+ nextState = SCREEN_BRIGHT;
}
- break;
- }
- if (mSpew) {
- Slog.d(TAG, "setTimeoutLocked now=" + now + " nextState=" + nextState
- + " when=" + when);
+ }
+ if (mSpew) {
+ Slog.d(TAG, "setTimeoutLocked now=" + now
+ + " timeoutOverride=" + timeoutOverride
+ + " nextState=" + nextState + " when=" + when);
+ }
+ mHandler.postAtTime(mTimeoutTask, when);
+ mNextTimeout = when; // for debugging
}
- mHandler.postAtTime(mTimeoutTask, when);
- mNextTimeout = when; // for debugging
}
}
@@ -1974,18 +2009,33 @@ class PowerManagerService extends IPowerManager.Stub
public void userActivityWithForce(long time, boolean noChangeLights, boolean force) {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
- userActivity(time, noChangeLights, OTHER_EVENT, force);
+ userActivity(time, -1, noChangeLights, OTHER_EVENT, force);
}
public void userActivity(long time, boolean noChangeLights) {
- userActivity(time, noChangeLights, OTHER_EVENT, false);
+ userActivity(time, -1, noChangeLights, OTHER_EVENT, false);
}
public void userActivity(long time, boolean noChangeLights, int eventType) {
- userActivity(time, noChangeLights, eventType, false);
+ userActivity(time, -1, noChangeLights, eventType, false);
}
public void userActivity(long time, boolean noChangeLights, int eventType, boolean force) {
+ userActivity(time, -1, noChangeLights, eventType, force);
+ }
+
+ /*
+ * Reset the user activity timeout to now + timeout. This overrides whatever else is going
+ * on with user activity. Don't use this function.
+ */
+ public void clearUserActivityTimeout(long now, long timeout) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
+ Slog.i(TAG, "clearUserActivity for " + timeout + "ms from now");
+ userActivity(now, timeout, false, OTHER_EVENT, false);
+ }
+
+ private void userActivity(long time, long timeoutOverride, boolean noChangeLights,
+ int eventType, boolean force) {
//mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
if (((mPokey & POKE_LOCK_IGNORE_CHEEK_EVENTS) != 0)
@@ -2057,7 +2107,7 @@ class PowerManagerService extends IPowerManager.Stub
mWakeLockState = mLocks.reactivateScreenLocksLocked();
setPowerState(mUserState | mWakeLockState, noChangeLights,
WindowManagerPolicy.OFF_BECAUSE_OF_USER);
- setTimeoutLocked(time, SCREEN_BRIGHT);
+ setTimeoutLocked(time, timeoutOverride, SCREEN_BRIGHT);
}
}
}
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 3586d21..2412b7d 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -206,6 +206,7 @@ class ServerThread extends Thread {
NotificationManagerService notification = null;
WallpaperManagerService wallpaper = null;
LocationManagerService location = null;
+ CountryDetectorService countryDetector = null;
if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
try {
@@ -316,6 +317,14 @@ class ServerThread extends Thread {
}
try {
+ Slog.i(TAG, "Country Detector");
+ countryDetector = new CountryDetectorService(context);
+ ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);
+ } catch (Throwable e) {
+ Slog.e(TAG, "Failure starting Country Detector", e);
+ }
+
+ try {
Slog.i(TAG, "Search Service");
ServiceManager.addService(Context.SEARCH_SERVICE,
new SearchManagerService(context));
@@ -479,6 +488,7 @@ class ServerThread extends Thread {
final InputMethodManagerService immF = imm;
final RecognitionManagerService recognitionF = recognition;
final LocationManagerService locationF = location;
+ final CountryDetectorService countryDetectorF = countryDetector;
// We now tell the activity manager it is okay to run third party
// code. It will call back into us once it has gotten to the state
@@ -506,6 +516,7 @@ class ServerThread extends Thread {
if (wallpaperF != null) wallpaperF.systemReady();
if (immF != null) immF.systemReady();
if (locationF != null) locationF.systemReady();
+ if (countryDetectorF != null) countryDetectorF.systemReady();
if (throttleF != null) throttleF.systemReady();
}
});
diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java
index 35baaa7..15080b2 100644
--- a/services/java/com/android/server/WifiService.java
+++ b/services/java/com/android/server/WifiService.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2010 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.
@@ -16,18 +16,6 @@
package com.android.server;
-import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
-import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
-import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
-import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
-import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
-
-import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
-import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
-import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
-import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING;
-import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
-
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothA2dp;
@@ -41,7 +29,6 @@ import android.content.pm.PackageManager;
import android.net.wifi.IWifiManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
-import android.net.wifi.WifiNative;
import android.net.wifi.WifiStateTracker;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
@@ -51,56 +38,43 @@ import android.net.ConnectivityManager;
import android.net.InterfaceConfiguration;
import android.net.NetworkStateTracker;
import android.net.DhcpInfo;
-import android.net.NetworkUtils;
import android.os.Binder;
-import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.INetworkManagementService;
-import android.os.Looper;
-import android.os.Message;
-import android.os.PowerManager;
-import android.os.Process;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.provider.Settings;
import android.util.Slog;
-import android.text.TextUtils;
import java.util.ArrayList;
-import java.util.BitSet;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
import java.util.List;
-import java.util.Map;
import java.util.Set;
-import java.util.regex.Pattern;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.io.FileDescriptor;
import java.io.PrintWriter;
-import java.net.UnknownHostException;
import com.android.internal.app.IBatteryStats;
-import android.app.backup.IBackupManager;
import com.android.server.am.BatteryStatsService;
import com.android.internal.R;
/**
* WifiService handles remote WiFi operation requests by implementing
- * the IWifiManager interface. It also creates a WifiMonitor to listen
- * for Wifi-related events.
+ * the IWifiManager interface.
*
* @hide
*/
+//TODO: Clean up multiple locks and implement WifiService
+// as a SM to track soft AP/client/adhoc bring up based
+// on device idle state, airplane mode and boot.
+
public class WifiService extends IWifiManager.Stub {
private static final String TAG = "WifiService";
- private static final boolean DBG = false;
- private static final Pattern scanResultPattern = Pattern.compile("\t+");
+ private static final boolean DBG = true;
+
private final WifiStateTracker mWifiStateTracker;
- /* TODO: fetch a configurable interface */
- private static final String SOFTAP_IFACE = "wl0.1";
private Context mContext;
- private int mWifiApState;
private AlarmManager mAlarmManager;
private PendingIntent mIdleIntent;
@@ -109,10 +83,8 @@ public class WifiService extends IWifiManager.Stub {
private boolean mDeviceIdle;
private int mPluggedType;
- private enum DriverAction {DRIVER_UNLOAD, NO_DRIVER_UNLOAD};
-
// true if the user enabled Wifi while in airplane mode
- private boolean mAirplaneModeOverwridden;
+ private AtomicBoolean mAirplaneModeOverwridden = new AtomicBoolean(false);
private final LockList mLocks = new LockList();
// some wifi lock statistics
@@ -128,9 +100,7 @@ public class WifiService extends IWifiManager.Stub {
private final IBatteryStats mBatteryStats;
- private INetworkManagementService nwService;
ConnectivityManager mCm;
- private WifiWatchdogService mWifiWatchdogService = null;
private String[] mWifiRegexs;
/**
@@ -142,46 +112,6 @@ public class WifiService extends IWifiManager.Stub {
*/
private static final long DEFAULT_IDLE_MILLIS = 15 * 60 * 1000; /* 15 minutes */
- private static final String WAKELOCK_TAG = "WifiService";
-
- // Wake lock used by other operations
- private static PowerManager.WakeLock sWakeLock;
-
- private static final int MESSAGE_ENABLE_WIFI = 0;
- private static final int MESSAGE_DISABLE_WIFI = 1;
- private static final int MESSAGE_STOP_WIFI = 2;
- private static final int MESSAGE_START_WIFI = 3;
- private static final int MESSAGE_UPDATE_STATE = 5;
- private static final int MESSAGE_START_ACCESS_POINT = 6;
- private static final int MESSAGE_STOP_ACCESS_POINT = 7;
- private static final int MESSAGE_SET_CHANNELS = 8;
-
-
- private final WifiHandler mWifiHandler;
-
- /*
- * Cache of scan results objects (size is somewhat arbitrary)
- */
- private static final int SCAN_RESULT_CACHE_SIZE = 80;
- private final LinkedHashMap<String, ScanResult> mScanResultCache;
-
- /*
- * Character buffer used to parse scan results (optimization)
- */
- private static final int SCAN_RESULT_BUFFER_SIZE = 512;
- private boolean mNeedReconfig;
-
- /*
- * Last UID that asked to enable WIFI.
- */
- private int mLastEnableUid = Process.myUid();
-
- /*
- * Last UID that asked to enable WIFI AP.
- */
- private int mLastApEnableUid = Process.myUid();
-
-
/**
* Number of allowed radio frequency channels in various regulatory domains.
* This list is sufficient for 802.11b/g networks (2.4GHz range).
@@ -191,46 +121,27 @@ public class WifiService extends IWifiManager.Stub {
private static final String ACTION_DEVICE_IDLE =
"com.android.server.WifiManager.action.DEVICE_IDLE";
+ private boolean mIsReceiverRegistered = false;
+
WifiService(Context context, WifiStateTracker tracker) {
mContext = context;
mWifiStateTracker = tracker;
mWifiStateTracker.enableRssiPolling(true);
mBatteryStats = BatteryStatsService.getService();
- IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
- nwService = INetworkManagementService.Stub.asInterface(b);
-
- mScanResultCache = new LinkedHashMap<String, ScanResult>(
- SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
- /*
- * Limit the cache size by SCAN_RESULT_CACHE_SIZE
- * elements
- */
- public boolean removeEldestEntry(Map.Entry eldest) {
- return SCAN_RESULT_CACHE_SIZE < this.size();
- }
- };
-
- HandlerThread wifiThread = new HandlerThread("WifiService");
- wifiThread.start();
- mWifiHandler = new WifiHandler(wifiThread.getLooper());
-
- mWifiStateTracker.setWifiState(WIFI_STATE_DISABLED);
- mWifiApState = WIFI_AP_STATE_DISABLED;
-
mAlarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
Intent idleIntent = new Intent(ACTION_DEVICE_IDLE, null);
mIdleIntent = PendingIntent.getBroadcast(mContext, IDLE_REQUEST, idleIntent, 0);
- PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
- sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
+ HandlerThread wifiThread = new HandlerThread("WifiService");
+ wifiThread.start();
mContext.registerReceiver(
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// clear our flag indicating the user has overwridden airplane mode
- mAirplaneModeOverwridden = false;
+ mAirplaneModeOverwridden.set(false);
// on airplane disable, restore Wifi if the saved state indicates so
if (!isAirplaneModeOn() && testAndClearWifiSavedState()) {
persistWifiEnabled(true);
@@ -245,11 +156,11 @@ public class WifiService extends IWifiManager.Stub {
@Override
public void onReceive(Context context, Intent intent) {
- ArrayList<String> available = intent.getStringArrayListExtra(
- ConnectivityManager.EXTRA_AVAILABLE_TETHER);
- ArrayList<String> active = intent.getStringArrayListExtra(
- ConnectivityManager.EXTRA_ACTIVE_TETHER);
- updateTetherState(available, active);
+ ArrayList<String> available = intent.getStringArrayListExtra(
+ ConnectivityManager.EXTRA_AVAILABLE_TETHER);
+ ArrayList<String> active = intent.getStringArrayListExtra(
+ ConnectivityManager.EXTRA_ACTIVE_TETHER);
+ updateTetherState(available, active);
}
},new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
@@ -301,17 +212,14 @@ public class WifiService extends IWifiManager.Stub {
}
} catch (Exception e) {
Slog.e(TAG, "Error configuring interface " + intf + ", :" + e);
- try {
- nwService.stopAccessPoint();
- } catch (Exception ee) {
- Slog.e(TAG, "Could not stop AP, :" + ee);
- }
- setWifiApEnabledState(WIFI_AP_STATE_FAILED, 0, DriverAction.DRIVER_UNLOAD);
+ setWifiApEnabled(null, false);
return;
}
if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
- Slog.e(TAG, "Error tethering "+intf);
+ Slog.e(TAG, "Error tethering on " + intf);
+ setWifiApEnabled(null, false);
+ return;
}
break;
}
@@ -353,12 +261,11 @@ public class WifiService extends IWifiManager.Stub {
/**
* see {@link android.net.wifi.WifiManager#pingSupplicant()}
- * @return {@code true} if the operation succeeds
+ * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
public boolean pingSupplicant() {
- enforceChangePermission();
-
- return mWifiStateTracker.ping();
+ enforceAccessPermission();
+ return mWifiStateTracker.pingSupplicant();
}
/**
@@ -367,19 +274,24 @@ public class WifiService extends IWifiManager.Stub {
*/
public boolean startScan(boolean forceActive) {
enforceChangePermission();
+ return mWifiStateTracker.startScan(forceActive);
+ }
- switch (mWifiStateTracker.getSupplicantState()) {
- case DISCONNECTED:
- case INACTIVE:
- case SCANNING:
- case DORMANT:
- break;
- default:
- mWifiStateTracker.setScanResultHandling(
- WifiStateTracker.SUPPL_SCAN_HANDLING_LIST_ONLY);
- break;
- }
- return mWifiStateTracker.scan(forceActive);
+ private void enforceAccessPermission() {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
+ "WifiService");
+ }
+
+ private void enforceChangePermission() {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
+ "WifiService");
+
+ }
+
+ private void enforceMulticastChangePermission() {
+ mContext.enforceCallingOrSelfPermission(
+ android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
+ "WifiService");
}
/**
@@ -388,168 +300,34 @@ public class WifiService extends IWifiManager.Stub {
* @return {@code true} if the enable/disable operation was
* started or is already in the queue.
*/
- public boolean setWifiEnabled(boolean enable) {
+ public synchronized boolean setWifiEnabled(boolean enable) {
enforceChangePermission();
- if (mWifiHandler == null) return false;
-
- synchronized (mWifiHandler) {
- // caller may not have WAKE_LOCK permission - it's not required here
- long ident = Binder.clearCallingIdentity();
- sWakeLock.acquire();
- Binder.restoreCallingIdentity(ident);
-
- mLastEnableUid = Binder.getCallingUid();
- // set a flag if the user is enabling Wifi while in airplane mode
- mAirplaneModeOverwridden = (enable && isAirplaneModeOn() && isAirplaneToggleable());
- sendEnableMessage(enable, true, Binder.getCallingUid());
- }
-
- return true;
- }
-
- /**
- * Enables/disables Wi-Fi synchronously.
- * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
- * @param persist {@code true} if the setting should be persisted.
- * @param uid The UID of the process making the request.
- * @return {@code true} if the operation succeeds (or if the existing state
- * is the same as the requested state)
- */
- private boolean setWifiEnabledBlocking(boolean enable, boolean persist, int uid) {
- final int eventualWifiState = enable ? WIFI_STATE_ENABLED : WIFI_STATE_DISABLED;
- final int wifiState = mWifiStateTracker.getWifiState();
-
- if (wifiState == eventualWifiState) {
- return true;
- }
- if (enable && isAirplaneModeOn() && !mAirplaneModeOverwridden) {
- return false;
- }
- /**
- * Multiple calls to unregisterReceiver() cause exception and a system crash.
- * This can happen if a supplicant is lost (or firmware crash occurs) and user indicates
- * disable wifi at the same time.
- * Avoid doing a disable when the current Wifi state is UNKNOWN
- * TODO: Handle driver load fail and supplicant lost as seperate states
- */
- if ((wifiState == WIFI_STATE_UNKNOWN) && !enable) {
- return false;
+ if (DBG) {
+ Slog.e(TAG, "Invoking mWifiStateTracker.setWifiEnabled\n");
}
- /**
- * Fail Wifi if AP is enabled
- * TODO: Deprecate WIFI_STATE_UNKNOWN and rename it
- * WIFI_STATE_FAILED
- */
- if ((mWifiApState == WIFI_AP_STATE_ENABLED) && enable) {
- setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
- return false;
+ // set a flag if the user is enabling Wifi while in airplane mode
+ if (enable && isAirplaneModeOn() && isAirplaneToggleable()) {
+ mAirplaneModeOverwridden.set(true);
}
- setWifiEnabledState(enable ? WIFI_STATE_ENABLING : WIFI_STATE_DISABLING, uid);
+ mWifiStateTracker.setWifiEnabled(enable);
+ persistWifiEnabled(enable);
if (enable) {
- if (!mWifiStateTracker.loadDriver()) {
- Slog.e(TAG, "Failed to load Wi-Fi driver.");
- setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
- return false;
+ if (!mIsReceiverRegistered) {
+ registerForBroadcasts();
+ mIsReceiverRegistered = true;
}
- if (!mWifiStateTracker.startSupplicant()) {
- mWifiStateTracker.unloadDriver();
- Slog.e(TAG, "Failed to start supplicant daemon.");
- setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
- return false;
- }
-
- registerForBroadcasts();
- mWifiStateTracker.startEventLoop();
-
- } else {
-
+ } else if (mIsReceiverRegistered){
mContext.unregisterReceiver(mReceiver);
- // Remove notification (it will no-op if it isn't visible)
- mWifiStateTracker.setNotificationVisible(false, 0, false, 0);
-
- boolean failedToStopSupplicantOrUnloadDriver = false;
-
- if (!mWifiStateTracker.stopSupplicant()) {
- Slog.e(TAG, "Failed to stop supplicant daemon.");
- setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
- failedToStopSupplicantOrUnloadDriver = true;
- }
-
- /**
- * Reset connections and disable interface
- * before we unload the driver
- */
- mWifiStateTracker.resetConnections(true);
-
- if (!mWifiStateTracker.unloadDriver()) {
- Slog.e(TAG, "Failed to unload Wi-Fi driver.");
- if (!failedToStopSupplicantOrUnloadDriver) {
- setWifiEnabledState(WIFI_STATE_UNKNOWN, uid);
- failedToStopSupplicantOrUnloadDriver = true;
- }
- }
-
- if (failedToStopSupplicantOrUnloadDriver) {
- return false;
- }
+ mIsReceiverRegistered = false;
}
- // Success!
-
- if (persist) {
- persistWifiEnabled(enable);
- }
- setWifiEnabledState(eventualWifiState, uid);
return true;
}
- private void setWifiEnabledState(int wifiState, int uid) {
- final int previousWifiState = mWifiStateTracker.getWifiState();
-
- long ident = Binder.clearCallingIdentity();
- try {
- if (wifiState == WIFI_STATE_ENABLED) {
- mBatteryStats.noteWifiOn(uid);
- } else if (wifiState == WIFI_STATE_DISABLED) {
- mBatteryStats.noteWifiOff(uid);
- }
- } catch (RemoteException e) {
- } finally {
- Binder.restoreCallingIdentity(ident);
- }
-
- // Update state
- mWifiStateTracker.setWifiState(wifiState);
-
- // Broadcast
- final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
- intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
- intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
- intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
- mContext.sendStickyBroadcast(intent);
- }
-
- private void enforceAccessPermission() {
- mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE,
- "WifiService");
- }
-
- private void enforceChangePermission() {
- mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE,
- "WifiService");
-
- }
-
- private void enforceMulticastChangePermission() {
- mContext.enforceCallingOrSelfPermission(
- android.Manifest.permission.CHANGE_WIFI_MULTICAST_STATE,
- "WifiService");
- }
-
/**
* see {@link WifiManager#getWifiState()}
* @return One of {@link WifiManager#WIFI_STATE_DISABLED},
@@ -564,62 +342,49 @@ public class WifiService extends IWifiManager.Stub {
}
/**
- * see {@link android.net.wifi.WifiManager#disconnect()}
- * @return {@code true} if the operation succeeds
- */
- public boolean disconnect() {
- enforceChangePermission();
-
- return mWifiStateTracker.disconnect();
- }
-
- /**
- * see {@link android.net.wifi.WifiManager#reconnect()}
- * @return {@code true} if the operation succeeds
- */
- public boolean reconnect() {
- enforceChangePermission();
-
- return mWifiStateTracker.reconnectCommand();
- }
-
- /**
- * see {@link android.net.wifi.WifiManager#reassociate()}
- * @return {@code true} if the operation succeeds
- */
- public boolean reassociate() {
- enforceChangePermission();
-
- return mWifiStateTracker.reassociate();
- }
-
- /**
* see {@link android.net.wifi.WifiManager#setWifiApEnabled(WifiConfiguration, boolean)}
* @param wifiConfig SSID, security and channel details as
* part of WifiConfiguration
- * @param enabled, true to enable and false to disable
+ * @param enabled true to enable and false to disable
* @return {@code true} if the start operation was
* started or is already in the queue.
*/
- public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
+ public synchronized boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
enforceChangePermission();
- if (mWifiHandler == null) return false;
-
- synchronized (mWifiHandler) {
-
- long ident = Binder.clearCallingIdentity();
- sWakeLock.acquire();
- Binder.restoreCallingIdentity(ident);
- mLastApEnableUid = Binder.getCallingUid();
- sendAccessPointMessage(enabled, wifiConfig, Binder.getCallingUid());
+ if (enabled) {
+ /* Use default config if there is no existing config */
+ if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
+ wifiConfig = new WifiConfiguration();
+ wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
+ wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
+ }
+ setWifiApConfiguration(wifiConfig);
}
+ mWifiStateTracker.setWifiApEnabled(wifiConfig, enabled);
+
return true;
}
- public WifiConfiguration getWifiApConfiguration() {
+ /**
+ * see {@link WifiManager#getWifiApState()}
+ * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
+ * {@link WifiManager#WIFI_AP_STATE_DISABLING},
+ * {@link WifiManager#WIFI_AP_STATE_ENABLED},
+ * {@link WifiManager#WIFI_AP_STATE_ENABLING},
+ * {@link WifiManager#WIFI_AP_STATE_FAILED}
+ */
+ public int getWifiApEnabledState() {
enforceAccessPermission();
+ return mWifiStateTracker.getWifiApState();
+ }
+
+ /**
+ * see {@link WifiManager#getWifiApConfiguration()}
+ * @return soft access point configuration
+ */
+ public synchronized WifiConfiguration getWifiApConfiguration() {
final ContentResolver cr = mContext.getContentResolver();
WifiConfiguration wifiConfig = new WifiConfiguration();
int authType;
@@ -637,7 +402,11 @@ public class WifiService extends IWifiManager.Stub {
}
}
- public void setWifiApConfiguration(WifiConfiguration wifiConfig) {
+ /**
+ * see {@link WifiManager#setWifiApConfiguration(WifiConfiguration)}
+ * @param wifiConfig WifiConfiguration details for soft access point
+ */
+ public synchronized void setWifiApConfiguration(WifiConfiguration wifiConfig) {
enforceChangePermission();
final ContentResolver cr = mContext.getContentResolver();
boolean isWpa;
@@ -653,143 +422,30 @@ public class WifiService extends IWifiManager.Stub {
}
/**
- * Enables/disables Wi-Fi AP synchronously. The driver is loaded
- * and soft access point configured as a single operation.
- * @param enable {@code true} to turn Wi-Fi on, {@code false} to turn it off.
- * @param uid The UID of the process making the request.
- * @param wifiConfig The WifiConfiguration for AP
- * @return {@code true} if the operation succeeds (or if the existing state
- * is the same as the requested state)
+ * see {@link android.net.wifi.WifiManager#disconnect()}
+ * @return {@code true} if the operation succeeds
*/
- private boolean setWifiApEnabledBlocking(boolean enable,
- int uid, WifiConfiguration wifiConfig) {
- final int eventualWifiApState = enable ? WIFI_AP_STATE_ENABLED : WIFI_AP_STATE_DISABLED;
-
- if (mWifiApState == eventualWifiApState) {
- /* Configuration changed on a running access point */
- if(enable && (wifiConfig != null)) {
- try {
- nwService.setAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
- SOFTAP_IFACE);
- setWifiApConfiguration(wifiConfig);
- return true;
- } catch(Exception e) {
- Slog.e(TAG, "Exception in nwService during AP restart");
- try {
- nwService.stopAccessPoint();
- } catch (Exception ee) {
- Slog.e(TAG, "Could not stop AP, :" + ee);
- }
- setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
- return false;
- }
- } else {
- return true;
- }
- }
-
- /**
- * Fail AP if Wifi is enabled
- */
- if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLED) && enable) {
- setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
- return false;
- }
-
- setWifiApEnabledState(enable ? WIFI_AP_STATE_ENABLING :
- WIFI_AP_STATE_DISABLING, uid, DriverAction.NO_DRIVER_UNLOAD);
-
- if (enable) {
-
- /* Use default config if there is no existing config */
- if (wifiConfig == null && ((wifiConfig = getWifiApConfiguration()) == null)) {
- wifiConfig = new WifiConfiguration();
- wifiConfig.SSID = mContext.getString(R.string.wifi_tether_configure_ssid_default);
- wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE);
- }
-
- if (!mWifiStateTracker.loadDriver()) {
- Slog.e(TAG, "Failed to load Wi-Fi driver for AP mode");
- setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
- return false;
- }
-
- try {
- nwService.startAccessPoint(wifiConfig, mWifiStateTracker.getInterfaceName(),
- SOFTAP_IFACE);
- } catch(Exception e) {
- Slog.e(TAG, "Exception in startAccessPoint()");
- setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
- return false;
- }
-
- setWifiApConfiguration(wifiConfig);
-
- } else {
-
- try {
- nwService.stopAccessPoint();
- } catch(Exception e) {
- Slog.e(TAG, "Exception in stopAccessPoint()");
- setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.DRIVER_UNLOAD);
- return false;
- }
-
- if (!mWifiStateTracker.unloadDriver()) {
- Slog.e(TAG, "Failed to unload Wi-Fi driver for AP mode");
- setWifiApEnabledState(WIFI_AP_STATE_FAILED, uid, DriverAction.NO_DRIVER_UNLOAD);
- return false;
- }
- }
-
- setWifiApEnabledState(eventualWifiApState, uid, DriverAction.NO_DRIVER_UNLOAD);
- return true;
+ public boolean disconnect() {
+ enforceChangePermission();
+ return mWifiStateTracker.disconnectCommand();
}
/**
- * see {@link WifiManager#getWifiApState()}
- * @return One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
- * {@link WifiManager#WIFI_AP_STATE_DISABLING},
- * {@link WifiManager#WIFI_AP_STATE_ENABLED},
- * {@link WifiManager#WIFI_AP_STATE_ENABLING},
- * {@link WifiManager#WIFI_AP_STATE_FAILED}
+ * see {@link android.net.wifi.WifiManager#reconnect()}
+ * @return {@code true} if the operation succeeds
*/
- public int getWifiApEnabledState() {
- enforceAccessPermission();
- return mWifiApState;
+ public boolean reconnect() {
+ enforceChangePermission();
+ return mWifiStateTracker.reconnectCommand();
}
- private void setWifiApEnabledState(int wifiAPState, int uid, DriverAction flag) {
- final int previousWifiApState = mWifiApState;
-
- /**
- * Unload the driver if going to a failed state
- */
- if ((mWifiApState == WIFI_AP_STATE_FAILED) && (flag == DriverAction.DRIVER_UNLOAD)) {
- mWifiStateTracker.unloadDriver();
- }
-
- long ident = Binder.clearCallingIdentity();
- try {
- if (wifiAPState == WIFI_AP_STATE_ENABLED) {
- mBatteryStats.noteWifiOn(uid);
- } else if (wifiAPState == WIFI_AP_STATE_DISABLED) {
- mBatteryStats.noteWifiOff(uid);
- }
- } catch (RemoteException e) {
- } finally {
- Binder.restoreCallingIdentity(ident);
- }
-
- // Update state
- mWifiApState = wifiAPState;
-
- // Broadcast
- final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
- intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
- intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiAPState);
- intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
- mContext.sendStickyBroadcast(intent);
+ /**
+ * see {@link android.net.wifi.WifiManager#reassociate()}
+ * @return {@code true} if the operation succeeds
+ */
+ public boolean reassociate() {
+ enforceChangePermission();
+ return mWifiStateTracker.reassociateCommand();
}
/**
@@ -798,217 +454,7 @@ public class WifiService extends IWifiManager.Stub {
*/
public List<WifiConfiguration> getConfiguredNetworks() {
enforceAccessPermission();
- String listStr;
-
- /*
- * We don't cache the list, because we want to allow
- * for the possibility that the configuration file
- * has been modified through some external means,
- * such as the wpa_cli command line program.
- */
- listStr = mWifiStateTracker.listNetworks();
-
- List<WifiConfiguration> networks =
- new ArrayList<WifiConfiguration>();
- if (listStr == null)
- return networks;
-
- String[] lines = listStr.split("\n");
- // Skip the first line, which is a header
- for (int i = 1; i < lines.length; i++) {
- String[] result = lines[i].split("\t");
- // network-id | ssid | bssid | flags
- WifiConfiguration config = new WifiConfiguration();
- try {
- config.networkId = Integer.parseInt(result[0]);
- } catch(NumberFormatException e) {
- continue;
- }
- if (result.length > 3) {
- if (result[3].indexOf("[CURRENT]") != -1)
- config.status = WifiConfiguration.Status.CURRENT;
- else if (result[3].indexOf("[DISABLED]") != -1)
- config.status = WifiConfiguration.Status.DISABLED;
- else
- config.status = WifiConfiguration.Status.ENABLED;
- } else {
- config.status = WifiConfiguration.Status.ENABLED;
- }
- readNetworkVariables(config);
- networks.add(config);
- }
-
- return networks;
- }
-
- /**
- * Read the variables from the supplicant daemon that are needed to
- * fill in the WifiConfiguration object.
- * <p/>
- * The caller must hold the synchronization monitor.
- * @param config the {@link WifiConfiguration} object to be filled in.
- */
- private void readNetworkVariables(WifiConfiguration config) {
-
- int netId = config.networkId;
- if (netId < 0)
- return;
-
- /*
- * TODO: maybe should have a native method that takes an array of
- * variable names and returns an array of values. But we'd still
- * be doing a round trip to the supplicant daemon for each variable.
- */
- String value;
-
- value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
- if (!TextUtils.isEmpty(value)) {
- config.SSID = value;
- } else {
- config.SSID = null;
- }
-
- value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
- if (!TextUtils.isEmpty(value)) {
- config.BSSID = value;
- } else {
- config.BSSID = null;
- }
-
- value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
- config.priority = -1;
- if (!TextUtils.isEmpty(value)) {
- try {
- config.priority = Integer.parseInt(value);
- } catch (NumberFormatException ignore) {
- }
- }
-
- value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
- config.hiddenSSID = false;
- if (!TextUtils.isEmpty(value)) {
- try {
- config.hiddenSSID = Integer.parseInt(value) != 0;
- } catch (NumberFormatException ignore) {
- }
- }
-
- value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
- config.wepTxKeyIndex = -1;
- if (!TextUtils.isEmpty(value)) {
- try {
- config.wepTxKeyIndex = Integer.parseInt(value);
- } catch (NumberFormatException ignore) {
- }
- }
-
- /*
- * Get up to 4 WEP keys. Note that the actual keys are not passed back,
- * just a "*" if the key is set, or the null string otherwise.
- */
- for (int i = 0; i < 4; i++) {
- value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.wepKeyVarNames[i]);
- if (!TextUtils.isEmpty(value)) {
- config.wepKeys[i] = value;
- } else {
- config.wepKeys[i] = null;
- }
- }
-
- /*
- * Get the private shared key. Note that the actual keys are not passed back,
- * just a "*" if the key is set, or the null string otherwise.
- */
- value = mWifiStateTracker.getNetworkVariable(netId, WifiConfiguration.pskVarName);
- if (!TextUtils.isEmpty(value)) {
- config.preSharedKey = value;
- } else {
- config.preSharedKey = null;
- }
-
- value = mWifiStateTracker.getNetworkVariable(config.networkId,
- WifiConfiguration.Protocol.varName);
- if (!TextUtils.isEmpty(value)) {
- String vals[] = value.split(" ");
- for (String val : vals) {
- int index =
- lookupString(val, WifiConfiguration.Protocol.strings);
- if (0 <= index) {
- config.allowedProtocols.set(index);
- }
- }
- }
-
- value = mWifiStateTracker.getNetworkVariable(config.networkId,
- WifiConfiguration.KeyMgmt.varName);
- if (!TextUtils.isEmpty(value)) {
- String vals[] = value.split(" ");
- for (String val : vals) {
- int index =
- lookupString(val, WifiConfiguration.KeyMgmt.strings);
- if (0 <= index) {
- config.allowedKeyManagement.set(index);
- }
- }
- }
-
- value = mWifiStateTracker.getNetworkVariable(config.networkId,
- WifiConfiguration.AuthAlgorithm.varName);
- if (!TextUtils.isEmpty(value)) {
- String vals[] = value.split(" ");
- for (String val : vals) {
- int index =
- lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
- if (0 <= index) {
- config.allowedAuthAlgorithms.set(index);
- }
- }
- }
-
- value = mWifiStateTracker.getNetworkVariable(config.networkId,
- WifiConfiguration.PairwiseCipher.varName);
- if (!TextUtils.isEmpty(value)) {
- String vals[] = value.split(" ");
- for (String val : vals) {
- int index =
- lookupString(val, WifiConfiguration.PairwiseCipher.strings);
- if (0 <= index) {
- config.allowedPairwiseCiphers.set(index);
- }
- }
- }
-
- value = mWifiStateTracker.getNetworkVariable(config.networkId,
- WifiConfiguration.GroupCipher.varName);
- if (!TextUtils.isEmpty(value)) {
- String vals[] = value.split(" ");
- for (String val : vals) {
- int index =
- lookupString(val, WifiConfiguration.GroupCipher.strings);
- if (0 <= index) {
- config.allowedGroupCiphers.set(index);
- }
- }
- }
-
- for (WifiConfiguration.EnterpriseField field :
- config.enterpriseFields) {
- value = mWifiStateTracker.getNetworkVariable(netId,
- field.varName());
- if (!TextUtils.isEmpty(value)) {
- if (field != config.eap) value = removeDoubleQuotes(value);
- field.setValue(value);
- }
- }
- }
-
- private static String removeDoubleQuotes(String string) {
- if (string.length() <= 2) return "";
- return string.substring(1, string.length() - 1);
- }
-
- private static String convertToQuotedString(String string) {
- return "\"" + string + "\"";
+ return mWifiStateTracker.getConfiguredNetworks();
}
/**
@@ -1018,280 +464,10 @@ public class WifiService extends IWifiManager.Stub {
*/
public int addOrUpdateNetwork(WifiConfiguration config) {
enforceChangePermission();
-
- /*
- * If the supplied networkId is -1, we create a new empty
- * network configuration. Otherwise, the networkId should
- * refer to an existing configuration.
- */
- int netId = config.networkId;
- boolean newNetwork = netId == -1;
- boolean doReconfig = false;
- // networkId of -1 means we want to create a new network
- synchronized (mWifiStateTracker) {
- if (newNetwork) {
- netId = mWifiStateTracker.addNetwork();
- if (netId < 0) {
- if (DBG) {
- Slog.d(TAG, "Failed to add a network!");
- }
- return -1;
- }
- doReconfig = true;
- }
- mNeedReconfig = mNeedReconfig || doReconfig;
- }
-
- setVariables: {
- /*
- * Note that if a networkId for a non-existent network
- * was supplied, then the first setNetworkVariable()
- * will fail, so we don't bother to make a separate check
- * for the validity of the ID up front.
- */
- if (config.SSID != null &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.ssidVarName,
- config.SSID)) {
- if (DBG) {
- Slog.d(TAG, "failed to set SSID: "+config.SSID);
- }
- break setVariables;
- }
-
- if (config.BSSID != null &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.bssidVarName,
- config.BSSID)) {
- if (DBG) {
- Slog.d(TAG, "failed to set BSSID: "+config.BSSID);
- }
- break setVariables;
- }
-
- String allowedKeyManagementString =
- makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
- if (config.allowedKeyManagement.cardinality() != 0 &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.KeyMgmt.varName,
- allowedKeyManagementString)) {
- if (DBG) {
- Slog.d(TAG, "failed to set key_mgmt: "+
- allowedKeyManagementString);
- }
- break setVariables;
- }
-
- String allowedProtocolsString =
- makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
- if (config.allowedProtocols.cardinality() != 0 &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.Protocol.varName,
- allowedProtocolsString)) {
- if (DBG) {
- Slog.d(TAG, "failed to set proto: "+
- allowedProtocolsString);
- }
- break setVariables;
- }
-
- String allowedAuthAlgorithmsString =
- makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
- if (config.allowedAuthAlgorithms.cardinality() != 0 &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.AuthAlgorithm.varName,
- allowedAuthAlgorithmsString)) {
- if (DBG) {
- Slog.d(TAG, "failed to set auth_alg: "+
- allowedAuthAlgorithmsString);
- }
- break setVariables;
- }
-
- String allowedPairwiseCiphersString =
- makeString(config.allowedPairwiseCiphers, WifiConfiguration.PairwiseCipher.strings);
- if (config.allowedPairwiseCiphers.cardinality() != 0 &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.PairwiseCipher.varName,
- allowedPairwiseCiphersString)) {
- if (DBG) {
- Slog.d(TAG, "failed to set pairwise: "+
- allowedPairwiseCiphersString);
- }
- break setVariables;
- }
-
- String allowedGroupCiphersString =
- makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
- if (config.allowedGroupCiphers.cardinality() != 0 &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.GroupCipher.varName,
- allowedGroupCiphersString)) {
- if (DBG) {
- Slog.d(TAG, "failed to set group: "+
- allowedGroupCiphersString);
- }
- break setVariables;
- }
-
- // Prevent client screw-up by passing in a WifiConfiguration we gave it
- // by preventing "*" as a key.
- if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
- !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.pskVarName,
- config.preSharedKey)) {
- if (DBG) {
- Slog.d(TAG, "failed to set psk: "+config.preSharedKey);
- }
- break setVariables;
- }
-
- boolean hasSetKey = false;
- if (config.wepKeys != null) {
- for (int i = 0; i < config.wepKeys.length; i++) {
- // Prevent client screw-up by passing in a WifiConfiguration we gave it
- // by preventing "*" as a key.
- if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
- if (!mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.wepKeyVarNames[i],
- config.wepKeys[i])) {
- if (DBG) {
- Slog.d(TAG,
- "failed to set wep_key"+i+": " +
- config.wepKeys[i]);
- }
- break setVariables;
- }
- hasSetKey = true;
- }
- }
- }
-
- if (hasSetKey) {
- if (!mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.wepTxKeyIdxVarName,
- Integer.toString(config.wepTxKeyIndex))) {
- if (DBG) {
- Slog.d(TAG,
- "failed to set wep_tx_keyidx: "+
- config.wepTxKeyIndex);
- }
- break setVariables;
- }
- }
-
- if (!mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.priorityVarName,
- Integer.toString(config.priority))) {
- if (DBG) {
- Slog.d(TAG, config.SSID + ": failed to set priority: "
- +config.priority);
- }
- break setVariables;
- }
-
- if (config.hiddenSSID && !mWifiStateTracker.setNetworkVariable(
- netId,
- WifiConfiguration.hiddenSSIDVarName,
- Integer.toString(config.hiddenSSID ? 1 : 0))) {
- if (DBG) {
- Slog.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
- config.hiddenSSID);
- }
- break setVariables;
- }
-
- for (WifiConfiguration.EnterpriseField field
- : config.enterpriseFields) {
- String varName = field.varName();
- String value = field.value();
- if (value != null) {
- if (field != config.eap) {
- value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
- }
- if (!mWifiStateTracker.setNetworkVariable(
- netId,
- varName,
- value)) {
- if (DBG) {
- Slog.d(TAG, config.SSID + ": failed to set " + varName +
- ": " + value);
- }
- break setVariables;
- }
- }
- }
- return netId;
- }
-
- /*
- * For an update, if one of the setNetworkVariable operations fails,
- * we might want to roll back all the changes already made. But the
- * chances are that if anything is going to go wrong, it'll happen
- * the first time we try to set one of the variables.
- */
- if (newNetwork) {
- removeNetwork(netId);
- if (DBG) {
- Slog.d(TAG,
- "Failed to set a network variable, removed network: "
- + netId);
- }
- }
- return -1;
+ return mWifiStateTracker.addOrUpdateNetwork(config);
}
- private static String makeString(BitSet set, String[] strings) {
- StringBuffer buf = new StringBuffer();
- int nextSetBit = -1;
-
- /* Make sure all set bits are in [0, strings.length) to avoid
- * going out of bounds on strings. (Shouldn't happen, but...) */
- set = set.get(0, strings.length);
-
- while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
- buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
- }
-
- // remove trailing space
- if (set.cardinality() > 0) {
- buf.setLength(buf.length() - 1);
- }
-
- return buf.toString();
- }
-
- private static int lookupString(String string, String[] strings) {
- int size = strings.length;
-
- string = string.replace('-', '_');
-
- for (int i = 0; i < size; i++)
- if (string.equals(strings[i]))
- return i;
-
- if (DBG) {
- // if we ever get here, we should probably add the
- // value to WifiConfiguration to reflect that it's
- // supported by the WPA supplicant
- Slog.w(TAG, "Failed to look-up a string: " + string);
- }
-
- return -1;
- }
-
- /**
+ /**
* See {@link android.net.wifi.WifiManager#removeNetwork(int)}
* @param netId the integer that identifies the network configuration
* to the supplicant
@@ -1299,7 +475,6 @@ public class WifiService extends IWifiManager.Stub {
*/
public boolean removeNetwork(int netId) {
enforceChangePermission();
-
return mWifiStateTracker.removeNetwork(netId);
}
@@ -1312,14 +487,7 @@ public class WifiService extends IWifiManager.Stub {
*/
public boolean enableNetwork(int netId, boolean disableOthers) {
enforceChangePermission();
-
- String ifname = mWifiStateTracker.getInterfaceName();
- NetworkUtils.enableInterface(ifname);
- boolean result = mWifiStateTracker.enableNetwork(netId, disableOthers);
- if (!result) {
- NetworkUtils.disableInterface(ifname);
- }
- return result;
+ return mWifiStateTracker.enableNetwork(netId, disableOthers);
}
/**
@@ -1330,7 +498,6 @@ public class WifiService extends IWifiManager.Stub {
*/
public boolean disableNetwork(int netId) {
enforceChangePermission();
-
return mWifiStateTracker.disableNetwork(netId);
}
@@ -1354,180 +521,19 @@ public class WifiService extends IWifiManager.Stub {
*/
public List<ScanResult> getScanResults() {
enforceAccessPermission();
- String reply;
-
- reply = mWifiStateTracker.scanResults();
- if (reply == null) {
- return null;
- }
-
- List<ScanResult> scanList = new ArrayList<ScanResult>();
-
- int lineCount = 0;
-
- int replyLen = reply.length();
- // Parse the result string, keeping in mind that the last line does
- // not end with a newline.
- for (int lineBeg = 0, lineEnd = 0; lineEnd <= replyLen; ++lineEnd) {
- if (lineEnd == replyLen || reply.charAt(lineEnd) == '\n') {
- ++lineCount;
- /*
- * Skip the first line, which is a header
- */
- if (lineCount == 1) {
- lineBeg = lineEnd + 1;
- continue;
- }
- if (lineEnd > lineBeg) {
- String line = reply.substring(lineBeg, lineEnd);
- ScanResult scanResult = parseScanResult(line);
- if (scanResult != null) {
- scanList.add(scanResult);
- } else if (DBG) {
- Slog.w(TAG, "misformatted scan result for: " + line);
- }
- }
- lineBeg = lineEnd + 1;
- }
- }
- mWifiStateTracker.setScanResultsList(scanList);
- return scanList;
- }
-
- /**
- * Parse the scan result line passed to us by wpa_supplicant (helper).
- * @param line the line to parse
- * @return the {@link ScanResult} object
- */
- private ScanResult parseScanResult(String line) {
- ScanResult scanResult = null;
- if (line != null) {
- /*
- * Cache implementation (LinkedHashMap) is not synchronized, thus,
- * must synchronized here!
- */
- synchronized (mScanResultCache) {
- String[] result = scanResultPattern.split(line);
- if (3 <= result.length && result.length <= 5) {
- String bssid = result[0];
- // bssid | frequency | level | flags | ssid
- int frequency;
- int level;
- try {
- frequency = Integer.parseInt(result[1]);
- level = Integer.parseInt(result[2]);
- /* some implementations avoid negative values by adding 256
- * so we need to adjust for that here.
- */
- if (level > 0) level -= 256;
- } catch (NumberFormatException e) {
- frequency = 0;
- level = 0;
- }
-
- /*
- * The formatting of the results returned by
- * wpa_supplicant is intended to make the fields
- * line up nicely when printed,
- * not to make them easy to parse. So we have to
- * apply some heuristics to figure out which field
- * is the SSID and which field is the flags.
- */
- String ssid;
- String flags;
- if (result.length == 4) {
- if (result[3].charAt(0) == '[') {
- flags = result[3];
- ssid = "";
- } else {
- flags = "";
- ssid = result[3];
- }
- } else if (result.length == 5) {
- flags = result[3];
- ssid = result[4];
- } else {
- // Here, we must have 3 fields: no flags and ssid
- // set
- flags = "";
- ssid = "";
- }
-
- // bssid + ssid is the hash key
- String key = bssid + ssid;
- scanResult = mScanResultCache.get(key);
- if (scanResult != null) {
- scanResult.level = level;
- scanResult.SSID = ssid;
- scanResult.capabilities = flags;
- scanResult.frequency = frequency;
- } else {
- // Do not add scan results that have no SSID set
- if (0 < ssid.trim().length()) {
- scanResult =
- new ScanResult(
- ssid, bssid, flags, level, frequency);
- mScanResultCache.put(key, scanResult);
- }
- }
- } else {
- Slog.w(TAG, "Misformatted scan result text with " +
- result.length + " fields: " + line);
- }
- }
- }
-
- return scanResult;
- }
-
- /**
- * Parse the "flags" field passed back in a scan result by wpa_supplicant,
- * and construct a {@code WifiConfiguration} that describes the encryption,
- * key management, and authenticaion capabilities of the access point.
- * @param flags the string returned by wpa_supplicant
- * @return the {@link WifiConfiguration} object, filled in
- */
- WifiConfiguration parseScanFlags(String flags) {
- WifiConfiguration config = new WifiConfiguration();
-
- if (flags.length() == 0) {
- config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
- }
- // ... to be implemented
- return config;
+ return mWifiStateTracker.getScanResultsList();
}
/**
* Tell the supplicant to persist the current list of configured networks.
* @return {@code true} if the operation succeeded
+ *
+ * TODO: deprecate this
*/
public boolean saveConfiguration() {
- boolean result;
+ boolean result = true;
enforceChangePermission();
-
- synchronized (mWifiStateTracker) {
- result = mWifiStateTracker.saveConfig();
- if (result && mNeedReconfig) {
- mNeedReconfig = false;
- result = mWifiStateTracker.reloadConfig();
-
- if (result) {
- Intent intent = new Intent(WifiManager.NETWORK_IDS_CHANGED_ACTION);
- mContext.sendBroadcast(intent);
- }
- }
- }
- // Inform the backup manager about a data change
- IBackupManager ibm = IBackupManager.Stub.asInterface(
- ServiceManager.getService(Context.BACKUP_SERVICE));
- if (ibm != null) {
- try {
- ibm.dataChanged("com.android.providers.settings");
- } catch (Exception e) {
- // Try again later
- }
- }
- return result;
+ return mWifiStateTracker.saveConfig();
}
/**
@@ -1542,7 +548,7 @@ public class WifiService extends IWifiManager.Stub {
* @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
* {@code numChannels} is outside the valid range.
*/
- public boolean setNumAllowedChannels(int numChannels, boolean persist) {
+ public synchronized boolean setNumAllowedChannels(int numChannels, boolean persist) {
Slog.i(TAG, "WifiService trying to setNumAllowed to "+numChannels+
" with persist set to "+persist);
enforceChangePermission();
@@ -1564,28 +570,15 @@ public class WifiService extends IWifiManager.Stub {
return false;
}
- if (mWifiHandler == null) return false;
-
- Message.obtain(mWifiHandler,
- MESSAGE_SET_CHANNELS, numChannels, (persist ? 1 : 0)).sendToTarget();
-
- return true;
- }
-
- /**
- * sets the number of allowed radio frequency channels synchronously
- * @param numChannels the number of allowed channels. Must be greater than 0
- * and less than or equal to 16.
- * @param persist {@code true} if the setting should be remembered.
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- */
- private boolean setNumAllowedChannelsBlocking(int numChannels, boolean persist) {
if (persist) {
Settings.Secure.putInt(mContext.getContentResolver(),
Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS,
numChannels);
}
- return mWifiStateTracker.setNumAllowedChannels(numChannels);
+
+ mWifiStateTracker.setNumAllowedChannels(numChannels);
+
+ return true;
}
/**
@@ -1663,8 +656,8 @@ public class WifiService extends IWifiManager.Stub {
WifiInfo info = mWifiStateTracker.requestConnectionInfo();
if (info.getSupplicantState() != SupplicantState.COMPLETED) {
// we used to go to sleep immediately, but this caused some race conditions
- // we don't have time to track down for this release. Delay instead, but not
- // as long as we would if connected (below)
+ // we don't have time to track down for this release. Delay instead,
+ // but not as long as we would if connected (below)
// TODO - fix the race conditions and switch back to the immediate turn-off
long triggerTime = System.currentTimeMillis() + (2*60*1000); // 2 min
Slog.d(TAG, "setting ACTION_DEVICE_IDLE timer for 120,000 ms");
@@ -1763,31 +756,9 @@ public class WifiService extends IWifiManager.Stub {
}
};
- private void sendEnableMessage(boolean enable, boolean persist, int uid) {
- Message msg = Message.obtain(mWifiHandler,
- (enable ? MESSAGE_ENABLE_WIFI : MESSAGE_DISABLE_WIFI),
- (persist ? 1 : 0), uid);
- msg.sendToTarget();
- }
-
- private void sendStartMessage(boolean scanOnlyMode) {
- Message.obtain(mWifiHandler, MESSAGE_START_WIFI, scanOnlyMode ? 1 : 0, 0).sendToTarget();
- }
-
- private void sendAccessPointMessage(boolean enable, WifiConfiguration wifiConfig, int uid) {
- Message.obtain(mWifiHandler,
- (enable ? MESSAGE_START_ACCESS_POINT : MESSAGE_STOP_ACCESS_POINT),
- uid, 0, wifiConfig).sendToTarget();
- }
-
private void updateWifiState() {
- // send a message so it's all serialized
- Message.obtain(mWifiHandler, MESSAGE_UPDATE_STATE, 0, 0).sendToTarget();
- }
-
- private void doUpdateWifiState() {
boolean wifiEnabled = getPersistedWifiEnabled();
- boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden;
+ boolean airplaneMode = isAirplaneModeOn() && !mAirplaneModeOverwridden.get();
boolean lockHeld = mLocks.hasLocks();
int strongestLockMode;
boolean wifiShouldBeEnabled = wifiEnabled && !airplaneMode;
@@ -1798,36 +769,23 @@ public class WifiService extends IWifiManager.Stub {
strongestLockMode = WifiManager.WIFI_MODE_FULL;
}
- synchronized (mWifiHandler) {
- if ((mWifiStateTracker.getWifiState() == WIFI_STATE_ENABLING) && !airplaneMode) {
- return;
- }
-
- /* Disable tethering when airplane mode is enabled */
- if (airplaneMode &&
- (mWifiApState == WIFI_AP_STATE_ENABLING || mWifiApState == WIFI_AP_STATE_ENABLED)) {
- sWakeLock.acquire();
- sendAccessPointMessage(false, null, mLastApEnableUid);
- }
+ /* Disable tethering when airplane mode is enabled */
+ if (airplaneMode) {
+ mWifiStateTracker.setWifiApEnabled(null, false);
+ }
- if (wifiShouldBeEnabled) {
- if (wifiShouldBeStarted) {
- sWakeLock.acquire();
- sendEnableMessage(true, false, mLastEnableUid);
- sWakeLock.acquire();
- sendStartMessage(strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
- } else if (!mWifiStateTracker.isDriverStopped()) {
- if (mCm == null) {
- mCm = (ConnectivityManager)mContext.
- getSystemService(Context.CONNECTIVITY_SERVICE);
- }
- mCm.requestNetworkTransitionWakelock(TAG);
- mWifiHandler.sendEmptyMessage(MESSAGE_STOP_WIFI);
- }
+ if (wifiShouldBeEnabled) {
+ if (wifiShouldBeStarted) {
+ mWifiStateTracker.setWifiEnabled(true);
+ mWifiStateTracker.setScanOnlyMode(
+ strongestLockMode == WifiManager.WIFI_MODE_SCAN_ONLY);
+ mWifiStateTracker.startWifi(true);
} else {
- sWakeLock.acquire();
- sendEnableMessage(false, false, mLastEnableUid);
+ mWifiStateTracker.requestCmWakeLock();
+ mWifiStateTracker.disconnectAndStop();
}
+ } else {
+ mWifiStateTracker.setWifiEnabled(false);
}
}
@@ -1865,71 +823,6 @@ public class WifiService extends IWifiManager.Stub {
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
}
- /**
- * Handler that allows posting to the WifiThread.
- */
- private class WifiHandler extends Handler {
- public WifiHandler(Looper looper) {
- super(looper);
- }
-
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
-
- case MESSAGE_ENABLE_WIFI:
- setWifiEnabledBlocking(true, msg.arg1 == 1, msg.arg2);
- if (mWifiWatchdogService == null) {
- mWifiWatchdogService = new WifiWatchdogService(mContext, mWifiStateTracker);
- }
- sWakeLock.release();
- break;
-
- case MESSAGE_START_WIFI:
- mWifiStateTracker.setScanOnlyMode(msg.arg1 != 0);
- mWifiStateTracker.restart();
- sWakeLock.release();
- break;
-
- case MESSAGE_UPDATE_STATE:
- doUpdateWifiState();
- break;
-
- case MESSAGE_DISABLE_WIFI:
- // a non-zero msg.arg1 value means the "enabled" setting
- // should be persisted
- setWifiEnabledBlocking(false, msg.arg1 == 1, msg.arg2);
- mWifiWatchdogService = null;
- sWakeLock.release();
- break;
-
- case MESSAGE_STOP_WIFI:
- mWifiStateTracker.disconnectAndStop();
- // don't release wakelock
- break;
-
- case MESSAGE_START_ACCESS_POINT:
- setWifiApEnabledBlocking(true,
- msg.arg1,
- (WifiConfiguration) msg.obj);
- sWakeLock.release();
- break;
-
- case MESSAGE_STOP_ACCESS_POINT:
- setWifiApEnabledBlocking(false,
- msg.arg1,
- (WifiConfiguration) msg.obj);
- sWakeLock.release();
- break;
-
- case MESSAGE_SET_CHANNELS:
- setNumAllowedChannelsBlocking(msg.arg1, msg.arg2 == 1);
- break;
-
- }
- }
- }
-
@Override
protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
@@ -1939,7 +832,7 @@ public class WifiService extends IWifiManager.Stub {
+ ", uid=" + Binder.getCallingUid());
return;
}
- pw.println("Wi-Fi is " + stateName(mWifiStateTracker.getWifiState()));
+ pw.println("Wi-Fi is " + mWifiStateTracker.getWifiStateByName());
pw.println("Stay-awake conditions: " +
Settings.System.getInt(mContext.getContentResolver(),
Settings.System.STAY_ON_WHILE_PLUGGED_IN, 0));
@@ -1971,23 +864,6 @@ public class WifiService extends IWifiManager.Stub {
mLocks.dump(pw);
}
- private static String stateName(int wifiState) {
- switch (wifiState) {
- case WIFI_STATE_DISABLING:
- return "disabling";
- case WIFI_STATE_DISABLED:
- return "disabled";
- case WIFI_STATE_ENABLING:
- return "enabling";
- case WIFI_STATE_ENABLED:
- return "enabled";
- case WIFI_STATE_UNKNOWN:
- return "unknown state";
- default:
- return "[invalid state]";
- }
- }
-
private class WifiLock extends DeathRecipient {
WifiLock(int lockMode, String tag, IBinder binder) {
super(lockMode, tag, binder);
diff --git a/services/java/com/android/server/WifiWatchdogService.java b/services/java/com/android/server/WifiWatchdogService.java
index 445dd03..be14cd3 100644
--- a/services/java/com/android/server/WifiWatchdogService.java
+++ b/services/java/com/android/server/WifiWatchdogService.java
@@ -275,12 +275,13 @@ public class WifiWatchdogService {
/**
* Unregister broadcasts and quit the watchdog thread
*/
- private void quit() {
- unregisterForWifiBroadcasts();
- mContext.getContentResolver().unregisterContentObserver(mContentObserver);
- mHandler.removeAllActions();
- mHandler.getLooper().quit();
- }
+ //TODO: Change back to running WWS when needed
+// private void quit() {
+// unregisterForWifiBroadcasts();
+// mContext.getContentResolver().unregisterContentObserver(mContentObserver);
+// mHandler.removeAllActions();
+// mHandler.getLooper().quit();
+// }
/**
* Waits for the main watchdog thread to create the handler.
@@ -751,7 +752,7 @@ public class WifiWatchdogService {
// Black list this "bad" AP, this will cause an attempt to connect to another
blacklistAp(ap.bssid);
// Initiate an association to an alternate AP
- mWifiStateTracker.reassociate();
+ mWifiStateTracker.reassociateCommand();
}
private void blacklistAp(String bssid) {
@@ -762,10 +763,7 @@ public class WifiWatchdogService {
// Before taking action, make sure we should not cancel our processing
if (shouldCancel()) return;
- if (!mWifiStateTracker.addToBlacklist(bssid)) {
- // There's a known bug where this method returns failure on success
- //Slog.e(TAG, "Blacklisting " + bssid + " failed");
- }
+ mWifiStateTracker.addToBlacklist(bssid);
if (D) {
myLogD("Blacklisting " + bssid);
@@ -860,10 +858,7 @@ public class WifiWatchdogService {
* (and blacklisted them). Clear the blacklist so the AP with best
* signal is chosen.
*/
- if (!mWifiStateTracker.clearBlacklist()) {
- // There's a known bug where this method returns failure on success
- //Slog.e(TAG, "Clearing blacklist failed");
- }
+ mWifiStateTracker.clearBlacklist();
if (V) {
myLogV("handleSleep: Set state to SLEEP and cleared blacklist");
@@ -1151,7 +1146,7 @@ public class WifiWatchdogService {
private void handleWifiStateChanged(int wifiState) {
if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
- quit();
+ onDisconnected();
} else if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
onEnabled();
}
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index fa2ec1f..440ebbd 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -6173,7 +6173,7 @@ public final class ActivityManagerService extends ActivityManagerNative implemen
if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
boolean bufferWasEmpty;
-
+ boolean needsFlush;
final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
synchronized (sb) {
bufferWasEmpty = sb.length() == 0;
@@ -6188,18 +6188,32 @@ public final class ActivityManagerService extends ActivityManagerNative implemen
sb.append(crashInfo.stackTrace);
}
sb.append("\n");
+
+ // Only buffer up to ~64k. Various logging bits truncate
+ // things at 128k.
+ needsFlush = (sb.length() > 64 * 1024);
}
- // Non-system apps are isolated with a different tag & policy.
- // They're also not batched. Batching is useful during system
- // boot with strict system-wide logging policies and lots of
- // things firing, but not common with regular apps, which
- // won't ship with StrictMode dropboxing enabled.
- if (!isSystemApp) {
+ // Flush immediately if the buffer's grown too large, or this
+ // is a non-system app. Non-system apps are isolated with a
+ // different tag & policy and not batched.
+ //
+ // Batching is useful during internal testing with
+ // StrictMode settings turned up high. Without batching,
+ // thousands of separate files could be created on boot.
+ if (!isSystemApp || needsFlush) {
new Thread("Error dump: " + dropboxTag) {
@Override
public void run() {
- dbox.addText(dropboxTag, sb.toString());
+ String report;
+ synchronized (sb) {
+ report = sb.toString();
+ sb.delete(0, sb.length());
+ sb.trimToSize();
+ }
+ if (report.length() != 0) {
+ dbox.addText(dropboxTag, report);
+ }
}
}.start();
return;
@@ -6207,8 +6221,9 @@ public final class ActivityManagerService extends ActivityManagerNative implemen
// System app batching:
if (!bufferWasEmpty) {
- // An existing dropbox-writing thread is outstanding and
- // will handle it.
+ // An existing dropbox-writing thread is outstanding, so
+ // we don't need to start it up. The existing thread will
+ // catch the buffer appends we just did.
return;
}
diff --git a/services/java/com/android/server/connectivity/Tethering.java b/services/java/com/android/server/connectivity/Tethering.java
index d27ccc0..acedd26 100644
--- a/services/java/com/android/server/connectivity/Tethering.java
+++ b/services/java/com/android/server/connectivity/Tethering.java
@@ -26,13 +26,13 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
+import android.hardware.Usb;
import android.net.ConnectivityManager;
import android.net.InterfaceConfiguration;
import android.net.IConnectivityManager;
import android.net.INetworkManagementEventObserver;
import android.net.NetworkInfo;
import android.net.NetworkUtils;
-import android.os.BatteryManager;
import android.os.Binder;
import android.os.Environment;
import android.os.HandlerThread;
@@ -136,7 +136,7 @@ public class Tethering extends INetworkManagementEventObserver.Stub {
mStateReceiver = new StateReceiver();
IntentFilter filter = new IntentFilter();
- filter.addAction(Intent.ACTION_BATTERY_CHANGED);
+ filter.addAction(Usb.ACTION_USB_STATE);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
mContext.registerReceiver(mStateReceiver, filter);
@@ -429,10 +429,9 @@ public class Tethering extends INetworkManagementEventObserver.Stub {
private class StateReceiver extends BroadcastReceiver {
public void onReceive(Context content, Intent intent) {
String action = intent.getAction();
- if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
- mUsbConnected = (intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
- == BatteryManager.BATTERY_PLUGGED_USB);
- Tethering.this.updateUsbStatus();
+ if (action.equals(Usb.ACTION_USB_STATE)) {
+ mUsbConnected = intent.getExtras().getBoolean(Usb.USB_CONNECTED);
+ updateUsbStatus();
} else if (action.equals(Intent.ACTION_MEDIA_SHARED)) {
mUsbMassStorageOff = false;
updateUsbStatus();
diff --git a/services/java/com/android/server/location/ComprehensiveCountryDetector.java b/services/java/com/android/server/location/ComprehensiveCountryDetector.java
new file mode 100755
index 0000000..e692f8d
--- /dev/null
+++ b/services/java/com/android/server/location/ComprehensiveCountryDetector.java
@@ -0,0 +1,359 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package com.android.server.location;
+
+import java.util.Locale;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import android.content.Context;
+import android.location.Country;
+import android.location.CountryListener;
+import android.location.Geocoder;
+import android.provider.Settings;
+import android.telephony.PhoneStateListener;
+import android.telephony.ServiceState;
+import android.telephony.TelephonyManager;
+import android.text.TextUtils;
+import android.util.Slog;
+
+/**
+ * This class is used to detect the country where the user is. The sources of
+ * country are queried in order of reliability, like
+ * <ul>
+ * <li>Mobile network</li>
+ * <li>Location</li>
+ * <li>SIM's country</li>
+ * <li>Phone's locale</li>
+ * </ul>
+ * <p>
+ * Call the {@link #detectCountry()} to get the available country immediately.
+ * <p>
+ * To be notified of the future country change, using the
+ * {@link #setCountryListener(CountryListener)}
+ * <p>
+ * Using the {@link #stop()} to stop listening to the country change.
+ * <p>
+ * The country information will be refreshed every
+ * {@link #LOCATION_REFRESH_INTERVAL} once the location based country is used.
+ *
+ * @hide
+ */
+public class ComprehensiveCountryDetector extends CountryDetectorBase {
+
+ private final static String TAG = "ComprehensiveCountryDetector";
+
+ /**
+ * The refresh interval when the location based country was used
+ */
+ private final static long LOCATION_REFRESH_INTERVAL = 1000 * 60 * 60 * 24; // 1 day
+
+ protected CountryDetectorBase mLocationBasedCountryDetector;
+ protected Timer mLocationRefreshTimer;
+
+ private final int mPhoneType;
+ private Country mCountry;
+ private TelephonyManager mTelephonyManager;
+ private Country mCountryFromLocation;
+ private boolean mStopped = false;
+ private ServiceState mLastState;
+
+ private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
+ @Override
+ public void onServiceStateChanged(ServiceState serviceState) {
+ // TODO: Find out how often we will be notified, if this method is called too
+ // many times, let's consider querying the network.
+ Slog.d(TAG, "onServiceStateChanged");
+ // We only care the state change
+ if (mLastState == null || mLastState.getState() != serviceState.getState()) {
+ detectCountry(true, true);
+ mLastState = new ServiceState(serviceState);
+ }
+ }
+ };
+
+ /**
+ * The listener for receiving the notification from LocationBasedCountryDetector.
+ */
+ private CountryListener mLocationBasedCountryDetectionListener = new CountryListener() {
+ public void onCountryDetected(Country country) {
+ mCountryFromLocation = country;
+ // Don't start the LocationBasedCountryDetector.
+ detectCountry(true, false);
+ stopLocationBasedDetector();
+ }
+ };
+
+ public ComprehensiveCountryDetector(Context context) {
+ super(context);
+ mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+ mPhoneType = mTelephonyManager.getPhoneType();
+ }
+
+ @Override
+ public Country detectCountry() {
+ // Don't start the LocationBasedCountryDetector if we have been stopped.
+ return detectCountry(false, !mStopped);
+ }
+
+ @Override
+ public void stop() {
+ Slog.i(TAG, "Stop the detector.");
+ cancelLocationRefresh();
+ removePhoneStateListener();
+ stopLocationBasedDetector();
+ mListener = null;
+ mStopped = true;
+ }
+
+ /**
+ * Get the country from different sources in order of the reliability.
+ */
+ private Country getCountry() {
+ Country result = null;
+ result = getNetworkBasedCountry();
+ if (result == null) {
+ result = getLastKnownLocationBasedCountry();
+ }
+ if (result == null) {
+ result = getSimBasedCountry();
+ }
+ if (result == null) {
+ result = getLocaleCountry();
+ }
+ return result;
+ }
+
+ /**
+ * @return the country from the mobile network.
+ */
+ protected Country getNetworkBasedCountry() {
+ String countryIso = null;
+ // TODO: The document says the result may be unreliable on CDMA networks. Shall we use
+ // it on CDMA phone? We may test the Android primarily used countries.
+ if (mPhoneType == TelephonyManager.PHONE_TYPE_GSM) {
+ countryIso = mTelephonyManager.getNetworkCountryIso();
+ if (!TextUtils.isEmpty(countryIso)) {
+ return new Country(countryIso, Country.COUNTRY_SOURCE_NETWORK);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @return the cached location based country.
+ */
+ protected Country getLastKnownLocationBasedCountry() {
+ return mCountryFromLocation;
+ }
+
+ /**
+ * @return the country from SIM card
+ */
+ protected Country getSimBasedCountry() {
+ String countryIso = null;
+ countryIso = mTelephonyManager.getSimCountryIso();
+ if (!TextUtils.isEmpty(countryIso)) {
+ return new Country(countryIso, Country.COUNTRY_SOURCE_SIM);
+ }
+ return null;
+ }
+
+ /**
+ * @return the country from the system's locale.
+ */
+ protected Country getLocaleCountry() {
+ Locale defaultLocale = Locale.getDefault();
+ if (defaultLocale != null) {
+ return new Country(defaultLocale.getCountry(), Country.COUNTRY_SOURCE_LOCALE);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * @param notifyChange indicates whether the listener should be notified the change of the
+ * country
+ * @param startLocationBasedDetection indicates whether the LocationBasedCountryDetector could
+ * be started if the current country source is less reliable than the location.
+ * @return the current available UserCountry
+ */
+ private Country detectCountry(boolean notifyChange, boolean startLocationBasedDetection) {
+ Country country = getCountry();
+ runAfterDetectionAsync(mCountry != null ? new Country(mCountry) : mCountry, country,
+ notifyChange, startLocationBasedDetection);
+ mCountry = country;
+ return mCountry;
+ }
+
+ /**
+ * Run the tasks in the service's thread.
+ */
+ protected void runAfterDetectionAsync(final Country country, final Country detectedCountry,
+ final boolean notifyChange, final boolean startLocationBasedDetection) {
+ mHandler.post(new Runnable() {
+ public void run() {
+ runAfterDetection(
+ country, detectedCountry, notifyChange, startLocationBasedDetection);
+ }
+ });
+ }
+
+ @Override
+ public void setCountryListener(CountryListener listener) {
+ CountryListener prevListener = mListener;
+ mListener = listener;
+ if (mListener == null) {
+ // Stop listening all services
+ removePhoneStateListener();
+ stopLocationBasedDetector();
+ cancelLocationRefresh();
+ } else if (prevListener == null) {
+ addPhoneStateListener();
+ detectCountry(false, true);
+ }
+ }
+
+ void runAfterDetection(final Country country, final Country detectedCountry,
+ final boolean notifyChange, final boolean startLocationBasedDetection) {
+ if (notifyChange) {
+ notifyIfCountryChanged(country, detectedCountry);
+ }
+ if (startLocationBasedDetection && (detectedCountry == null
+ || detectedCountry.getSource() > Country.COUNTRY_SOURCE_LOCATION)
+ && isAirplaneModeOff() && mListener != null && isGeoCoderImplemented()) {
+ // Start finding location when the source is less reliable than the
+ // location and the airplane mode is off (as geocoder will not
+ // work).
+ // TODO : Shall we give up starting the detector within a
+ // period of time?
+ startLocationBasedDetector(mLocationBasedCountryDetectionListener);
+ }
+ if (detectedCountry == null
+ || detectedCountry.getSource() >= Country.COUNTRY_SOURCE_LOCATION) {
+ // Schedule the location refresh if the country source is
+ // not more reliable than the location or no country is
+ // found.
+ // TODO: Listen to the preference change of GPS, Wifi etc,
+ // and start detecting the country.
+ scheduleLocationRefresh();
+ } else {
+ // Cancel the location refresh once the current source is
+ // more reliable than the location.
+ cancelLocationRefresh();
+ stopLocationBasedDetector();
+ }
+ }
+
+ /**
+ * Find the country from LocationProvider.
+ */
+ private synchronized void startLocationBasedDetector(CountryListener listener) {
+ if (mLocationBasedCountryDetector != null) {
+ return;
+ }
+ mLocationBasedCountryDetector = createLocationBasedCountryDetector();
+ mLocationBasedCountryDetector.setCountryListener(listener);
+ mLocationBasedCountryDetector.detectCountry();
+ }
+
+ private synchronized void stopLocationBasedDetector() {
+ if (mLocationBasedCountryDetector != null) {
+ mLocationBasedCountryDetector.stop();
+ mLocationBasedCountryDetector = null;
+ }
+ }
+
+ protected CountryDetectorBase createLocationBasedCountryDetector() {
+ return new LocationBasedCountryDetector(mContext);
+ }
+
+ protected boolean isAirplaneModeOff() {
+ return Settings.System.getInt(
+ mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 0;
+ }
+
+ /**
+ * Notify the country change.
+ */
+ private void notifyIfCountryChanged(final Country country, final Country detectedCountry) {
+ if (detectedCountry != null && mListener != null
+ && (country == null || !country.equals(detectedCountry))) {
+ Slog.d(TAG,
+ "The country was changed from " + country != null ? country.getCountryIso() :
+ country + " to " + detectedCountry.getCountryIso());
+ notifyListener(detectedCountry);
+ }
+ }
+
+ /**
+ * Schedule the next location refresh. We will do nothing if the scheduled task exists.
+ */
+ private synchronized void scheduleLocationRefresh() {
+ if (mLocationRefreshTimer != null) return;
+ mLocationRefreshTimer = new Timer();
+ mLocationRefreshTimer.schedule(new TimerTask() {
+ @Override
+ public void run() {
+ mLocationRefreshTimer = null;
+ detectCountry(false, true);
+ }
+ }, LOCATION_REFRESH_INTERVAL);
+ }
+
+ /**
+ * Cancel the scheduled refresh task if it exists
+ */
+ private synchronized void cancelLocationRefresh() {
+ if (mLocationRefreshTimer != null) {
+ mLocationRefreshTimer.cancel();
+ mLocationRefreshTimer = null;
+ }
+ }
+
+ protected synchronized void addPhoneStateListener() {
+ if (mPhoneStateListener == null && mPhoneType == TelephonyManager.PHONE_TYPE_GSM) {
+ mLastState = null;
+ mPhoneStateListener = new PhoneStateListener() {
+ @Override
+ public void onServiceStateChanged(ServiceState serviceState) {
+ // TODO: Find out how often we will be notified, if this
+ // method is called too
+ // many times, let's consider querying the network.
+ Slog.d(TAG, "onServiceStateChanged");
+ // We only care the state change
+ if (mLastState == null || mLastState.getState() != serviceState.getState()) {
+ detectCountry(true, true);
+ mLastState = new ServiceState(serviceState);
+ }
+ }
+ };
+ mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE);
+ }
+ }
+
+ protected synchronized void removePhoneStateListener() {
+ if (mPhoneStateListener != null) {
+ mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
+ mPhoneStateListener = null;
+ }
+ }
+
+ protected boolean isGeoCoderImplemented() {
+ return Geocoder.isImplemented();
+ }
+}
diff --git a/services/java/com/android/server/location/CountryDetectorBase.java b/services/java/com/android/server/location/CountryDetectorBase.java
new file mode 100644
index 0000000..8326ef9
--- /dev/null
+++ b/services/java/com/android/server/location/CountryDetectorBase.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package com.android.server.location;
+
+import android.content.Context;
+import android.location.Country;
+import android.location.CountryListener;
+import android.os.Handler;
+
+/**
+ * This class defines the methods need to be implemented by the country
+ * detector.
+ * <p>
+ * Calling {@link #detectCountry} to start detecting the country. The country
+ * could be returned immediately if it is available.
+ *
+ * @hide
+ */
+public abstract class CountryDetectorBase {
+ protected final Handler mHandler;
+ protected final Context mContext;
+ protected CountryListener mListener;
+ protected Country mDetectedCountry;
+
+ public CountryDetectorBase(Context ctx) {
+ mContext = ctx;
+ mHandler = new Handler();
+ }
+
+ /**
+ * Start detecting the country that the user is in.
+ *
+ * @return the country if it is available immediately, otherwise null should
+ * be returned.
+ */
+ public abstract Country detectCountry();
+
+ /**
+ * Register a listener to receive the notification when the country is detected or changed.
+ * <p>
+ * The previous listener will be replaced if it exists.
+ */
+ public void setCountryListener(CountryListener listener) {
+ mListener = listener;
+ }
+
+ /**
+ * Stop detecting the country. The detector should release all system services and be ready to
+ * be freed
+ */
+ public abstract void stop();
+
+ protected void notifyListener(Country country) {
+ if (mListener != null) {
+ mListener.onCountryDetected(country);
+ }
+ }
+}
diff --git a/services/java/com/android/server/location/LocationBasedCountryDetector.java b/services/java/com/android/server/location/LocationBasedCountryDetector.java
new file mode 100755
index 0000000..139f05d
--- /dev/null
+++ b/services/java/com/android/server/location/LocationBasedCountryDetector.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package com.android.server.location;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import android.content.Context;
+import android.location.Address;
+import android.location.Country;
+import android.location.Geocoder;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.os.Bundle;
+import android.util.Slog;
+
+/**
+ * This class detects which country the user currently is in through the enabled
+ * location providers and the GeoCoder
+ * <p>
+ * Use {@link #detectCountry} to start querying. If the location can not be
+ * resolved within the given time, the last known location will be used to get
+ * the user country through the GeoCoder. The IllegalStateException will be
+ * thrown if there is a ongoing query.
+ * <p>
+ * The current query can be stopped by {@link #stop()}
+ *
+ * @hide
+ */
+public class LocationBasedCountryDetector extends CountryDetectorBase {
+ private final static String TAG = "LocationBasedCountryDetector";
+ private final static long QUERY_LOCATION_TIMEOUT = 1000 * 60 * 5; // 5 mins
+
+ /**
+ * Used for canceling location query
+ */
+ protected Timer mTimer;
+
+ /**
+ * The thread to query the country from the GeoCoder.
+ */
+ protected Thread mQueryThread;
+ protected List<LocationListener> mLocationListeners;
+
+ private LocationManager mLocationManager;
+ private List<String> mEnabledProviders;
+
+ public LocationBasedCountryDetector(Context ctx) {
+ super(ctx);
+ mLocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
+ }
+
+ /**
+ * @return the ISO 3166-1 two letters country code from the location
+ */
+ protected String getCountryFromLocation(Location location) {
+ String country = null;
+ Geocoder geoCoder = new Geocoder(mContext);
+ try {
+ List<Address> addresses = geoCoder.getFromLocation(
+ location.getLatitude(), location.getLongitude(), 1);
+ if (addresses != null && addresses.size() > 0) {
+ country = addresses.get(0).getCountryCode();
+ }
+ } catch (IOException e) {
+ Slog.w(TAG, "Exception occurs when getting country from location");
+ }
+ return country;
+ }
+
+ /**
+ * Register the listeners with the location providers
+ */
+ protected void registerEnabledProviders(List<LocationListener> listeners) {
+ int total = listeners.size();
+ for (int i = 0; i< total; i++) {
+ mLocationManager.requestLocationUpdates(
+ mEnabledProviders.get(i), 0, 0, listeners.get(i));
+ }
+ }
+
+ /**
+ * Unregister the listeners with the location providers
+ */
+ protected void unregisterProviders(List<LocationListener> listeners) {
+ for (LocationListener listener : listeners) {
+ mLocationManager.removeUpdates(listener);
+ }
+ }
+
+ /**
+ * @return the last known location from all providers
+ */
+ protected Location getLastKnownLocation() {
+ List<String> providers = mLocationManager.getAllProviders();
+ Location bestLocation = null;
+ for (String provider : providers) {
+ Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider);
+ if (lastKnownLocation != null) {
+ if (bestLocation == null || bestLocation.getTime() < lastKnownLocation.getTime()) {
+ bestLocation = lastKnownLocation;
+ }
+ }
+ }
+ return bestLocation;
+ }
+
+ /**
+ * @return the timeout for querying the location.
+ */
+ protected long getQueryLocationTimeout() {
+ return QUERY_LOCATION_TIMEOUT;
+ }
+
+ /**
+ * @return the total number of enabled location providers
+ */
+ protected int getTotalEnabledProviders() {
+ if (mEnabledProviders == null) {
+ mEnabledProviders = mLocationManager.getProviders(true);
+ }
+ return mEnabledProviders.size();
+ }
+
+ /**
+ * Start detecting the country.
+ * <p>
+ * Queries the location from all location providers, then starts a thread to query the
+ * country from GeoCoder.
+ */
+ @Override
+ public synchronized Country detectCountry() {
+ if (mLocationListeners != null) {
+ throw new IllegalStateException();
+ }
+ // Request the location from all enabled providers.
+ int totalProviders = getTotalEnabledProviders();
+ if (totalProviders > 0) {
+ mLocationListeners = new ArrayList<LocationListener>(totalProviders);
+ for (int i = 0; i < totalProviders; i++) {
+ LocationListener listener = new LocationListener () {
+ public void onLocationChanged(Location location) {
+ if (location != null) {
+ LocationBasedCountryDetector.this.stop();
+ queryCountryCode(location);
+ }
+ }
+ public void onProviderDisabled(String provider) {
+ }
+ public void onProviderEnabled(String provider) {
+ }
+ public void onStatusChanged(String provider, int status, Bundle extras) {
+ }
+ };
+ mLocationListeners.add(listener);
+ }
+ registerEnabledProviders(mLocationListeners);
+ mTimer = new Timer();
+ mTimer.schedule(new TimerTask() {
+ @Override
+ public void run() {
+ mTimer = null;
+ LocationBasedCountryDetector.this.stop();
+ // Looks like no provider could provide the location, let's try the last
+ // known location.
+ queryCountryCode(getLastKnownLocation());
+ }
+ }, getQueryLocationTimeout());
+ } else {
+ // There is no provider enabled.
+ queryCountryCode(getLastKnownLocation());
+ }
+ return mDetectedCountry;
+ }
+
+ /**
+ * Stop the current query without notifying the listener.
+ */
+ @Override
+ public synchronized void stop() {
+ if (mLocationListeners != null) {
+ unregisterProviders(mLocationListeners);
+ mLocationListeners = null;
+ }
+ if (mTimer != null) {
+ mTimer.cancel();
+ mTimer = null;
+ }
+ }
+
+ /**
+ * Start a new thread to query the country from Geocoder.
+ */
+ private synchronized void queryCountryCode(final Location location) {
+ if (location == null) {
+ notifyListener(null);
+ return;
+ }
+ if (mQueryThread != null) return;
+ mQueryThread = new Thread(new Runnable() {
+ public void run() {
+ String countryIso = null;
+ if (location != null) {
+ countryIso = getCountryFromLocation(location);
+ }
+ if (countryIso != null) {
+ mDetectedCountry = new Country(countryIso, Country.COUNTRY_SOURCE_LOCATION);
+ } else {
+ mDetectedCountry = null;
+ }
+ notifyListener(mDetectedCountry);
+ mQueryThread = null;
+ }
+ });
+ mQueryThread.start();
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java b/services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java
new file mode 100644
index 0000000..17a1585
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/CountryDetectorServiceTest.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package com.android.server;
+
+import android.content.Context;
+import android.location.Country;
+import android.location.CountryListener;
+import android.location.ICountryListener;
+import android.os.RemoteException;
+import android.test.AndroidTestCase;
+
+public class CountryDetectorServiceTest extends AndroidTestCase {
+ private class CountryListenerTester extends ICountryListener.Stub {
+ private Country mCountry;
+
+ @Override
+ public void onCountryDetected(Country country) throws RemoteException {
+ mCountry = country;
+ }
+
+ public Country getCountry() {
+ return mCountry;
+ }
+
+ public boolean isNotified() {
+ return mCountry != null;
+ }
+ }
+
+ private class CountryDetectorServiceTester extends CountryDetectorService {
+
+ private CountryListener mListener;
+
+ public CountryDetectorServiceTester(Context context) {
+ super(context);
+ }
+
+ @Override
+ public void notifyReceivers(Country country) {
+ super.notifyReceivers(country);
+ }
+
+ @Override
+ protected void setCountryListener(final CountryListener listener) {
+ mListener = listener;
+ }
+
+ public boolean isListenerSet() {
+ return mListener != null;
+ }
+ }
+
+ public void testAddRemoveListener() throws RemoteException {
+ CountryDetectorServiceTester serviceTester = new CountryDetectorServiceTester(getContext());
+ serviceTester.systemReady();
+ waitForSystemReady(serviceTester);
+ CountryListenerTester listenerTester = new CountryListenerTester();
+ serviceTester.addCountryListener(listenerTester);
+ assertTrue(serviceTester.isListenerSet());
+ serviceTester.removeCountryListener(listenerTester);
+ assertFalse(serviceTester.isListenerSet());
+ }
+
+ public void testNotifyListeners() throws RemoteException {
+ CountryDetectorServiceTester serviceTester = new CountryDetectorServiceTester(getContext());
+ CountryListenerTester listenerTesterA = new CountryListenerTester();
+ CountryListenerTester listenerTesterB = new CountryListenerTester();
+ Country country = new Country("US", Country.COUNTRY_SOURCE_NETWORK);
+ serviceTester.systemReady();
+ waitForSystemReady(serviceTester);
+ serviceTester.addCountryListener(listenerTesterA);
+ serviceTester.addCountryListener(listenerTesterB);
+ serviceTester.notifyReceivers(country);
+ assertTrue(serviceTester.isListenerSet());
+ assertTrue(listenerTesterA.isNotified());
+ assertTrue(listenerTesterB.isNotified());
+ serviceTester.removeCountryListener(listenerTesterA);
+ serviceTester.removeCountryListener(listenerTesterB);
+ assertFalse(serviceTester.isListenerSet());
+ }
+
+ private void waitForSystemReady(CountryDetectorService service) {
+ int count = 5;
+ while (count-- > 0) {
+ try {
+ Thread.sleep(500);
+ } catch (Exception e) {
+ }
+ if (service.isSystemReady()) {
+ return;
+ }
+ }
+ throw new RuntimeException("Wait System Ready timeout");
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/location/ComprehensiveCountryDetectorTest.java b/services/tests/servicestests/src/com/android/server/location/ComprehensiveCountryDetectorTest.java
new file mode 100644
index 0000000..98966c0
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/location/ComprehensiveCountryDetectorTest.java
@@ -0,0 +1,299 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package com.android.server.location;
+
+import android.location.Country;
+import android.location.CountryListener;
+import android.test.AndroidTestCase;
+
+public class ComprehensiveCountryDetectorTest extends AndroidTestCase {
+ private class TestCountryDetector extends ComprehensiveCountryDetector {
+ public final static String COUNTRY_ISO = "us";
+ private boolean mLocationBasedDetectorStarted;
+ private boolean mLocationBasedDetectorStopped;
+ protected boolean mNotified;
+ private boolean listenerAdded = false;
+
+ private Country mNotifiedCountry;
+ public TestCountryDetector() {
+ super(getContext());
+ }
+
+ public void notifyLocationBasedListener(Country country) {
+ mNotified = true;
+ mNotifiedCountry = country;
+ mLocationBasedCountryDetector.notifyListener(country);
+ }
+
+ public boolean locationBasedDetectorStarted() {
+ return mLocationBasedCountryDetector != null && mLocationBasedDetectorStarted;
+ }
+
+ public boolean locationBasedDetectorStopped() {
+ return mLocationBasedCountryDetector == null && mLocationBasedDetectorStopped;
+ }
+
+ public boolean locationRefreshStarted() {
+ return mLocationRefreshTimer != null;
+ }
+
+ public boolean locationRefreshCancelled() {
+ return mLocationRefreshTimer == null;
+ }
+
+ @Override
+ protected CountryDetectorBase createLocationBasedCountryDetector() {
+ return new CountryDetectorBase(mContext) {
+ @Override
+ public Country detectCountry() {
+ mLocationBasedDetectorStarted = true;
+ return null;
+ }
+
+ @Override
+ public void stop() {
+ mLocationBasedDetectorStopped = true;
+ }
+ };
+ }
+
+ @Override
+ protected Country getNetworkBasedCountry() {
+ return null;
+ }
+
+ @Override
+ protected Country getLastKnownLocationBasedCountry() {
+ return mNotifiedCountry;
+ }
+
+ @Override
+ protected Country getSimBasedCountry() {
+ return null;
+ }
+
+ @Override
+ protected Country getLocaleCountry() {
+ return null;
+ }
+
+ @Override
+ protected void runAfterDetectionAsync(final Country country, final Country detectedCountry,
+ final boolean notifyChange, final boolean startLocationBasedDetection) {
+ runAfterDetection(country, detectedCountry, notifyChange, startLocationBasedDetection);
+ };
+
+ @Override
+ protected boolean isAirplaneModeOff() {
+ return true;
+ }
+
+ @Override
+ protected synchronized void addPhoneStateListener() {
+ listenerAdded = true;
+ }
+
+ @Override
+ protected synchronized void removePhoneStateListener() {
+ listenerAdded = false;
+ }
+
+ @Override
+ protected boolean isGeoCoderImplemented() {
+ return true;
+ }
+
+ public boolean isPhoneStateListenerAdded() {
+ return listenerAdded;
+ }
+ }
+
+ private class CountryListenerImpl implements CountryListener {
+ private boolean mNotified;
+ private Country mCountry;
+
+ public void onCountryDetected(Country country) {
+ mNotified = true;
+ mCountry = country;
+ }
+
+ public boolean notified() {
+ return mNotified;
+ }
+
+ public Country getCountry() {
+ return mCountry;
+ }
+ }
+
+ public void testDetectNetworkBasedCountry() {
+ final Country resultCountry = new Country(
+ TestCountryDetector.COUNTRY_ISO, Country.COUNTRY_SOURCE_NETWORK);
+ TestCountryDetector countryDetector = new TestCountryDetector() {
+ @Override
+ protected Country getNetworkBasedCountry() {
+ return resultCountry;
+ }
+ };
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ Country country = countryDetector.detectCountry();
+ assertTrue(sameCountry(country, resultCountry));
+ assertFalse(listener.notified());
+ assertFalse(countryDetector.locationBasedDetectorStarted());
+ assertFalse(countryDetector.locationRefreshStarted());
+ countryDetector.stop();
+ }
+
+ public void testDetectLocationBasedCountry() {
+ final Country resultCountry = new Country(
+ TestCountryDetector.COUNTRY_ISO, Country.COUNTRY_SOURCE_SIM);
+ final Country locationBasedCountry = new Country(
+ TestCountryDetector.COUNTRY_ISO, Country.COUNTRY_SOURCE_LOCATION);
+ TestCountryDetector countryDetector = new TestCountryDetector() {
+ @Override
+ protected Country getSimBasedCountry() {
+ return resultCountry;
+ }
+ };
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ Country country = countryDetector.detectCountry();
+ assertTrue(sameCountry(country, resultCountry));
+ assertTrue(countryDetector.locationBasedDetectorStarted());
+ countryDetector.notifyLocationBasedListener(locationBasedCountry);
+ assertTrue(listener.notified());
+ assertTrue(sameCountry(listener.getCountry(), locationBasedCountry));
+ assertTrue(countryDetector.locationBasedDetectorStopped());
+ assertTrue(countryDetector.locationRefreshStarted());
+ countryDetector.stop();
+ assertTrue(countryDetector.locationRefreshCancelled());
+ }
+
+ public void testLocaleBasedCountry() {
+ final Country resultCountry = new Country(
+ TestCountryDetector.COUNTRY_ISO, Country.COUNTRY_SOURCE_LOCALE);
+ TestCountryDetector countryDetector = new TestCountryDetector() {
+ @Override
+ protected Country getLocaleCountry() {
+ return resultCountry;
+ }
+ };
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ Country country = countryDetector.detectCountry();
+ assertTrue(sameCountry(country, resultCountry));
+ assertFalse(listener.notified());
+ assertTrue(countryDetector.locationBasedDetectorStarted());
+ assertTrue(countryDetector.locationRefreshStarted());
+ countryDetector.stop();
+ assertTrue(countryDetector.locationRefreshCancelled());
+ }
+
+ public void testStoppingDetector() {
+ // Test stopping detector when LocationBasedCountryDetector was started
+ final Country resultCountry = new Country(
+ TestCountryDetector.COUNTRY_ISO, Country.COUNTRY_SOURCE_SIM);
+ TestCountryDetector countryDetector = new TestCountryDetector() {
+ @Override
+ protected Country getSimBasedCountry() {
+ return resultCountry;
+ }
+ };
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ Country country = countryDetector.detectCountry();
+ assertTrue(sameCountry(country, resultCountry));
+ assertTrue(countryDetector.locationBasedDetectorStarted());
+ countryDetector.stop();
+ // The LocationBasedDetector should be stopped.
+ assertTrue(countryDetector.locationBasedDetectorStopped());
+ // The location refresh should not running.
+ assertTrue(countryDetector.locationRefreshCancelled());
+ }
+
+ public void testLocationBasedCountryNotFound() {
+ final Country resultCountry = new Country(
+ TestCountryDetector.COUNTRY_ISO, Country.COUNTRY_SOURCE_SIM);
+ TestCountryDetector countryDetector = new TestCountryDetector() {
+ @Override
+ protected Country getSimBasedCountry() {
+ return resultCountry;
+ }
+ };
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ Country country = countryDetector.detectCountry();
+ assertTrue(sameCountry(country, resultCountry));
+ assertTrue(countryDetector.locationBasedDetectorStarted());
+ countryDetector.notifyLocationBasedListener(null);
+ assertFalse(listener.notified());
+ assertTrue(sameCountry(listener.getCountry(), null));
+ assertTrue(countryDetector.locationBasedDetectorStopped());
+ assertTrue(countryDetector.locationRefreshStarted());
+ countryDetector.stop();
+ assertTrue(countryDetector.locationRefreshCancelled());
+ }
+
+ public void testNoCountryFound() {
+ TestCountryDetector countryDetector = new TestCountryDetector();
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ Country country = countryDetector.detectCountry();
+ assertTrue(sameCountry(country, null));
+ assertTrue(countryDetector.locationBasedDetectorStarted());
+ countryDetector.notifyLocationBasedListener(null);
+ assertFalse(listener.notified());
+ assertTrue(sameCountry(listener.getCountry(), null));
+ assertTrue(countryDetector.locationBasedDetectorStopped());
+ assertTrue(countryDetector.locationRefreshStarted());
+ countryDetector.stop();
+ assertTrue(countryDetector.locationRefreshCancelled());
+ }
+
+ public void testAddRemoveListener() {
+ TestCountryDetector countryDetector = new TestCountryDetector();
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ assertTrue(countryDetector.isPhoneStateListenerAdded());
+ assertTrue(countryDetector.locationBasedDetectorStarted());
+ countryDetector.setCountryListener(null);
+ assertFalse(countryDetector.isPhoneStateListenerAdded());
+ assertTrue(countryDetector.locationBasedDetectorStopped());
+ }
+
+ public void testGeocoderNotImplemented() {
+ TestCountryDetector countryDetector = new TestCountryDetector() {
+ @Override
+ protected boolean isGeoCoderImplemented() {
+ return false;
+ }
+ };
+ CountryListenerImpl listener = new CountryListenerImpl();
+ countryDetector.setCountryListener(listener);
+ assertTrue(countryDetector.isPhoneStateListenerAdded());
+ assertFalse(countryDetector.locationBasedDetectorStarted());
+ countryDetector.setCountryListener(null);
+ assertFalse(countryDetector.isPhoneStateListenerAdded());
+ }
+
+ private boolean sameCountry(Country country1, Country country2) {
+ return country1 == null && country2 == null || country1 != null && country2 != null &&
+ country1.getCountryIso().equalsIgnoreCase(country2.getCountryIso()) &&
+ country1.getSource() == country2.getSource();
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/location/LocationBasedCountryDetectorTest.java b/services/tests/servicestests/src/com/android/server/location/LocationBasedCountryDetectorTest.java
new file mode 100755
index 0000000..71e8e2a
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/location/LocationBasedCountryDetectorTest.java
@@ -0,0 +1,324 @@
+/*
+ * Copyright (C) 2010 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
+ */
+package com.android.server.location;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Timer;
+
+import android.location.Country;
+import android.location.CountryListener;
+import android.location.Location;
+import android.location.LocationListener;
+import android.test.AndroidTestCase;
+
+public class LocationBasedCountryDetectorTest extends AndroidTestCase {
+ private class TestCountryDetector extends LocationBasedCountryDetector {
+ public static final int TOTAL_PROVIDERS = 2;
+ protected Object countryFoundLocker = new Object();
+ protected boolean notifyCountry = false;
+ private final Location mLocation;
+ private final String mCountry;
+ private final long mQueryLocationTimeout;
+ private List<LocationListener> mListeners;
+
+ public TestCountryDetector(String country, String provider) {
+ this(country, provider, 1000 * 60 * 5);
+ }
+
+ public TestCountryDetector(String country, String provider, long queryLocationTimeout) {
+ super(getContext());
+ mCountry = country;
+ mLocation = new Location(provider);
+ mQueryLocationTimeout = queryLocationTimeout;
+ mListeners = new ArrayList<LocationListener>();
+ }
+
+ @Override
+ protected String getCountryFromLocation(Location location) {
+ synchronized (countryFoundLocker) {
+ if (!notifyCountry) {
+ try {
+ countryFoundLocker.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+ if (mLocation.getProvider().endsWith(location.getProvider())) {
+ return mCountry;
+ } else {
+ return null;
+ }
+ }
+
+ @Override
+ protected Location getLastKnownLocation() {
+ return mLocation;
+ }
+
+ @Override
+ protected void registerEnabledProviders(List<LocationListener> listeners) {
+ mListeners.addAll(listeners);
+ }
+
+ @Override
+ protected void unregisterProviders(List<LocationListener> listeners) {
+ for (LocationListener listener : mLocationListeners) {
+ assertTrue(mListeners.remove(listener));
+ }
+ }
+
+ @Override
+ protected long getQueryLocationTimeout() {
+ return mQueryLocationTimeout;
+ }
+
+ @Override
+ protected int getTotalEnabledProviders() {
+ return TOTAL_PROVIDERS;
+ }
+
+ public void notifyLocationFound() {
+ // Listener could be removed in the notification.
+ LocationListener[] listeners = new LocationListener[mListeners.size()];
+ mLocationListeners.toArray(listeners);
+ for (LocationListener listener :listeners) {
+ listener.onLocationChanged(mLocation);
+ }
+ }
+
+ public int getListenersCount() {
+ return mListeners.size();
+ }
+
+ public void notifyCountryFound() {
+ synchronized (countryFoundLocker) {
+ notifyCountry = true;
+ countryFoundLocker.notify();
+ }
+ }
+
+ public Timer getTimer() {
+ return mTimer;
+ }
+
+ public Thread getQueryThread() {
+ return mQueryThread;
+ }
+ }
+
+ private class CountryListenerImpl implements CountryListener {
+ private boolean mNotified;
+ private String mCountryCode;
+ public void onCountryDetected(Country country) {
+ mNotified = true;
+ if (country != null) {
+ mCountryCode = country.getCountryIso();
+ }
+ }
+
+ public boolean notified() {
+ return mNotified;
+ }
+
+ public String getCountry() {
+ return mCountryCode;
+ }
+ }
+
+ public void testFindingCountry() {
+ final String country = "us";
+ final String provider = "Good";
+ CountryListenerImpl countryListener = new CountryListenerImpl();
+ TestCountryDetector detector = new TestCountryDetector(country, provider);
+ detector.setCountryListener(countryListener);
+ detector.detectCountry();
+ assertEquals(detector.getListenersCount(), TestCountryDetector.TOTAL_PROVIDERS);
+ detector.notifyLocationFound();
+ // All listeners should be unregistered
+ assertEquals(detector.getListenersCount(), 0);
+ assertNull(detector.getTimer());
+ Thread queryThread = waitForQueryThreadLaunched(detector);
+ detector.notifyCountryFound();
+ // Wait for query thread ending
+ waitForThreadEnding(queryThread);
+ // QueryThread should be set to NULL
+ assertNull(detector.getQueryThread());
+ assertTrue(countryListener.notified());
+ assertEquals(countryListener.getCountry(), country);
+ }
+
+ public void testFindingCountryCancelled() {
+ final String country = "us";
+ final String provider = "Good";
+ CountryListenerImpl countryListener = new CountryListenerImpl();
+ TestCountryDetector detector = new TestCountryDetector(country, provider);
+ detector.setCountryListener(countryListener);
+ detector.detectCountry();
+ assertEquals(detector.getListenersCount(), TestCountryDetector.TOTAL_PROVIDERS);
+ detector.notifyLocationFound();
+ // All listeners should be unregistered
+ assertEquals(detector.getListenersCount(), 0);
+ // The time should be stopped
+ assertNull(detector.getTimer());
+ Thread queryThread = waitForQueryThreadLaunched(detector);
+ detector.stop();
+ // There is no way to stop the thread, let's test it could be stopped, after get country
+ detector.notifyCountryFound();
+ // Wait for query thread ending
+ waitForThreadEnding(queryThread);
+ // QueryThread should be set to NULL
+ assertNull(detector.getQueryThread());
+ assertTrue(countryListener.notified());
+ assertEquals(countryListener.getCountry(), country);
+ }
+
+ public void testFindingLocationCancelled() {
+ final String country = "us";
+ final String provider = "Good";
+ CountryListenerImpl countryListener = new CountryListenerImpl();
+ TestCountryDetector detector = new TestCountryDetector(country, provider);
+ detector.setCountryListener(countryListener);
+ detector.detectCountry();
+ assertEquals(detector.getListenersCount(), TestCountryDetector.TOTAL_PROVIDERS);
+ detector.stop();
+ // All listeners should be unregistered
+ assertEquals(detector.getListenersCount(), 0);
+ // The time should be stopped
+ assertNull(detector.getTimer());
+ // QueryThread should still be NULL
+ assertNull(detector.getQueryThread());
+ assertFalse(countryListener.notified());
+ }
+
+ public void testFindingLocationFailed() {
+ final String country = "us";
+ final String provider = "Good";
+ long timeout = 1000;
+ TestCountryDetector detector = new TestCountryDetector(country, provider, timeout) {
+ @Override
+ protected Location getLastKnownLocation() {
+ return null;
+ }
+ };
+ CountryListenerImpl countryListener = new CountryListenerImpl();
+ detector.setCountryListener(countryListener);
+ detector.detectCountry();
+ assertEquals(detector.getListenersCount(), TestCountryDetector.TOTAL_PROVIDERS);
+ waitForTimerReset(detector);
+ // All listeners should be unregistered
+ assertEquals(detector.getListenersCount(), 0);
+ // QueryThread should still be NULL
+ assertNull(detector.getQueryThread());
+ assertTrue(countryListener.notified());
+ assertNull(countryListener.getCountry());
+ }
+
+ public void testFindingCountryFailed() {
+ final String country = "us";
+ final String provider = "Good";
+ TestCountryDetector detector = new TestCountryDetector(country, provider) {
+ @Override
+ protected String getCountryFromLocation(Location location) {
+ synchronized (countryFoundLocker) {
+ if (! notifyCountry) {
+ try {
+ countryFoundLocker.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+ // We didn't find country.
+ return null;
+ }
+ };
+ CountryListenerImpl countryListener = new CountryListenerImpl();
+ detector.setCountryListener(countryListener);
+ detector.detectCountry();
+ assertEquals(detector.getListenersCount(), TestCountryDetector.TOTAL_PROVIDERS);
+ detector.notifyLocationFound();
+ // All listeners should be unregistered
+ assertEquals(detector.getListenersCount(), 0);
+ assertNull(detector.getTimer());
+ Thread queryThread = waitForQueryThreadLaunched(detector);
+ detector.notifyCountryFound();
+ // Wait for query thread ending
+ waitForThreadEnding(queryThread);
+ // QueryThread should be set to NULL
+ assertNull(detector.getQueryThread());
+ // CountryListener should be notified
+ assertTrue(countryListener.notified());
+ assertNull(countryListener.getCountry());
+ }
+
+ public void testFindingCountryWithLastKnownLocation() {
+ final String country = "us";
+ final String provider = "Good";
+ long timeout = 1000;
+ TestCountryDetector detector = new TestCountryDetector(country, provider, timeout);
+ CountryListenerImpl countryListener = new CountryListenerImpl();
+ detector.setCountryListener(countryListener);
+ detector.detectCountry();
+ assertEquals(detector.getListenersCount(), TestCountryDetector.TOTAL_PROVIDERS);
+ waitForTimerReset(detector);
+ // All listeners should be unregistered
+ assertEquals(detector.getListenersCount(), 0);
+ Thread queryThread = waitForQueryThreadLaunched(detector);
+ detector.notifyCountryFound();
+ // Wait for query thread ending
+ waitForThreadEnding(queryThread);
+ // QueryThread should be set to NULL
+ assertNull(detector.getQueryThread());
+ // CountryListener should be notified
+ assertTrue(countryListener.notified());
+ assertEquals(countryListener.getCountry(), country);
+ }
+
+ private void waitForTimerReset(TestCountryDetector detector) {
+ int count = 5;
+ long interval = 1000;
+ try {
+ while (count-- > 0 && detector.getTimer() != null) {
+ Thread.sleep(interval);
+ }
+ } catch (InterruptedException e) {
+ }
+ Timer timer = detector.getTimer();
+ assertTrue(timer == null);
+ }
+
+ private void waitForThreadEnding(Thread thread) {
+ try {
+ thread.join(5000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private Thread waitForQueryThreadLaunched(TestCountryDetector detector) {
+ int count = 5;
+ long interval = 1000;
+ try {
+ while (count-- > 0 && detector.getQueryThread() == null) {
+ Thread.sleep(interval);
+ }
+ } catch (InterruptedException e) {
+ }
+ Thread thread = detector.getQueryThread();
+ assertTrue(thread != null);
+ return thread;
+ }
+}
diff --git a/telephony/java/com/android/internal/telephony/CallManager.java b/telephony/java/com/android/internal/telephony/CallManager.java
index 9a13a5f..1381a2d 100644
--- a/telephony/java/com/android/internal/telephony/CallManager.java
+++ b/telephony/java/com/android/internal/telephony/CallManager.java
@@ -16,8 +16,6 @@
package com.android.internal.telephony;
-
-
import android.content.Context;
import android.os.AsyncResult;
import android.os.Handler;
@@ -25,7 +23,6 @@ import android.os.Message;
import android.os.RegistrantList;
import android.telephony.PhoneStateListener;
-
import java.util.ArrayList;
import java.util.List;
@@ -49,8 +46,23 @@ import java.util.List;
public final class CallManager {
private static final int EVENT_DISCONNECT = 100;
- private static final int EVENT_CALL_STATE_CHANGED = 101;
-
+ private static final int EVENT_PRECISE_CALL_STATE_CHANGED = 101;
+ private static final int EVENT_NEW_RINGING_CONNECTION = 102;
+ private static final int EVENT_UNKNOWN_CONNECTION = 103;
+ private static final int EVENT_INCOMING_RING = 104;
+ private static final int EVENT_RINGBACK_TONE = 105;
+ private static final int EVENT_IN_CALL_VOICE_PRIVACY_ON = 106;
+ private static final int EVENT_IN_CALL_VOICE_PRIVACY_OFF = 107;
+ private static final int EVENT_CALL_WAITING = 108;
+ private static final int EVENT_DISPLAY_INFO = 109;
+ private static final int EVENT_SIGNAL_INFO = 110;
+ private static final int EVENT_CDMA_OTA_STATUS_CHANGE = 111;
+ private static final int EVENT_RESEND_INCALL_MUTE = 112;
+ private static final int EVENT_MMI_INITIATE = 113;
+ private static final int EVENT_MMI_COMPLETE = 114;
+ private static final int EVENT_ECM_TIMER_RESET = 115;
+ private static final int EVENT_SUBSCRIPTION_INFO_READY = 116;
+ private static final int EVENT_SUPP_SERVICE_FAILED = 117;
// Singleton instance
private static final CallManager INSTANCE = new CallManager();
@@ -89,13 +101,46 @@ public final class CallManager {
protected final RegistrantList mServiceStateRegistrants
= new RegistrantList();
+ protected final RegistrantList mMmiRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mUnknownConnectionRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mRingbackToneRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mInCallVoicePrivacyOnRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mInCallVoicePrivacyOffRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mCallWaitingRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mDisplayInfoRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mSignalInfoRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mCdmaOtaStatusChangeRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mResendIncallMuteRegistrants
+ = new RegistrantList();
+
+ protected final RegistrantList mMmiInitiateRegistrants
+ = new RegistrantList();
+
protected final RegistrantList mMmiCompleteRegistrants
= new RegistrantList();
- protected final RegistrantList mMmiRegistrants
+ protected final RegistrantList mEcmTimerResetRegistrants
= new RegistrantList();
- protected final RegistrantList mUnknownConnectionRegistrants
+ protected final RegistrantList mSubscriptionInfoReadyRegistrants
= new RegistrantList();
protected final RegistrantList mSuppServiceFailedRegistrants
@@ -118,9 +163,28 @@ public final class CallManager {
}
/**
+ * Get current coarse-grained voice call state.
+ * If the Call Manager has an active call and call waiting occurs,
+ * then the phone state is RINGING not OFFHOOK
+ *
+ */
+ public Phone.State getState() {
+ Phone.State s = Phone.State.IDLE;
+
+ for(Phone phone : mPhones) {
+ if (phone.getState() == Phone.State.RINGING) {
+ return Phone.State.RINGING;
+ } else if (phone.getState() == Phone.State.OFFHOOK) {
+ s = Phone.State.OFFHOOK;
+ }
+ }
+ return s;
+ }
+
+ /**
* Register phone to CallManager
* @param phone
- * @return
+ * @return true if register successfully
*/
public boolean registerPhone(Phone phone) {
if (phone != null && !mPhones.contains(phone)) {
@@ -159,13 +223,45 @@ public final class CallManager {
}
private void registerForPhoneStates(Phone phone) {
- phone.registerForPreciseCallStateChanged(mHandler, EVENT_CALL_STATE_CHANGED, null);
+ phone.registerForPreciseCallStateChanged(mHandler, EVENT_PRECISE_CALL_STATE_CHANGED, null);
phone.registerForDisconnect(mHandler, EVENT_DISCONNECT, null);
+ phone.registerForNewRingingConnection(mHandler, EVENT_NEW_RINGING_CONNECTION, null);
+ phone.registerForUnknownConnection(mHandler, EVENT_UNKNOWN_CONNECTION, null);
+ phone.registerForIncomingRing(mHandler, EVENT_INCOMING_RING, null);
+ phone.registerForRingbackTone(mHandler, EVENT_RINGBACK_TONE, null);
+ phone.registerForInCallVoicePrivacyOn(mHandler, EVENT_IN_CALL_VOICE_PRIVACY_ON, null);
+ phone.registerForInCallVoicePrivacyOff(mHandler, EVENT_IN_CALL_VOICE_PRIVACY_OFF, null);
+ phone.registerForCallWaiting(mHandler, EVENT_CALL_WAITING, null);
+ phone.registerForDisplayInfo(mHandler, EVENT_DISPLAY_INFO, null);
+ phone.registerForSignalInfo(mHandler, EVENT_SIGNAL_INFO, null);
+ phone.registerForCdmaOtaStatusChange(mHandler, EVENT_CDMA_OTA_STATUS_CHANGE, null);
+ phone.registerForResendIncallMute(mHandler, EVENT_RESEND_INCALL_MUTE, null);
+ phone.registerForMmiInitiate(mHandler, EVENT_MMI_INITIATE, null);
+ phone.registerForMmiComplete(mHandler, EVENT_MMI_COMPLETE, null);
+ phone.registerForEcmTimerReset(mHandler, EVENT_ECM_TIMER_RESET, null);
+ phone.registerForSubscriptionInfoReady(mHandler, EVENT_SUBSCRIPTION_INFO_READY, null);
+ phone.registerForSuppServiceFailed(mHandler, EVENT_SUPP_SERVICE_FAILED, null);
}
private void unregisterForPhoneStates(Phone phone) {
phone.unregisterForPreciseCallStateChanged(mHandler);
phone.unregisterForDisconnect(mHandler);
+ phone.unregisterForNewRingingConnection(mHandler);
+ phone.unregisterForUnknownConnection(mHandler);
+ phone.unregisterForIncomingRing(mHandler);
+ phone.unregisterForRingbackTone(mHandler);
+ phone.unregisterForInCallVoicePrivacyOn(mHandler);
+ phone.unregisterForInCallVoicePrivacyOff(mHandler);
+ phone.unregisterForCallWaiting(mHandler);
+ phone.unregisterForDisplayInfo(mHandler);
+ phone.unregisterForSignalInfo(mHandler);
+ phone.unregisterForCdmaOtaStatusChange(mHandler);
+ phone.unregisterForResendIncallMute(mHandler);
+ phone.unregisterForMmiInitiate(mHandler);
+ phone.unregisterForMmiComplete(mHandler);
+ phone.unregisterForEcmTimerReset(mHandler);
+ phone.unregisterForSubscriptionInfoReady(mHandler);
+ phone.unregisterForSuppServiceFailed(mHandler);
}
/**
@@ -523,12 +619,16 @@ public final class CallManager {
* Notifies when a previously untracked non-ringing/waiting connection has appeared.
* This is likely due to some other entity (eg, SIM card application) initiating a call.
*/
- public void registerForUnknownConnection(Handler h, int what, Object obj){}
+ public void registerForUnknownConnection(Handler h, int what, Object obj){
+ mUnknownConnectionRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregisters for unknown connection notifications.
*/
- public void unregisterForUnknownConnection(Handler h){}
+ public void unregisterForUnknownConnection(Handler h){
+ mUnknownConnectionRegistrants.remove(h);
+ }
/**
@@ -543,14 +643,18 @@ public final class CallManager {
* If Connection.isRinging() is true, then
* Connection.getCall() == Phone.getRingingCall()
*/
- public void registerForNewRingingConnection(Handler h, int what, Object obj){}
+ public void registerForNewRingingConnection(Handler h, int what, Object obj){
+ mNewRingingConnectionRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregisters for new ringing connection notification.
* Extraneous calls are tolerated silently
*/
- public void unregisterForNewRingingConnection(Handler h){}
+ public void unregisterForNewRingingConnection(Handler h){
+ mNewRingingConnectionRegistrants.remove(h);
+ }
/**
* Notifies when an incoming call rings.<p>
@@ -560,14 +664,18 @@ public final class CallManager {
* AsyncResult.userObj = obj
* AsyncResult.result = a Connection. <p>
*/
- public void registerForIncomingRing(Handler h, int what, Object obj){}
+ public void registerForIncomingRing(Handler h, int what, Object obj){
+ mIncomingRingRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregisters for ring notification.
* Extraneous calls are tolerated silently
*/
- public void unregisterForIncomingRing(Handler h){}
+ public void unregisterForIncomingRing(Handler h){
+ mIncomingRingRegistrants.remove(h);
+ }
/**
* Notifies when out-band ringback tone is needed.<p>
@@ -578,26 +686,32 @@ public final class CallManager {
* AsyncResult.result = boolean, true to start play ringback tone
* and false to stop. <p>
*/
- public void registerForRingbackTone(Handler h, int what, Object obj){}
+ public void registerForRingbackTone(Handler h, int what, Object obj){
+ mRingbackToneRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregisters for ringback tone notification.
*/
- public void unregisterForRingbackTone(Handler h){}
+ public void unregisterForRingbackTone(Handler h){
+ mRingbackToneRegistrants.remove(h);
+ }
/**
* Registers the handler to reset the uplink mute state to get
* uplink audio.
*/
- public void registerForResendIncallMute(Handler h, int what, Object obj){}
+ public void registerForResendIncallMute(Handler h, int what, Object obj){
+ mResendIncallMuteRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregisters for resend incall mute notifications.
*/
- public void unregisterForResendIncallMute(Handler h){}
-
-
+ public void unregisterForResendIncallMute(Handler h){
+ mResendIncallMuteRegistrants.remove(h);
+ }
/**
* Register for notifications of initiation of a new MMI code request.
@@ -610,13 +724,17 @@ public final class CallManager {
*
* <code>obj.result</code> will be an "MmiCode" object.
*/
- public void registerForMmiInitiate(Handler h, int what, Object obj){}
+ public void registerForMmiInitiate(Handler h, int what, Object obj){
+ mMmiInitiateRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregisters for new MMI initiate notification.
* Extraneous calls are tolerated silently
*/
- public void unregisterForMmiInitiate(Handler h){}
+ public void unregisterForMmiInitiate(Handler h){
+ mMmiInitiateRegistrants.remove(h);
+ }
/**
* Register for notifications that an MMI request has completed
@@ -626,13 +744,17 @@ public final class CallManager {
* <code>Message.obj</code> will contain an AsyncResult.
* <code>obj.result</code> will be an "MmiCode" object
*/
- public void registerForMmiComplete(Handler h, int what, Object obj){}
+ public void registerForMmiComplete(Handler h, int what, Object obj){
+ mMmiCompleteRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregisters for MMI complete notification.
* Extraneous calls are tolerated silently
*/
- public void unregisterForMmiComplete(Handler h){}
+ public void unregisterForMmiComplete(Handler h){
+ mMmiCompleteRegistrants.remove(h);
+ }
/**
* Registration point for Ecm timer reset
@@ -640,15 +762,17 @@ public final class CallManager {
* @param what user-defined message code
* @param obj placed in Message.obj
*/
- public void registerForEcmTimerReset(Handler h, int what, Object obj){}
+ public void registerForEcmTimerReset(Handler h, int what, Object obj){
+ mEcmTimerResetRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregister for notification for Ecm timer reset
* @param h Handler to be removed from the registrant list.
*/
- public void unregisterForEcmTimerReset(Handler h){}
-
-
+ public void unregisterForEcmTimerReset(Handler h){
+ mEcmTimerResetRegistrants.remove(h);
+ }
/**
* Register for ServiceState changed.
@@ -664,73 +788,133 @@ public final class CallManager {
public void unregisterForServiceStateChanged(Handler h){}
/**
- * Register for Supplementary Service notifications from the network.
+ * Register for notifications when a supplementary service attempt fails.
* Message.obj will contain an AsyncResult.
- * AsyncResult.result will be a SuppServiceNotification instance.
*
* @param h Handler that receives the notification message.
* @param what User-defined message code.
* @param obj User object.
*/
- public void registerForSuppServiceNotification(Handler h, int what, Object obj){}
+ public void registerForSuppServiceFailed(Handler h, int what, Object obj){
+ mSuppServiceFailedRegistrants.addUnique(h, what, obj);
+ }
/**
- * Unregisters for Supplementary Service notifications.
+ * Unregister for notifications when a supplementary service attempt fails.
* Extraneous calls are tolerated silently
*
* @param h Handler to be removed from the registrant list.
*/
- public void unregisterForSuppServiceNotification(Handler h){}
+ public void unregisterForSuppServiceFailed(Handler h){
+ mSuppServiceFailedRegistrants.remove(h);
+ }
/**
- * Register for notifications when a supplementary service attempt fails.
- * Message.obj will contain an AsyncResult.
+ * Register for notifications when a sInCall VoicePrivacy is enabled
*
* @param h Handler that receives the notification message.
* @param what User-defined message code.
* @param obj User object.
*/
- public void registerForSuppServiceFailed(Handler h, int what, Object obj){}
+ public void registerForInCallVoicePrivacyOn(Handler h, int what, Object obj){
+ mInCallVoicePrivacyOnRegistrants.addUnique(h, what, obj);
+ }
/**
- * Unregister for notifications when a supplementary service attempt fails.
- * Extraneous calls are tolerated silently
+ * Unregister for notifications when a sInCall VoicePrivacy is enabled
*
* @param h Handler to be removed from the registrant list.
*/
- public void unregisterForSuppServiceFailed(Handler h){}
+ public void unregisterForInCallVoicePrivacyOn(Handler h){
+ mInCallVoicePrivacyOnRegistrants.remove(h);
+ }
/**
- * Register for notifications when a sInCall VoicePrivacy is enabled
+ * Register for notifications when a sInCall VoicePrivacy is disabled
*
* @param h Handler that receives the notification message.
* @param what User-defined message code.
* @param obj User object.
*/
- public void registerForInCallVoicePrivacyOn(Handler h, int what, Object obj){}
+ public void registerForInCallVoicePrivacyOff(Handler h, int what, Object obj){
+ mInCallVoicePrivacyOffRegistrants.addUnique(h, what, obj);
+ }
/**
- * Unegister for notifications when a sInCall VoicePrivacy is enabled
+ * Unregister for notifications when a sInCall VoicePrivacy is disabled
*
* @param h Handler to be removed from the registrant list.
*/
- public void unregisterForInCallVoicePrivacyOn(Handler h){}
+ public void unregisterForInCallVoicePrivacyOff(Handler h){
+ mInCallVoicePrivacyOffRegistrants.remove(h);
+ }
/**
- * Register for notifications when a sInCall VoicePrivacy is disabled
+ * Register for notifications when CDMA call waiting comes
+ *
+ * @param h Handler that receives the notification message.
+ * @param what User-defined message code.
+ * @param obj User object.
+ */
+ public void registerForCallWaiting(Handler h, int what, Object obj){
+ mCallWaitingRegistrants.addUnique(h, what, obj);
+ }
+
+ /**
+ * Unregister for notifications when CDMA Call waiting comes
+ * @param h Handler to be removed from the registrant list.
+ */
+ public void unregisterForCallWaiting(Handler h){
+ mCallWaitingRegistrants.remove(h);
+ }
+
+
+ /**
+ * Register for signal information notifications from the network.
+ * Message.obj will contain an AsyncResult.
+ * AsyncResult.result will be a SuppServiceNotification instance.
+ *
+ * @param h Handler that receives the notification message.
+ * @param what User-defined message code.
+ * @param obj User object.
+ */
+
+ public void registerForSignalInfo(Handler h, int what, Object obj){
+ mSignalInfoRegistrants.addUnique(h, what, obj);
+ }
+
+ /**
+ * Unregisters for signal information notifications.
+ * Extraneous calls are tolerated silently
+ *
+ * @param h Handler to be removed from the registrant list.
+ */
+ public void unregisterForSignalInfo(Handler h){
+ mSignalInfoRegistrants.remove(h);
+ }
+
+ /**
+ * Register for display information notifications from the network.
+ * Message.obj will contain an AsyncResult.
+ * AsyncResult.result will be a SuppServiceNotification instance.
*
* @param h Handler that receives the notification message.
* @param what User-defined message code.
* @param obj User object.
*/
- public void registerForInCallVoicePrivacyOff(Handler h, int what, Object obj){}
+ public void registerForDisplayInfo(Handler h, int what, Object obj){
+ mDisplayInfoRegistrants.addUnique(h, what, obj);
+ }
/**
- * Unegister for notifications when a sInCall VoicePrivacy is disabled
+ * Unregisters for display information notifications.
+ * Extraneous calls are tolerated silently
*
* @param h Handler to be removed from the registrant list.
*/
- public void unregisterForInCallVoicePrivacyOff(Handler h){}
+ public void unregisterForDisplayInfo(Handler h) {
+ mDisplayInfoRegistrants.remove(h);
+ }
/**
* Register for notifications when CDMA OTA Provision status change
@@ -739,13 +923,17 @@ public final class CallManager {
* @param what User-defined message code.
* @param obj User object.
*/
- public void registerForCdmaOtaStatusChange(Handler h, int what, Object obj){}
+ public void registerForCdmaOtaStatusChange(Handler h, int what, Object obj){
+ mCdmaOtaStatusChangeRegistrants.addUnique(h, what, obj);
+ }
/**
- * Unegister for notifications when CDMA OTA Provision status change
+ * Unregister for notifications when CDMA OTA Provision status change
* @param h Handler to be removed from the registrant list.
*/
- public void unregisterForCdmaOtaStatusChange(Handler h){}
+ public void unregisterForCdmaOtaStatusChange(Handler h){
+ mCdmaOtaStatusChangeRegistrants.remove(h);
+ }
/**
* Registration point for subscription info ready
@@ -753,13 +941,17 @@ public final class CallManager {
* @param what what code of message when delivered
* @param obj placed in Message.obj
*/
- public void registerForSubscriptionInfoReady(Handler h, int what, Object obj){}
+ public void registerForSubscriptionInfoReady(Handler h, int what, Object obj){
+ mSubscriptionInfoReadyRegistrants.addUnique(h, what, obj);
+ }
/**
* Unregister for notifications for subscription info
* @param h Handler to be removed from the registrant list.
*/
- public void unregisterForSubscriptionInfoReady(Handler h){}
+ public void unregisterForSubscriptionInfoReady(Handler h){
+ mSubscriptionInfoReadyRegistrants.remove(h);
+ }
/* APIs to access foregroudCalls, backgroudCalls, and ringingCalls
* 1. APIs to access list of calls
@@ -974,9 +1166,57 @@ public final class CallManager {
case EVENT_DISCONNECT:
mDisconnectRegistrants.notifyRegistrants((AsyncResult) msg.obj);
break;
- case EVENT_CALL_STATE_CHANGED:
+ case EVENT_PRECISE_CALL_STATE_CHANGED:
mPreciseCallStateRegistrants.notifyRegistrants((AsyncResult) msg.obj);
break;
+ case EVENT_NEW_RINGING_CONNECTION:
+ mNewRingingConnectionRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_UNKNOWN_CONNECTION:
+ mUnknownConnectionRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_INCOMING_RING:
+ mIncomingRingRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_RINGBACK_TONE:
+ mRingbackToneRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_IN_CALL_VOICE_PRIVACY_ON:
+ mInCallVoicePrivacyOnRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_IN_CALL_VOICE_PRIVACY_OFF:
+ mInCallVoicePrivacyOffRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_CALL_WAITING:
+ mCallWaitingRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_DISPLAY_INFO:
+ mDisplayInfoRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_SIGNAL_INFO:
+ mSignalInfoRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_CDMA_OTA_STATUS_CHANGE:
+ mCdmaOtaStatusChangeRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_RESEND_INCALL_MUTE:
+ mResendIncallMuteRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_MMI_INITIATE:
+ mMmiInitiateRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_MMI_COMPLETE:
+ mMmiCompleteRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_ECM_TIMER_RESET:
+ mEcmTimerResetRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_SUBSCRIPTION_INFO_READY:
+ mSubscriptionInfoReadyRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
+ case EVENT_SUPP_SERVICE_FAILED:
+ mSuppServiceFailedRegistrants.notifyRegistrants((AsyncResult) msg.obj);
+ break;
}
}
};
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaCall.java b/telephony/java/com/android/internal/telephony/cdma/CdmaCall.java
index c3bb01f..4ad61bb 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaCall.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaCall.java
@@ -75,8 +75,7 @@ public final class CdmaCall extends Call {
public Phone
getPhone() {
- //TODO, see GsmCall
- return null;
+ return owner.phone;
}
public boolean isMultiparty() {
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmCall.java b/telephony/java/com/android/internal/telephony/gsm/GsmCall.java
index 9542d20..58124a2 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmCall.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmCall.java
@@ -70,8 +70,7 @@ class GsmCall extends Call {
public Phone
getPhone() {
- //TODO
- return null;
+ return owner.phone;
}
public boolean
diff --git a/telephony/tests/telephonytests/Android.mk b/telephony/tests/telephonytests/Android.mk
index 45e265a..98e4403 100644
--- a/telephony/tests/telephonytests/Android.mk
+++ b/telephony/tests/telephonytests/Android.mk
@@ -5,6 +5,8 @@ LOCAL_MODULE_TAGS := tests
LOCAL_SRC_FILES := $(call all-subdir-java-files)
+LOCAL_STATIC_JAVA_LIBRARIES := librilproto-java
+
LOCAL_JAVA_LIBRARIES := android.test.runner
LOCAL_PACKAGE_NAME := FrameworksTelephonyTests
diff --git a/telephony/tests/telephonytests/AndroidManifest.xml b/telephony/tests/telephonytests/AndroidManifest.xml
index 6a97423..ba1d957 100644
--- a/telephony/tests/telephonytests/AndroidManifest.xml
+++ b/telephony/tests/telephonytests/AndroidManifest.xml
@@ -32,6 +32,13 @@
android:targetPackage="com.android.frameworks.telephonytests"
android:label="Frameworks Telephony Tests">
</instrumentation>
+
+ <instrumentation android:name=".TelephonyMockRilTestRunner"
+ android:targetPackage="com.android.frameworks.telephonytests"
+ android:label="Test Runner for Mock Ril Tests"
+ />
+
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
+ <uses-permission android:name="android.permission.INTERNET" />
</manifest>
diff --git a/telephony/tests/telephonytests/src/com/android/frameworks/telephonytests/TelephonyMockRilTestRunner.java b/telephony/tests/telephonytests/src/com/android/frameworks/telephonytests/TelephonyMockRilTestRunner.java
new file mode 100644
index 0000000..9192f57
--- /dev/null
+++ b/telephony/tests/telephonytests/src/com/android/frameworks/telephonytests/TelephonyMockRilTestRunner.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2010, 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.
+ */
+
+package com.android.frameworks.telephonytests;
+
+import android.os.Bundle;
+
+import android.test.InstrumentationTestRunner;
+import android.test.InstrumentationTestSuite;
+import android.util.Log;
+
+import java.io.IOException;
+
+import com.android.internal.telephony.RilChannel;
+import com.android.internal.telephony.mockril.MockRilTest;
+
+import junit.framework.TestSuite;
+
+public class TelephonyMockRilTestRunner extends InstrumentationTestRunner {
+
+ public RilChannel mMockRilChannel;
+
+ @Override
+ public TestSuite getAllTests() {
+ log("getAllTests E");
+ TestSuite suite = new InstrumentationTestSuite(this);
+ suite.addTestSuite(MockRilTest.class);
+ log("getAllTests X");
+ return suite;
+ }
+
+ @Override
+ public ClassLoader getLoader() {
+ log("getLoader EX");
+ return TelephonyMockRilTestRunner.class.getClassLoader();
+ }
+
+ @Override
+ public void onCreate(Bundle icicle) {
+ log("onCreate E");
+ try {
+ mMockRilChannel = RilChannel.makeRilChannel();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ log("onCreate X");
+
+ super.onCreate(icicle);
+ }
+
+ @Override
+ public void onDestroy() {
+ // I've not seen this called
+ log("onDestroy EX");
+ super.onDestroy();
+ }
+
+ @Override
+ public void onStart() {
+ // Called when the instrumentation thread is started.
+ // At the moment we don't need the thread so return
+ // which will shut down this unused thread.
+ log("onStart EX");
+ super.onStart();
+ }
+
+ @Override
+ public void finish(int resultCode, Bundle results) {
+ // Called when complete so I ask the mMockRilChannel to quit.
+ log("finish E");
+ mMockRilChannel.close();
+ log("finish X");
+ super.finish(resultCode, results);
+ }
+
+ private void log(String s) {
+ Log.e("TelephonyMockRilTestRunner", s);
+ }
+}
diff --git a/telephony/tests/telephonytests/src/com/android/internal/telephony/mockril/MockRilTest.java b/telephony/tests/telephonytests/src/com/android/internal/telephony/mockril/MockRilTest.java
new file mode 100644
index 0000000..ee03b7c
--- /dev/null
+++ b/telephony/tests/telephonytests/src/com/android/internal/telephony/mockril/MockRilTest.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package com.android.internal.telephony.mockril;
+
+import android.util.Log;
+import android.test.InstrumentationTestCase;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import com.android.internal.communication.MsgHeader;
+import com.android.internal.communication.Msg;
+import com.android.internal.telephony.RilChannel;
+import com.android.internal.telephony.ril_proto.RilCtrlCmds;
+
+import com.android.frameworks.telephonytests.TelephonyMockRilTestRunner;
+import com.google.protobuf.micro.InvalidProtocolBufferMicroException;
+
+// Test suite for test ril
+public class MockRilTest extends InstrumentationTestCase {
+ private static final String TAG = "MockRilTest";
+
+ RilChannel mMockRilChannel;
+ TelephonyMockRilTestRunner mRunner;
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ mRunner = (TelephonyMockRilTestRunner)getInstrumentation();
+ mMockRilChannel = mRunner.mMockRilChannel;
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ static void log(String s) {
+ Log.v(TAG, s);
+ }
+
+ /**
+ * Test protobuf serialization and deserialization
+ * @throws InvalidProtocolBufferMicroException
+ */
+ public void testProtobufSerDes() throws InvalidProtocolBufferMicroException {
+ log("testProtobufSerdes E");
+
+ RilCtrlCmds.CtrlRspRadioState rs = new RilCtrlCmds.CtrlRspRadioState();
+ assertTrue(String.format("expected rs.state == 0 was %d", rs.getState()),
+ rs.getState() == 0);
+ rs.setState(1);
+ assertTrue(String.format("expected rs.state == 1 was %d", rs.getState()),
+ rs.getState() == 1);
+
+ byte[] rs_ser = rs.toByteArray();
+ RilCtrlCmds.CtrlRspRadioState rsNew = RilCtrlCmds.CtrlRspRadioState.parseFrom(rs_ser);
+ assertTrue(String.format("expected rsNew.state == 1 was %d", rs.getState()),
+ rs.getState() == 1);
+
+ log("testProtobufSerdes X");
+ }
+
+ /**
+ * Test echo command works using writeMsg & readMsg
+ */
+ public void testEchoMsg() throws IOException {
+ log("testEchoMsg E");
+
+ MsgHeader mh = new MsgHeader();
+ mh.setCmd(0);
+ mh.setToken(1);
+ mh.setStatus(2);
+ ByteBuffer data = ByteBuffer.allocate(3);
+ data.put((byte)3);
+ data.put((byte)4);
+ data.put((byte)5);
+ Msg.send(mMockRilChannel, mh, data);
+
+ Msg respMsg = Msg.recv(mMockRilChannel);
+ assertTrue(String.format("expected mhd.header.cmd == 0 was %d",respMsg.getCmd()),
+ respMsg.getCmd() == 0);
+ assertTrue(String.format("expected mhd.header.token == 1 was %d",respMsg.getToken()),
+ respMsg.getToken() == 1);
+ assertTrue(String.format("expected mhd.header.status == 2 was %d", respMsg.getStatus()),
+ respMsg.getStatus() == 2);
+ assertTrue(String.format("expected mhd.data[0] == 3 was %d", respMsg.getData(0)),
+ respMsg.getData(0) == 3);
+ assertTrue(String.format("expected mhd.data[1] == 4 was %d", respMsg.getData(1)),
+ respMsg.getData(1) == 4);
+ assertTrue(String.format("expected mhd.data[2] == 5 was %d", respMsg.getData(2)),
+ respMsg.getData(2) == 5);
+
+ log("testEchoMsg X");
+ }
+
+ /**
+ * Test get as
+ */
+ public void testGetAs() {
+ log("testGetAs E");
+
+ // Use a message header as the protobuf data content
+ MsgHeader mh = new MsgHeader();
+ mh.setCmd(12345);
+ mh.setToken(9876);
+ mh.setStatus(7654);
+ mh.setLengthData(4321);
+ byte[] data = mh.toByteArray();
+ MsgHeader mhResult = Msg.getAs(MsgHeader.class, data);
+
+ assertTrue(String.format("expected cmd == 12345 was %d", mhResult.getCmd()),
+ mhResult.getCmd() == 12345);
+ assertTrue(String.format("expected token == 9876 was %d", mhResult.getToken()),
+ mhResult.getToken() == 9876);
+ assertTrue(String.format("expected status == 7654 was %d", mhResult.getStatus()),
+ mhResult.getStatus() == 7654);
+ assertTrue(String.format("expected lengthData == 4321 was %d", mhResult.getLengthData()),
+ mhResult.getLengthData() == 4321);
+
+ Msg msg = Msg.obtain();
+ msg.setData(ByteBuffer.wrap(data));
+
+ mhResult = msg.getDataAs(MsgHeader.class);
+
+ assertTrue(String.format("expected cmd == 12345 was %d", mhResult.getCmd()),
+ mhResult.getCmd() == 12345);
+ assertTrue(String.format("expected token == 9876 was %d", mhResult.getToken()),
+ mhResult.getToken() == 9876);
+ assertTrue(String.format("expected status == 7654 was %d", mhResult.getStatus()),
+ mhResult.getStatus() == 7654);
+ assertTrue(String.format("expected lengthData == 4321 was %d", mhResult.getLengthData()),
+ mhResult.getLengthData() == 4321);
+
+ log("testGetAs X");
+ }
+
+ public void testGetRadioState() throws IOException {
+ log("testGetRadioState E");
+
+ Msg.send(mMockRilChannel, 1, 9876, 0, null);
+
+ Msg resp = Msg.recv(mMockRilChannel);
+ //resp.printHeader("testGetRadioState");
+
+ assertTrue(String.format("expected cmd == 1 was %d", resp.getCmd()),
+ resp.getCmd() == 1);
+ assertTrue(String.format("expected token == 9876 was %d", resp.getToken()),
+ resp.getToken() == 9876);
+ assertTrue(String.format("expected status == 0 was %d", resp.getStatus()),
+ resp.getStatus() == 0);
+
+ RilCtrlCmds.CtrlRspRadioState rsp = resp.getDataAs(RilCtrlCmds.CtrlRspRadioState.class);
+
+ int state = rsp.getState();
+ log("testGetRadioState state=" + state);
+ assertTrue(String.format("expected RadioState >= 0 && RadioState <= 9 was %d", state),
+ ((state >= 0) && (state <= 9)));
+
+ log("testGetRadioState X");
+ }
+}
diff --git a/test-runner/src/android/test/LoaderTestCase.java b/test-runner/src/android/test/LoaderTestCase.java
new file mode 100644
index 0000000..8be6590
--- /dev/null
+++ b/test-runner/src/android/test/LoaderTestCase.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2010 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
+ */
+
+package android.test;
+
+import android.content.Loader;
+import android.content.Loader.OnLoadCompleteListener;
+import android.os.AsyncTask;
+import android.os.Handler;
+import android.os.Looper;
+import android.os.Message;
+
+import java.util.concurrent.ArrayBlockingQueue;
+
+/**
+ * A convenience class for testing {@link Loader}s. This test case
+ * provides a simple way to synchronously get the result from a Loader making
+ * it easy to assert that the Loader returns the expected result.
+ */
+public class LoaderTestCase extends AndroidTestCase {
+ static {
+ // Force class loading of AsyncTask on the main thread so that it's handlers are tied to
+ // the main thread and responses from the worker thread get delivered on the main thread.
+ // The tests are run on another thread, allowing them to block waiting on a response from
+ // the code running on the main thread. The main thread can't block since the AysncTask
+ // results come in via the event loop.
+ new AsyncTask<Void, Void, Void>() {
+ @Override
+ protected Void doInBackground(Void... args) {return null;}
+ @Override
+ protected void onPostExecute(Void result) {}
+ };
+ }
+
+ /**
+ * Runs a Loader synchronously and returns the result of the load. The loader will
+ * be started, stopped, and destroyed by this method so it cannot be reused.
+ *
+ * @param loader The loader to run synchronously
+ * @return The result from the loader
+ */
+ public <T> T getLoaderResultSynchronously(final Loader<T> loader) {
+ // The test thread blocks on this queue until the loader puts it's result in
+ final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);
+
+ // This callback runs on the "main" thread and unblocks the test thread
+ // when it puts the result into the blocking queue
+ final OnLoadCompleteListener<T> listener = new OnLoadCompleteListener<T>() {
+ @Override
+ public void onLoadComplete(Loader<T> completedLoader, T data) {
+ // Shut the loader down
+ completedLoader.unregisterListener(this);
+ completedLoader.stopLoading();
+ completedLoader.destroy();
+
+ // Store the result, unblocking the test thread
+ queue.add(data);
+ }
+ };
+
+ // This handler runs on the "main" thread of the process since AsyncTask
+ // is documented as needing to run on the main thread and many Loaders use
+ // AsyncTask
+ final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {
+ @Override
+ public void handleMessage(Message msg) {
+ loader.registerListener(0, listener);
+ loader.startLoading();
+ }
+ };
+
+ // Ask the main thread to start the loading process
+ mainThreadHandler.sendEmptyMessage(0);
+
+ // Block on the queue waiting for the result of the load to be inserted
+ T result;
+ while (true) {
+ try {
+ result = queue.take();
+ break;
+ } catch (InterruptedException e) {
+ throw new RuntimeException("waiting thread interrupted", e);
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java b/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java
index a5870f8..b62db51 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/CallbackProxy.java
@@ -177,7 +177,7 @@ public class CallbackProxy extends Handler implements EventSender, LayoutTestCon
break;
case LAYOUT_DUMP_TEXT:
- mLayoutTestController.dumpAsText();
+ mLayoutTestController.dumpAsText(msg.arg1 == 1);
break;
case LAYOUT_DUMP_CHILD_FRAMES_TEXT:
@@ -387,7 +387,11 @@ public class CallbackProxy extends Handler implements EventSender, LayoutTestCon
}
public void dumpAsText() {
- obtainMessage(LAYOUT_DUMP_TEXT).sendToTarget();
+ obtainMessage(LAYOUT_DUMP_TEXT, 0).sendToTarget();
+ }
+
+ public void dumpAsText(boolean enablePixelTests) {
+ obtainMessage(LAYOUT_DUMP_TEXT, enablePixelTests ? 1 : 0).sendToTarget();
}
public void dumpChildFramesAsText() {
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
index 8bdf77c..939c623 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/FileFilter.java
@@ -110,6 +110,23 @@ public class FileFilter {
ignoreResultList.add("storage/private-browsing-readonly.html"); // private browsing not supported
ignoreResultList.add("websocket/tests/workers"); // workers not supported
+ // Expected failures due to missing expected results
+ ignoreResultList.add("dom/xhtml/level3/core/canonicalform08.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/canonicalform09.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/documentgetinputencoding03.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/entitygetinputencoding02.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/entitygetxmlversion02.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri05.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri07.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri09.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri10.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri11.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri15.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri17.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodegetbaseuri18.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodelookupnamespaceuri01.xhtml");
+ ignoreResultList.add("dom/xhtml/level3/core/nodelookupprefix19.xhtml");
+
// TODO: These need to be triaged
ignoreResultList.add("fast/css/case-transform.html"); // will not fix #619707
ignoreResultList.add("fast/dom/Element/offsetLeft-offsetTop-body-quirk.html"); // different screen size result in extra spaces in Apple compared to us
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java
index 83460bd..15288b5 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/LayoutTestController.java
@@ -18,30 +18,30 @@ package com.android.dumprendertree;
public interface LayoutTestController {
- public void dumpAsText();
- public void dumpChildFramesAsText();
- public void waitUntilDone();
- public void notifyDone();
-
- // Force a redraw of the page
- public void display();
- // Used with pixel dumps of content
- public void testRepaint();
-
- // If the page title changes, add the information to the output.
- public void dumpTitleChanges();
- public void dumpBackForwardList();
- public void dumpChildFrameScrollPositions();
- public void dumpEditingCallbacks();
-
- // Show/Hide window for window.onBlur() testing
- public void setWindowIsKey(boolean b);
- // Mac function, used to disable events going to the window
- public void setMainFrameIsFirstResponder(boolean b);
-
- public void dumpSelectionRect();
-
- // invalidate and draw one line at a time of the web view.
+ public void dumpAsText(boolean enablePixelTests);
+ public void dumpChildFramesAsText();
+ public void waitUntilDone();
+ public void notifyDone();
+
+ // Force a redraw of the page
+ public void display();
+ // Used with pixel dumps of content
+ public void testRepaint();
+
+ // If the page title changes, add the information to the output.
+ public void dumpTitleChanges();
+ public void dumpBackForwardList();
+ public void dumpChildFrameScrollPositions();
+ public void dumpEditingCallbacks();
+
+ // Show/Hide window for window.onBlur() testing
+ public void setWindowIsKey(boolean b);
+ // Mac function, used to disable events going to the window
+ public void setMainFrameIsFirstResponder(boolean b);
+
+ public void dumpSelectionRect();
+
+ // invalidate and draw one line at a time of the web view.
public void repaintSweepHorizontally();
// History testing functions
diff --git a/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java
index bf66fae..ef96813 100644
--- a/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java
+++ b/tests/DumpRenderTree/src/com/android/dumprendertree/TestShellActivity.java
@@ -342,7 +342,12 @@ public class TestShellActivity extends Activity implements LayoutTestController
// .......................................
// LayoutTestController Functions
- public void dumpAsText() {
+ public void dumpAsText(boolean enablePixelTests) {
+ // Added after webkit update to r63859. See trac.webkit.org/changeset/63730.
+ if (enablePixelTests) {
+ Log.v(LOGTAG, "dumpAsText(enablePixelTests == true) not implemented on Android!");
+ }
+
mDumpDataType = DumpDataType.DUMP_AS_TEXT;
mDumpTopFrameAsText = true;
if (mWebView != null) {
diff --git a/tests/DumpRenderTree2/AndroidManifest.xml b/tests/DumpRenderTree2/AndroidManifest.xml
index 14df611..1213674 100644
--- a/tests/DumpRenderTree2/AndroidManifest.xml
+++ b/tests/DumpRenderTree2/AndroidManifest.xml
@@ -25,13 +25,13 @@ limitations under the License.
</intent-filter>
</activity>
- <activity android:name=".LayoutTestsRunner"
- android:label="Layout tests' runner">
+ <activity android:name=".TestsListActivity"
+ android:label="Tests' list activity">
</activity>
- <activity android:name=".LayoutTestsExecuter"
- android:label="Layout tests' executer"
- android:process=":executer">
+ <activity android:name=".LayoutTestsExecutor"
+ android:label="Layout tests' executor"
+ android:process=":executor">
</activity>
<service android:name="ManagerService">
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/AbstractResult.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/AbstractResult.java
index 3c7dee2..0a80ed4 100644
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/AbstractResult.java
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/AbstractResult.java
@@ -27,8 +27,21 @@ import android.webkit.WebView;
public abstract class AbstractResult {
public enum TestType {
- TEXT,
- PIXEL
+ TEXT {
+ @Override
+ public AbstractResult createResult(Bundle bundle) {
+ return new TextResult(bundle);
+ }
+ },
+ RENDER_TREE {
+ @Override
+ public AbstractResult createResult(Bundle bundle) {
+ /** TODO: RenderTree tests are not yet supported */
+ return null;
+ }
+ };
+
+ public abstract AbstractResult createResult(Bundle bundle);
}
public enum ResultCode {
@@ -101,6 +114,8 @@ public abstract class AbstractResult {
*/
public abstract TestType getType();
+ public abstract String getRelativePath();
+
/**
* Returns a piece of HTML code that presents a visual diff between a result and
* the expected result.
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTest.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTest.java
deleted file mode 100644
index 1312ef9..0000000
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTest.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-package com.android.dumprendertree2;
-
-import android.app.Activity;
-import android.net.Uri;
-import android.os.Handler;
-import android.os.Message;
-import android.webkit.JsPromptResult;
-import android.webkit.JsResult;
-import android.webkit.WebChromeClient;
-import android.webkit.WebSettings;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import android.webkit.WebStorage.QuotaUpdater;
-
-import java.io.File;
-
-/**
- * A class that represents a single layout test. It is responsible for running the test,
- * checking its result and creating an AbstractResult object.
- */
-public class LayoutTest {
-
- private static final String LOG_TAG = "LayoutTest";
-
- public static final int MSG_ACTUAL_RESULT_OBTAINED = 0;
-
- private String mRelativePath;
- private String mTestsRootDirPath;
- private String mUrl;
- private boolean mOnTestFinishedCalled;
- private Message mTestFinishedMsg;
- private AbstractResult mResult;
-
- private WebView mWebView;
- private Activity mActivity;
-
- private final Handler mResultHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- if (msg.what == MSG_ACTUAL_RESULT_OBTAINED) {
- mResult.setExpectedTextResult(LayoutTestsRunnerThread
- .getExpectedTextResult(mRelativePath));
- mResult.setExpectedImageResult(LayoutTestsRunnerThread
- .getExpectedImageResult(mRelativePath));
- mTestFinishedMsg.sendToTarget();
- }
- }
- };
-
- private WebViewClient mWebViewClient = new WebViewClient() {
- @Override
- public void onPageFinished(WebView view, String url) {
- /** Some tests fire up many page loads, we don't want to detect them */
- if (!url.equals(mUrl)) {
- return;
- }
-
- onTestFinished();
- }
- };
-
- private WebChromeClient mWebChromeClient = new WebChromeClient() {
- @Override
- public void onExceededDatabaseQuota(String url, String databaseIdentifier,
- long currentQuota, long estimatedSize, long totalUsedQuota,
- QuotaUpdater quotaUpdater) {
- /** TODO: This should be recorded as part of the text result */
- quotaUpdater.updateQuota(currentQuota + 5 * 1024 * 1024);
- }
-
- @Override
- public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
- /** TODO: Alerts should be recorded as part of text result */
- result.confirm();
- return true;
- }
-
- @Override
- public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
- /** TODO: Alerts should be recorded as part of text result */
- result.confirm();
- return true;
- }
-
- @Override
- public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
- JsPromptResult result) {
- /** TODO: Alerts should be recorded as part of text result */
- result.confirm();
- return true;
- }
-
- };
-
- public LayoutTest(String relativePath, String testsRootDirPath, Message testFinishedMsg,
- LayoutTestsRunner activity) {
- mRelativePath = relativePath;
- mTestsRootDirPath = testsRootDirPath;
- mTestFinishedMsg = testFinishedMsg;
- mActivity = activity;
- }
-
- public LayoutTest(AbstractResult result, String relativePath) {
- mResult = result;
- mRelativePath = relativePath;
- }
-
- public void run() {
- mWebView = new WebView(mActivity);
- mActivity.setContentView(mWebView);
-
- setupWebView();
-
- /** TODO: Add timeout msg */
- mUrl = Uri.fromFile(new File(mTestsRootDirPath, mRelativePath)).toString();
- mWebView.loadUrl(mUrl);
- }
-
- private void onTestFinished() {
- if (mOnTestFinishedCalled) {
- return;
- }
-
- mOnTestFinishedCalled = true;
-
- /**
- * If the result has not been set by the time the test finishes we create
- * a default type of result.
- */
- if (mResult == null) {
- /** TODO: Default type should be RenderTreeResult. We don't support it now. */
- mResult = new TextResult(mRelativePath);
- }
-
- /** TODO: Implement waitUntilDone */
-
- mResult.obtainActualResults(mWebView,
- mResultHandler.obtainMessage(MSG_ACTUAL_RESULT_OBTAINED));
- }
-
- private void setupWebView() {
- WebSettings webViewSettings = mWebView.getSettings();
- webViewSettings.setAppCacheEnabled(true);
- webViewSettings.setAppCachePath(mActivity.getApplicationContext().getCacheDir().getPath());
- webViewSettings.setAppCacheMaxSize(Long.MAX_VALUE);
- webViewSettings.setJavaScriptEnabled(true);
- webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
- webViewSettings.setSupportMultipleWindows(true);
- webViewSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
- webViewSettings.setDatabaseEnabled(true);
- webViewSettings.setDatabasePath(mActivity.getDir("databases", 0).getAbsolutePath());
- webViewSettings.setDomStorageEnabled(true);
- webViewSettings.setWorkersEnabled(false);
- webViewSettings.setXSSAuditorEnabled(false);
-
- mWebView.setWebViewClient(mWebViewClient);
- mWebView.setWebChromeClient(mWebChromeClient);
- }
-
- public AbstractResult getResult() {
- return mResult;
- }
-
- public String getRelativePath() {
- return mRelativePath;
- }
-} \ No newline at end of file
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsExecuter.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsExecutor.java
index 6fd3085..608b14e 100644
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsExecuter.java
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsExecutor.java
@@ -30,6 +30,7 @@ import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
+import android.view.Window;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
@@ -47,7 +48,7 @@ import java.util.List;
* to ManagerService. The reason why is to handle crashing (test that crashes brings down
* whole process with it).
*/
-public class LayoutTestsExecuter extends Activity {
+public class LayoutTestsExecutor extends Activity {
/** TODO: make it a setting */
static final String TESTS_ROOT_DIR_PATH =
@@ -55,14 +56,23 @@ public class LayoutTestsExecuter extends Activity {
File.separator + "android" +
File.separator + "LayoutTests";
- private static final String LOG_TAG = "LayoutTestExecuter";
+ private static final String LOG_TAG = "LayoutTestExecutor";
public static final String EXTRA_TESTS_LIST = "TestsList";
+ public static final String EXTRA_TEST_INDEX = "TestIndex";
private static final int MSG_ACTUAL_RESULT_OBTAINED = 0;
private List<String> mTestsList;
- private int mCurrentTestCount = 0;
+
+ /**
+ * This is a number of currently running test. It is 0-based and doesn't reset after
+ * the crash. Initial index is passed to LayoutTestsExecuter in the intent that starts
+ * it.
+ */
+ private int mCurrentTestIndex;
+
+ private int mTotalTestCount;
private WebView mCurrentWebView;
private String mCurrentTestRelativePath;
@@ -94,6 +104,8 @@ public class LayoutTestsExecuter extends Activity {
public void handleMessage(Message msg) {
if (msg.what == MSG_ACTUAL_RESULT_OBTAINED) {
reportResultToService();
+ mCurrentTestIndex++;
+ updateProgressBar();
runNextTest();
}
}
@@ -153,8 +165,12 @@ public class LayoutTestsExecuter extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ requestWindowFeature(Window.FEATURE_PROGRESS);
+
Intent intent = getIntent();
mTestsList = intent.getStringArrayListExtra(EXTRA_TESTS_LIST);
+ mCurrentTestIndex = intent.getIntExtra(EXTRA_TEST_INDEX, -1);
+ mTotalTestCount = mCurrentTestIndex + mTestsList.size();
bindService(new Intent(this, ManagerService.class), mServiceConnection,
Context.BIND_AUTO_CREATE);
@@ -191,7 +207,6 @@ public class LayoutTestsExecuter extends Activity {
return;
}
- mCurrentTestCount++;
mCurrentTestRelativePath = mTestsList.remove(0);
mCurrentTestUri =
Uri.fromFile(new File(TESTS_ROOT_DIR_PATH, mCurrentTestRelativePath)).toString();
@@ -226,6 +241,7 @@ public class LayoutTestsExecuter extends Activity {
Message serviceMsg =
Message.obtain(null, ManagerService.MSG_PROCESS_ACTUAL_RESULTS);
Bundle bundle = mCurrentResult.getBundle();
+ bundle.putInt("testIndex", mCurrentTestIndex);
/** TODO: Add timeout info to bundle */
serviceMsg.setData(bundle);
mManagerServiceMessenger.send(serviceMsg);
@@ -234,7 +250,20 @@ public class LayoutTestsExecuter extends Activity {
}
}
+ private void updateProgressBar() {
+ getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
+ mCurrentTestIndex * Window.PROGRESS_END / mTotalTestCount);
+ setTitle(mCurrentTestIndex * 100 / mTotalTestCount + "% " +
+ "(" + mCurrentTestIndex + "/" + mTotalTestCount + ")");
+ }
+
private void onAllTestsFinished() {
- Log.d(LOG_TAG + "::onAllTestsFisnihed", "Begin.");
+ try {
+ Message serviceMsg =
+ Message.obtain(null, ManagerService.MSG_ALL_TESTS_FINISHED);
+ mManagerServiceMessenger.send(serviceMsg);
+ } catch (RemoteException e) {
+ Log.e(LOG_TAG + "::onAllTestsFinished", e.getMessage());
+ }
}
} \ No newline at end of file
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsRunnerThread.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsRunnerThread.java
deleted file mode 100644
index ac814cb..0000000
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsRunnerThread.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-package com.android.dumprendertree2;
-
-import android.content.Intent;
-import android.os.Environment;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.util.Log;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.LinkedList;
-
-/**
- * A Thread that is responsible for finding and loading the tests, starting them and
- * generating summaries. The actual running of the test is delegated to LayoutTestsRunner
- * activity (a UI thread) because of a WebView object that need to be created in UI thread
- * so it can be displayed on the screen. However, the logic for doing this remains in
- * this class (in handler created in constructor).
- */
-public class LayoutTestsRunnerThread extends Thread {
-
- private static final String LOG_TAG = "LayoutTestsRunnerThread";
-
- /** Messages for handler on this thread */
- public static final int MSG_TEST_FINISHED = 0;
-
- /** Messages for our handler running on UI thread */
- public static final int MSG_RUN_TEST = 0;
-
- /** TODO: make it a setting */
- private static final String TESTS_ROOT_DIR_PATH =
- Environment.getExternalStorageDirectory() +
- File.separator + "android" +
- File.separator + "LayoutTests";
-
- /** TODO: make it a setting */
- private static final String RESULTS_ROOT_DIR_PATH =
- Environment.getExternalStorageDirectory() +
- File.separator + "android" +
- File.separator + "LayoutTests-results";
-
- /** TODO: Make it a setting */
- private static final String EXPECTED_RESULT_SECONDARY_LOCATION_RELATIVE_DIR_PREFIX =
- "platform" + File.separator +
- "android-v8" + File.separator;
-
- /** TODO: Make these settings */
- private static final String TEXT_RESULT_EXTENSION = "txt";
- private static final String IMAGE_RESULT_EXTENSION = "png";
-
- /** A list containing relative paths of tests to run */
- private LinkedList<String> mTestsList = new LinkedList<String>();
-
- private FileFilter mFileFilter;
- private Summarizer mSummarizer;
-
- /** Our handler running on this thread. Created in run() method. */
- private Handler mHandler;
-
- /** Our handler running on UI thread. Created in constructor of this thread. */
- private Handler mHandlerOnUiThread;
-
- /**
- * A relative path to the folder with the tests we want to run or particular test.
- * Used up to and including preloadTests().
- */
- private String mRelativePath;
-
- private LayoutTestsRunner mActivity;
-
- private LayoutTest mCurrentTest;
- private String mCurrentTestPath;
- private int mCurrentTestCount = 0;
- private int mTotalTestCount;
-
- /**
- * The given path must be relative to the root dir. The given handler must be
- * able to handle messages that update the display (UI thread).
- *
- * @param path
- * @param uiDisplayHandler
- */
- public LayoutTestsRunnerThread(String path, LayoutTestsRunner activity) {
- mFileFilter = new FileFilter(TESTS_ROOT_DIR_PATH);
- mRelativePath = path;
- mActivity = activity;
-
- /** This creates a handler that runs on the thread that _created_ this thread */
- mHandlerOnUiThread = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_RUN_TEST:
- ((LayoutTest) msg.obj).run();
- break;
- }
- }
- };
- }
-
- @Override
- public void run() {
- Looper.prepare();
-
- mSummarizer = new Summarizer(mFileFilter, RESULTS_ROOT_DIR_PATH);
-
- /** A handler obtained from UI thread to handle messages concerning updating the display */
- final Handler uiDisplayHandler = mActivity.getHandler();
-
- /** Creates a new handler in _this_ thread */
- mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_TEST_FINISHED:
- onTestFinished(mCurrentTest);
- uiDisplayHandler.obtainMessage(LayoutTestsRunner.MSG_UPDATE_PROGRESS,
- mCurrentTestCount, mTotalTestCount).sendToTarget();
- runNextTest();
- break;
- }
- }
- };
-
- /** Check if the path is correct */
- File file = new File(TESTS_ROOT_DIR_PATH, mRelativePath);
- if (!file.exists()) {
- Log.e(LOG_TAG + "::run", "Path does not exist: " + mRelativePath);
- return;
- }
-
- /** Populate the tests' list accordingly */
- if (file.isDirectory()) {
- uiDisplayHandler.sendEmptyMessage(LayoutTestsRunner.MSG_SHOW_PROGRESS_DIALOG);
- preloadTests(mRelativePath);
- uiDisplayHandler.sendEmptyMessage(LayoutTestsRunner.MSG_DISMISS_PROGRESS_DIALOG);
- } else {
- mTestsList.addLast(mRelativePath);
- mTotalTestCount = 1;
- }
-
- /**
- * Instead of running next test here, we send a tests' list to Executer activity.
- * Rest of the code is never executed and will be gradually moved to the service.
- */
- Intent intent = new Intent();
- intent.setClass(mActivity, LayoutTestsExecuter.class);
- intent.setAction(Intent.ACTION_RUN);
- intent.putStringArrayListExtra(LayoutTestsExecuter.EXTRA_TESTS_LIST,
- new ArrayList<String>(mTestsList));
- mActivity.startActivity(intent);
-
- Looper.loop();
- }
-
- /**
- * Loads all the tests from the given folders and all the subfolders
- * into mTestsList.
- *
- * @param dirRelativePath
- */
- private void preloadTests(String dirRelativePath) {
- LinkedList<String> foldersList = new LinkedList<String>();
- foldersList.add(dirRelativePath);
-
- String relativePath;
- String currentDirRelativePath;
- String itemName;
- File[] items;
- while (!foldersList.isEmpty()) {
- currentDirRelativePath = foldersList.removeFirst();
- items = new File(TESTS_ROOT_DIR_PATH, currentDirRelativePath).listFiles();
- for (File item : items) {
- itemName = item.getName();
- relativePath = currentDirRelativePath + File.separator + itemName;
-
- if (item.isDirectory() && FileFilter.isTestDir(itemName)) {
- foldersList.add(relativePath);
- continue;
- }
-
- if (FileFilter.isTestFile(itemName)) {
- if (!mFileFilter.isSkip(relativePath)) {
- mTestsList.addLast(relativePath);
- } else {
- mSummarizer.addSkippedTest(relativePath);
- }
- }
- }
- }
-
- mTotalTestCount = mTestsList.size();
- }
-
- private void runNextTest() {
- if (mTestsList.isEmpty()) {
- onFinishedTests();
- return;
- }
-
- mCurrentTestCount++;
- mCurrentTestPath = mTestsList.removeFirst();
- mCurrentTest = new LayoutTest(mCurrentTestPath, TESTS_ROOT_DIR_PATH,
- mHandler.obtainMessage(MSG_TEST_FINISHED), mActivity);
-
- /**
- * This will run the test on UI thread. The reason why we need to run the test
- * on UI thread is because of the WebView. If we want to display the webview on
- * the screen it needs to be in the UI thread. WebView should be created as
- * part of the LayoutTest.run() method.
- */
- mHandlerOnUiThread.obtainMessage(MSG_RUN_TEST, mCurrentTest).sendToTarget();
- }
-
- private void onTestFinished(LayoutTest test) {
- String testPath = test.getRelativePath();
-
- /** Obtain the result */
- AbstractResult result = test.getResult();
- if (result == null) {
- Log.e(LOG_TAG + "::runTests", testPath + ": result NULL!!");
- return;
- }
-
- dumpResultData(result, testPath);
-
- mSummarizer.appendTest(test);
- }
-
- private void dumpResultData(AbstractResult result, String testPath) {
- dumpActualTextResult(result, testPath);
- dumpActualImageResult(result, testPath);
- }
-
- private void dumpActualTextResult(AbstractResult result, String testPath) {
- String actualTextResult = result.getActualTextResult();
- if (actualTextResult == null) {
- return;
- }
-
- String resultPath = FileFilter.setPathEnding(testPath, "-actual." + TEXT_RESULT_EXTENSION);
- FsUtils.writeDataToStorage(new File(RESULTS_ROOT_DIR_PATH, resultPath),
- actualTextResult.getBytes(), false);
- }
-
- private void dumpActualImageResult(AbstractResult result, String testPath) {
- byte[] actualImageResult = result.getActualImageResult();
- if (actualImageResult == null) {
- return;
- }
-
- String resultPath = FileFilter.setPathEnding(testPath, "-actual." + IMAGE_RESULT_EXTENSION);
- FsUtils.writeDataToStorage(new File(RESULTS_ROOT_DIR_PATH, resultPath),
- actualImageResult, false);
- }
-
- private void onFinishedTests() {
- Log.d(LOG_TAG + "::onFinishedTests", "Begin.");
- Looper.myLooper().quit();
- mSummarizer.summarize();
- /** TODO: Present some kind of notification to the user that
- * allows to chose next action, e.g:
- * - go to html view of results
- * - zip results
- * - run more tests before zipping */
- }
-
- public static String getExpectedTextResult(String relativePath) {
- return new String(getExpectedResult(relativePath, TEXT_RESULT_EXTENSION));
- }
-
- public static byte[] getExpectedImageResult(String relativePath) {
- return getExpectedResult(relativePath, IMAGE_RESULT_EXTENSION);
- }
-
- private static byte[] getExpectedResult(String relativePath, String extension) {
- relativePath = FileFilter.setPathEnding(relativePath, "-expected." + extension);
-
- byte[] bytes = FsUtils.readDataFromStorage(new File(TESTS_ROOT_DIR_PATH, relativePath));
- if (bytes == null) {
- relativePath = EXPECTED_RESULT_SECONDARY_LOCATION_RELATIVE_DIR_PREFIX + relativePath;
- bytes = FsUtils.readDataFromStorage(new File(TESTS_ROOT_DIR_PATH, relativePath));
- }
-
- return bytes;
- }
-} \ No newline at end of file
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/ManagerService.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/ManagerService.java
index e452a38..e32247c 100644
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/ManagerService.java
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/ManagerService.java
@@ -18,12 +18,16 @@ package com.android.dumprendertree2;
import android.app.Service;
import android.content.Intent;
+import android.os.Bundle;
+import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
+import java.io.File;
+
/**
* A service that handles managing the results of tests, informing of crashes, generating
* summaries, etc.
@@ -32,7 +36,29 @@ public class ManagerService extends Service {
private static final String LOG_TAG = "ManagerService";
+ /** TODO: make it a setting */
+ static final String TESTS_ROOT_DIR_PATH =
+ Environment.getExternalStorageDirectory() +
+ File.separator + "android" +
+ File.separator + "LayoutTests";
+
+ /** TODO: make it a setting */
+ static final String RESULTS_ROOT_DIR_PATH =
+ Environment.getExternalStorageDirectory() +
+ File.separator + "android" +
+ File.separator + "LayoutTests-results";
+
+ /** TODO: Make it a setting */
+ private static final String EXPECTED_RESULT_SECONDARY_LOCATION_RELATIVE_DIR_PREFIX =
+ "platform" + File.separator +
+ "android-v8" + File.separator;
+
+ /** TODO: Make these settings */
+ private static final String TEXT_RESULT_EXTENSION = "txt";
+ private static final String IMAGE_RESULT_EXTENSION = "png";
+
static final int MSG_PROCESS_ACTUAL_RESULTS = 0;
+ static final int MSG_ALL_TESTS_FINISHED = 1;
private Handler mIncomingHandler = new Handler() {
@Override
@@ -40,6 +66,11 @@ public class ManagerService extends Service {
switch (msg.what) {
case MSG_PROCESS_ACTUAL_RESULTS:
Log.d(LOG_TAG + ".mIncomingHandler", msg.getData().getString("relativePath"));
+ onActualResultsObtained(msg.getData());
+ break;
+
+ case MSG_ALL_TESTS_FINISHED:
+ mSummarizer.summarize();
break;
}
}
@@ -47,14 +78,76 @@ public class ManagerService extends Service {
private Messenger mMessenger = new Messenger(mIncomingHandler);
+ private FileFilter mFileFilter;
+ private Summarizer mSummarizer;
+
@Override
public void onCreate() {
super.onCreate();
- /** TODO: */
+
+ mFileFilter = new FileFilter(TESTS_ROOT_DIR_PATH);
+ mSummarizer = new Summarizer(mFileFilter, RESULTS_ROOT_DIR_PATH);
}
@Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
+
+ private void onActualResultsObtained(Bundle bundle) {
+ AbstractResult results =
+ AbstractResult.TestType.valueOf(bundle.getString("type")).createResult(bundle);
+ String relativePath = results.getRelativePath();
+ results.setExpectedTextResult(getExpectedTextResult(relativePath));
+ results.setExpectedImageResult(getExpectedImageResult(relativePath));
+
+ dumpActualTextResult(results);
+ dumpActualImageResult(results);
+
+ mSummarizer.appendTest(results);
+ }
+
+ private void dumpActualTextResult(AbstractResult result) {
+ String testPath = result.getRelativePath();
+ String actualTextResult = result.getActualTextResult();
+ if (actualTextResult == null) {
+ return;
+ }
+
+ String resultPath = FileFilter.setPathEnding(testPath, "-actual." + TEXT_RESULT_EXTENSION);
+ FsUtils.writeDataToStorage(new File(RESULTS_ROOT_DIR_PATH, resultPath),
+ actualTextResult.getBytes(), false);
+ }
+
+ private void dumpActualImageResult(AbstractResult result) {
+ String testPath = result.getRelativePath();
+ byte[] actualImageResult = result.getActualImageResult();
+ if (actualImageResult == null) {
+ return;
+ }
+
+ String resultPath = FileFilter.setPathEnding(testPath, "-actual." + IMAGE_RESULT_EXTENSION);
+ FsUtils.writeDataToStorage(new File(RESULTS_ROOT_DIR_PATH, resultPath),
+ actualImageResult, false);
+ }
+
+ public static String getExpectedTextResult(String relativePath) {
+ return new String(getExpectedResult(relativePath, TEXT_RESULT_EXTENSION));
+ }
+
+ public static byte[] getExpectedImageResult(String relativePath) {
+ return getExpectedResult(relativePath, IMAGE_RESULT_EXTENSION);
+ }
+
+ private static byte[] getExpectedResult(String relativePath, String extension) {
+ relativePath = FileFilter.setPathEnding(relativePath, "-expected." + extension);
+
+ byte[] bytes = FsUtils.readDataFromStorage(new File(TESTS_ROOT_DIR_PATH, relativePath));
+ if (bytes == null) {
+ relativePath = EXPECTED_RESULT_SECONDARY_LOCATION_RELATIVE_DIR_PREFIX + relativePath;
+ bytes = FsUtils.readDataFromStorage(new File(TESTS_ROOT_DIR_PATH, relativePath));
+ }
+
+ return bytes;
+ }
} \ No newline at end of file
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/Summarizer.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/Summarizer.java
index 4d15bb5..36cde86 100644
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/Summarizer.java
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/Summarizer.java
@@ -16,8 +16,6 @@
package com.android.dumprendertree2;
-import android.util.Log;
-
import java.io.File;
import java.util.EnumMap;
import java.util.HashSet;
@@ -155,15 +153,8 @@ public class Summarizer {
mSkippedTestsList.addLast(relativePath);
}
- public void appendTest(LayoutTest test) {
- String testPath = test.getRelativePath();
-
- /** Obtain the result */
- AbstractResult result = test.getResult();
- if (result == null) {
- Log.e(LOG_TAG + "::appendTest", testPath + ": result NULL!!");
- return;
- }
+ public void appendTest(AbstractResult result) {
+ String testPath = result.getRelativePath();
AbstractResult.ResultCode resultCode = result.getResultCode();
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsRunner.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/TestsListActivity.java
index 4421aba..a402ae1 100644
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/LayoutTestsRunner.java
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/TestsListActivity.java
@@ -24,18 +24,16 @@ import android.os.Handler;
import android.os.Message;
import android.view.Window;
+import java.util.ArrayList;
+
/**
- * An Activity that is responsible only for updating the UI features, like titles, progress bars,
- * etc.
- *
- * <p>Also, the webview form the test must be running in this activity's thread if we want
- * to be able to display it on the screen.
+ * An Activity that generates a list of tests and sends the intent to
+ * LayoutTestsExecuter to run them. It also restarts the LayoutTestsExecuter
+ * after it crashes (TODO).
*/
-public class LayoutTestsRunner extends Activity {
+public class TestsListActivity extends Activity {
- public static final int MSG_UPDATE_PROGRESS = 1;
- public static final int MSG_SHOW_PROGRESS_DIALOG = 2;
- public static final int MSG_DISMISS_PROGRESS_DIALOG = 3;
+ private static final int MSG_TEST_LIST_PRELOADER_DONE = 0;
/** Constants for adding extras to an intent */
public static final String EXTRA_TEST_PATH = "TestPath";
@@ -46,31 +44,25 @@ public class LayoutTestsRunner extends Activity {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
- case MSG_UPDATE_PROGRESS:
- int i = msg.arg1;
- int size = msg.arg2;
- getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
- i * Window.PROGRESS_END / size);
- setTitle(i * 100 / size + "% (" + i + "/" + size + ")");
- break;
-
- case MSG_SHOW_PROGRESS_DIALOG:
- sProgressDialog.show();
- break;
-
- case MSG_DISMISS_PROGRESS_DIALOG:
+ case MSG_TEST_LIST_PRELOADER_DONE:
sProgressDialog.dismiss();
+ mTestsList = (ArrayList<String>)msg.obj;
+ mTotalTestCount = mTestsList.size();
+ restartExecutor(0);
break;
}
}
};
+ private ArrayList<String> mTestsList;
+ private int mTotalTestCount;
+
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Prepare the progress dialog */
- sProgressDialog = new ProgressDialog(LayoutTestsRunner.this);
+ sProgressDialog = new ProgressDialog(TestsListActivity.this);
sProgressDialog.setCancelable(false);
sProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
sProgressDialog.setTitle(R.string.dialog_progress_title);
@@ -78,17 +70,32 @@ public class LayoutTestsRunner extends Activity {
requestWindowFeature(Window.FEATURE_PROGRESS);
- /** Execute the intent */
Intent intent = getIntent();
if (!intent.getAction().equals(Intent.ACTION_RUN)) {
return;
}
String path = intent.getStringExtra(EXTRA_TEST_PATH);
- new LayoutTestsRunnerThread(path, this).start();
+ sProgressDialog.show();
+ Message doneMsg = Message.obtain(mHandler, MSG_TEST_LIST_PRELOADER_DONE);
+
+ new TestsListPreloaderThread(path, doneMsg).start();
}
- public Handler getHandler() {
- return mHandler;
+ /**
+ * (Re)starts the executer activity from the given test number (inclusive, 0-based).
+ * This number is an index in mTestsList, not the sublist passed in the intent.
+ *
+ * @param startFrom
+ * test index in mTestsList to start the tests from (inclusive, 0-based)
+ */
+ private void restartExecutor(int startFrom) {
+ Intent intent = new Intent();
+ intent.setClass(this, LayoutTestsExecutor.class);
+ intent.setAction(Intent.ACTION_RUN);
+ intent.putStringArrayListExtra(LayoutTestsExecutor.EXTRA_TESTS_LIST,
+ new ArrayList<String>(mTestsList.subList(startFrom, mTotalTestCount)));
+ intent.putExtra(LayoutTestsExecutor.EXTRA_TEST_INDEX, startFrom);
+ startActivity(intent);
}
} \ No newline at end of file
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/TestsListPreloaderThread.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/TestsListPreloaderThread.java
new file mode 100644
index 0000000..f76105d
--- /dev/null
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/TestsListPreloaderThread.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2010 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.
+ */
+
+package com.android.dumprendertree2;
+
+import android.os.Environment;
+import android.os.Message;
+import android.util.Log;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.LinkedList;
+
+/**
+ * A Thread that is responsible for generating a lists of tests to run.
+ */
+public class TestsListPreloaderThread extends Thread {
+
+ private static final String LOG_TAG = "TestsListPreloaderThread";
+
+ /** TODO: make it a setting */
+ private static final String TESTS_ROOT_DIR_PATH =
+ Environment.getExternalStorageDirectory() +
+ File.separator + "android" +
+ File.separator + "LayoutTests";
+
+ /** A list containing relative paths of tests to run */
+ private ArrayList<String> mTestsList = new ArrayList<String>();
+
+ private FileFilter mFileFilter;
+
+ /**
+ * A relative path to the folder with the tests we want to run or particular test.
+ * Used up to and including preloadTests().
+ */
+ private String mRelativePath;
+
+ private Message mDoneMsg;
+
+ /**
+ * The given path must be relative to the root dir.
+ *
+ * @param path
+ * @param doneMsg
+ */
+ public TestsListPreloaderThread(String path, Message doneMsg) {
+ mFileFilter = new FileFilter(TESTS_ROOT_DIR_PATH);
+ mRelativePath = path;
+ mDoneMsg = doneMsg;
+ }
+
+ @Override
+ public void run() {
+ /** Check if the path is correct */
+ File file = new File(TESTS_ROOT_DIR_PATH, mRelativePath);
+ if (!file.exists()) {
+ Log.e(LOG_TAG + "::run", "Path does not exist: " + mRelativePath);
+ return;
+ }
+
+ /** Populate the tests' list accordingly */
+ if (file.isDirectory()) {
+ preloadTests(mRelativePath);
+ } else {
+ mTestsList.add(mRelativePath);
+ }
+ mDoneMsg.obj = mTestsList;
+ mDoneMsg.sendToTarget();
+ }
+
+ /**
+ * Loads all the tests from the given folders and all the subfolders
+ * into mTestsList.
+ *
+ * @param dirRelativePath
+ */
+ private void preloadTests(String dirRelativePath) {
+ LinkedList<String> foldersList = new LinkedList<String>();
+ foldersList.add(dirRelativePath);
+
+ String relativePath;
+ String currentDirRelativePath;
+ String itemName;
+ File[] items;
+ while (!foldersList.isEmpty()) {
+ currentDirRelativePath = foldersList.removeFirst();
+ items = new File(TESTS_ROOT_DIR_PATH, currentDirRelativePath).listFiles();
+ for (File item : items) {
+ itemName = item.getName();
+ relativePath = currentDirRelativePath + File.separator + itemName;
+
+ if (item.isDirectory() && FileFilter.isTestDir(itemName)) {
+ foldersList.add(relativePath);
+ continue;
+ }
+
+ if (FileFilter.isTestFile(itemName)) {
+ if (!mFileFilter.isSkip(relativePath)) {
+ mTestsList.add(relativePath);
+ } else {
+ //mSummarizer.addSkippedTest(relativePath);
+ /** TODO: Summarizer is now in service - figure out how to send the info */
+ }
+ }
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/TextResult.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/TextResult.java
index 7bab4ae..33ee4c7 100644
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/TextResult.java
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/TextResult.java
@@ -61,7 +61,10 @@ public class TextResult extends AbstractResult {
mExpectedResult = bundle.getString("expectedTextualResult");
mActualResult = bundle.getString("actualTextualResult");
mRelativePath = bundle.getString("relativePath");
- mResultCode = ResultCode.valueOf(bundle.getString("resultCode"));
+ String resultCode = bundle.getString("resultCode");
+ if (resultCode != null) {
+ mResultCode = ResultCode.valueOf(resultCode);
+ }
}
@Override
@@ -177,4 +180,9 @@ public class TextResult extends AbstractResult {
bundle.putString("type", getType().name());
return bundle;
}
+
+ @Override
+ public String getRelativePath() {
+ return mRelativePath;
+ }
} \ No newline at end of file
diff --git a/tests/DumpRenderTree2/src/com/android/dumprendertree2/ui/DirListActivity.java b/tests/DumpRenderTree2/src/com/android/dumprendertree2/ui/DirListActivity.java
index 790d1d3..661a8ec 100644
--- a/tests/DumpRenderTree2/src/com/android/dumprendertree2/ui/DirListActivity.java
+++ b/tests/DumpRenderTree2/src/com/android/dumprendertree2/ui/DirListActivity.java
@@ -17,7 +17,7 @@
package com.android.dumprendertree2.ui;
import com.android.dumprendertree2.FileFilter;
-import com.android.dumprendertree2.LayoutTestsRunner;
+import com.android.dumprendertree2.TestsListActivity;
import com.android.dumprendertree2.R;
import android.app.Activity;
@@ -203,9 +203,9 @@ public class DirListActivity extends ListActivity {
} else {
/** Run the test */
Intent intent = new Intent();
- intent.setClass(DirListActivity.this, LayoutTestsRunner.class);
+ intent.setClass(DirListActivity.this, TestsListActivity.class);
intent.setAction(Intent.ACTION_RUN);
- intent.putExtra(LayoutTestsRunner.EXTRA_TEST_PATH, item.getRelativePath());
+ intent.putExtra(TestsListActivity.EXTRA_TEST_PATH, item.getRelativePath());
startActivity(intent);
}
}
@@ -277,9 +277,9 @@ public class DirListActivity extends ListActivity {
removeDialog(DIALOG_RUN_ABORT_DIR);
/** Run the tests */
Intent intent = new Intent();
- intent.setClass(DirListActivity.this, LayoutTestsRunner.class);
+ intent.setClass(DirListActivity.this, TestsListActivity.class);
intent.setAction(Intent.ACTION_RUN);
- intent.putExtra(LayoutTestsRunner.EXTRA_TEST_PATH,
+ intent.putExtra(TestsListActivity.EXTRA_TEST_PATH,
args.getString("relativePath"));
startActivity(intent);
}
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
index 4a22b68..6fac902 100644
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ b/wifi/java/android/net/wifi/WifiManager.java
@@ -165,7 +165,7 @@ public class WifiManager {
*
* @hide
*/
- public static final int WIFI_AP_STATE_DISABLING = 0;
+ public static final int WIFI_AP_STATE_DISABLING = 10;
/**
* Wi-Fi AP is disabled.
*
@@ -174,7 +174,7 @@ public class WifiManager {
*
* @hide
*/
- public static final int WIFI_AP_STATE_DISABLED = 1;
+ public static final int WIFI_AP_STATE_DISABLED = 11;
/**
* Wi-Fi AP is currently being enabled. The state will change to
* {@link #WIFI_AP_STATE_ENABLED} if it finishes successfully.
@@ -184,7 +184,7 @@ public class WifiManager {
*
* @hide
*/
- public static final int WIFI_AP_STATE_ENABLING = 2;
+ public static final int WIFI_AP_STATE_ENABLING = 12;
/**
* Wi-Fi AP is enabled.
*
@@ -193,7 +193,7 @@ public class WifiManager {
*
* @hide
*/
- public static final int WIFI_AP_STATE_ENABLED = 3;
+ public static final int WIFI_AP_STATE_ENABLED = 13;
/**
* Wi-Fi AP is in a failed state. This state will occur when an error occurs during
* enabling or disabling
@@ -203,7 +203,7 @@ public class WifiManager {
*
* @hide
*/
- public static final int WIFI_AP_STATE_FAILED = 4;
+ public static final int WIFI_AP_STATE_FAILED = 14;
/**
* Broadcast intent action indicating that a connection to the supplicant has
diff --git a/wifi/java/android/net/wifi/WifiMonitor.java b/wifi/java/android/net/wifi/WifiMonitor.java
index 266d801..f2f8343 100644
--- a/wifi/java/android/net/wifi/WifiMonitor.java
+++ b/wifi/java/android/net/wifi/WifiMonitor.java
@@ -155,7 +155,7 @@ public class WifiMonitor {
public MonitorThread() {
super("WifiMonitor");
}
-
+
public void run() {
if (connectToSupplicant()) {
@@ -272,7 +272,7 @@ public class WifiMonitor {
int connectTries = 0;
while (true) {
- if (mWifiStateTracker.connectToSupplicant()) {
+ if (WifiNative.connectToSupplicant()) {
return true;
}
if (connectTries++ < 3) {
@@ -375,7 +375,7 @@ public class WifiMonitor {
if (newSupplicantState == SupplicantState.INVALID) {
Log.w(TAG, "Invalid supplicant state: " + newState);
}
- mWifiStateTracker.notifyStateChange(networkId, BSSID, newSupplicantState);
+ mWifiStateTracker.notifySupplicantStateChange(networkId, BSSID, newSupplicantState);
}
}
@@ -395,7 +395,7 @@ public class WifiMonitor {
}
}
}
- mWifiStateTracker.notifyStateChange(newState, BSSID, networkId);
+ mWifiStateTracker.notifyNetworkStateChange(newState, BSSID, networkId);
}
/**
diff --git a/wifi/java/android/net/wifi/WifiNative.java b/wifi/java/android/net/wifi/WifiNative.java
index 7a3282c..47f8813 100644
--- a/wifi/java/android/net/wifi/WifiNative.java
+++ b/wifi/java/android/net/wifi/WifiNative.java
@@ -41,6 +41,8 @@ public class WifiNative {
public native static String getErrorString(int errorCode);
public native static boolean loadDriver();
+
+ public native static boolean isDriverLoaded();
public native static boolean unloadDriver();
diff --git a/wifi/java/android/net/wifi/WifiStateTracker.java b/wifi/java/android/net/wifi/WifiStateTracker.java
index 5780a04..96f0354 100644
--- a/wifi/java/android/net/wifi/WifiStateTracker.java
+++ b/wifi/java/android/net/wifi/WifiStateTracker.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2010 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.
@@ -22,6 +22,21 @@ import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
+/**
+ * TODO: Add soft AP states as part of WIFI_STATE_XXX
+ * Retain WIFI_STATE_ENABLING that indicates driver is loading
+ * Add WIFI_STATE_AP_ENABLED to indicate soft AP has started
+ * and WIFI_STATE_FAILED for failure
+ * Deprecate WIFI_STATE_UNKNOWN
+ *
+ * Doing this will simplify the logic for sending broadcasts
+ */
+import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
+import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
+import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
+import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING;
+import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
+
import android.app.ActivityManagerNative;
import android.net.NetworkInfo;
import android.net.NetworkStateTracker;
@@ -31,21 +46,25 @@ import android.net.ConnectivityManager;
import android.net.NetworkInfo.DetailedState;
import android.net.NetworkInfo.State;
import android.net.NetworkProperties;
+import android.os.Binder;
import android.os.Message;
import android.os.Parcelable;
import android.os.Handler;
-import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.INetworkManagementService;
+import android.os.PowerManager;
import android.os.SystemProperties;
-import android.os.Looper;
import android.os.RemoteException;
import android.os.ServiceManager;
+import android.os.Process;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
-import android.util.Config;
+import android.util.Slog;
import android.app.Notification;
import android.app.PendingIntent;
+import android.app.backup.IBackupManager;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothA2dp;
@@ -54,15 +73,22 @@ import android.content.Intent;
import android.content.Context;
import android.database.ContentObserver;
import com.android.internal.app.IBatteryStats;
+import com.android.internal.util.HierarchicalState;
+import com.android.internal.util.HierarchicalStateMachine;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.LinkedHashMap;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Pattern;
/**
* Track the state of Wifi connectivity. All event handling is done here,
@@ -70,165 +96,61 @@ import java.util.concurrent.atomic.AtomicInteger;
*
* @hide
*/
-public class WifiStateTracker extends Handler implements NetworkStateTracker {
+//TODO: we still need frequent scanning for the case when
+// we issue disconnect but need scan results for open network notification
+public class WifiStateTracker extends HierarchicalStateMachine implements NetworkStateTracker {
- private static final boolean LOCAL_LOGD = Config.LOGD || false;
-
private static final String TAG = "WifiStateTracker";
+ private static final String NETWORKTYPE = "WIFI";
+ private static final boolean DBG = false;
- // Event log tags (must be in sync with event-log-tags)
- private static final int EVENTLOG_NETWORK_STATE_CHANGED = 50021;
- private static final int EVENTLOG_SUPPLICANT_STATE_CHANGED = 50022;
- private static final int EVENTLOG_DRIVER_STATE_CHANGED = 50023;
- private static final int EVENTLOG_INTERFACE_CONFIGURATION_STATE_CHANGED = 50024;
- private static final int EVENTLOG_SUPPLICANT_CONNECTION_STATE_CHANGED = 50025;
-
- // Event codes
- private static final int EVENT_SUPPLICANT_CONNECTION = 1;
- private static final int EVENT_SUPPLICANT_DISCONNECT = 2;
- private static final int EVENT_SUPPLICANT_STATE_CHANGED = 3;
- private static final int EVENT_NETWORK_STATE_CHANGED = 4;
- private static final int EVENT_SCAN_RESULTS_AVAILABLE = 5;
- private static final int EVENT_INTERFACE_CONFIGURATION_SUCCEEDED = 6;
- private static final int EVENT_INTERFACE_CONFIGURATION_FAILED = 7;
- private static final int EVENT_POLL_INTERVAL = 8;
- private static final int EVENT_DHCP_START = 9;
- private static final int EVENT_DEFERRED_DISCONNECT = 10;
- private static final int EVENT_DEFERRED_RECONNECT = 11;
- /**
- * The driver is started or stopped. The object will be the state: true for
- * started, false for stopped.
- */
- private static final int EVENT_DRIVER_STATE_CHANGED = 12;
- private static final int EVENT_PASSWORD_KEY_MAY_BE_INCORRECT = 13;
- private static final int EVENT_MAYBE_START_SCAN_POST_DISCONNECT = 14;
-
- /**
- * The driver state indication.
- */
- private static final int DRIVER_STARTED = 0;
- private static final int DRIVER_STOPPED = 1;
- private static final int DRIVER_HUNG = 2;
-
- /**
- * Interval in milliseconds between polling for connection
- * status items that are not sent via asynchronous events.
- * An example is RSSI (signal strength).
- */
- private static final int POLL_STATUS_INTERVAL_MSECS = 3000;
-
- /**
- * The max number of the WPA supplicant loop iterations before we
- * decide that the loop should be terminated:
- */
- private static final int MAX_SUPPLICANT_LOOP_ITERATIONS = 4;
-
- /**
- * When a DISCONNECT event is received, we defer handling it to
- * allow for the possibility that the DISCONNECT is about to
- * be followed shortly by a CONNECT to the same network we were
- * just connected to. In such a case, we don't want to report
- * the network as down, nor do we want to reconfigure the network
- * interface, etc. If we get a CONNECT event for another network
- * within the delay window, we immediately handle the pending
- * disconnect before processing the CONNECT.<p/>
- * The five second delay is chosen somewhat arbitrarily, but is
- * meant to cover most of the cases where a DISCONNECT/CONNECT
- * happens to a network.
- */
- private static final int DISCONNECT_DELAY_MSECS = 5000;
- /**
- * When the supplicant goes idle after we do an explicit disconnect
- * following a DHCP failure, we need to kick the supplicant into
- * trying to associate with access points.
- */
- private static final int RECONNECT_DELAY_MSECS = 2000;
-
- /**
- * When the supplicant disconnects from an AP it sometimes forgets
- * to restart scanning. Wait this delay before asking it to start
- * scanning (in case it forgot). 15 sec is the standard delay between
- * scans.
- */
- private static final int KICKSTART_SCANNING_DELAY_MSECS = 15000;
+ /* TODO: fetch a configurable interface */
+ private static final String SOFTAP_IFACE = "wl0.1";
- /**
- * The maximum number of times we will retry a connection to an access point
- * for which we have failed in acquiring an IP address from DHCP. A value of
- * N means that we will make N+1 connection attempts in all.
- * <p>
- * See {@link Settings.Secure#WIFI_MAX_DHCP_RETRY_COUNT}. This is the default
- * value if a Settings value is not present.
- */
- private static final int DEFAULT_MAX_DHCP_RETRIES = 9;
-
- private static final int DRIVER_POWER_MODE_AUTO = 0;
- private static final int DRIVER_POWER_MODE_ACTIVE = 1;
+ private WifiMonitor mWifiMonitor;
+ private INetworkManagementService nwService;
+ private ConnectivityManager mCm;
- /**
- * The current WPA supplicant loop state (used to detect looping behavior):
- */
- private SupplicantState mSupplicantLoopState = SupplicantState.DISCONNECTED;
+ /* Scan results handling */
+ private List<ScanResult> mScanResults;
+ private static final Pattern scanResultPattern = Pattern.compile("\t+");
+ private static final int SCAN_RESULT_CACHE_SIZE = 80;
+ private final LinkedHashMap<String, ScanResult> mScanResultCache;
- /**
- * The current number of WPA supplicant loop iterations:
- */
- private int mNumSupplicantLoopIterations = 0;
+ private String mInterfaceName;
+ private AtomicBoolean mTeardownRequested = new AtomicBoolean(false);
+ private AtomicBoolean mPrivateDnsRouteSet = new AtomicBoolean(false);
+ private AtomicInteger mDefaultGatewayAddr = new AtomicInteger(0);
+ private AtomicBoolean mDefaultRouteSet = new AtomicBoolean(false);
- /**
- * The current number of supplicant state changes. This is used to determine
- * if we've received any new info since we found out it was DISCONNECTED or
- * INACTIVE. If we haven't for X ms, we then request a scan - it should have
- * done that automatically, but sometimes some firmware does not.
- */
- private int mNumSupplicantStateChanges = 0;
+ private int mNumAllowedChannels = 0;
+ private int mLastSignalLevel = -1;
+ private String mLastBssid;
+ private int mLastNetworkId;
+ private boolean mEnableRssiPolling = false;
+ private boolean mPasswordKeyMayBeIncorrect = false;
+ private boolean mUseStaticIp = false;
+ private int mReconnectCount = 0;
+ private boolean mIsScanMode = false;
/**
- * True if we received an event that that a password-key may be incorrect.
- * If the next incoming supplicant state change event is DISCONNECT,
- * broadcast a message that we have a possible password error and disable
- * the network.
+ * Instance of the bluetooth headset helper. This needs to be created
+ * early because there is a delay before it actually 'connects', as
+ * noted by its javadoc. If we check before it is connected, it will be
+ * in an error state and we will not disable coexistence.
*/
- private boolean mPasswordKeyMayBeIncorrect = false;
+ private BluetoothHeadset mBluetoothHeadset;
- public static final int SUPPL_SCAN_HANDLING_NORMAL = 1;
- public static final int SUPPL_SCAN_HANDLING_LIST_ONLY = 2;
+ private BluetoothA2dp mBluetoothA2dp;
- private WifiMonitor mWifiMonitor;
- private WifiInfo mWifiInfo;
- private List<ScanResult> mScanResults;
- private WifiManager mWM;
- private boolean mHaveIpAddress;
- private boolean mObtainingIpAddress;
- private boolean mTornDownByConnMgr;
- private NetworkInfo mNetworkInfo;
- private boolean mTeardownRequested = false;
- /**
- * A DISCONNECT event has been received, but processing it
- * is being deferred.
- */
- private boolean mDisconnectPending;
/**
- * An operation has been performed as a result of which we expect the next event
- * will be a DISCONNECT.
+ * Observes the static IP address settings.
*/
- private boolean mDisconnectExpected;
- private DhcpHandler mDhcpTarget;
- private DhcpInfo mDhcpInfo;
+ private SettingsObserver mSettingsObserver;
private NetworkProperties mNetworkProperties;
- private int mLastSignalLevel = -1;
- private String mLastBssid;
- private String mLastSsid;
- private int mLastNetworkId = -1;
- private boolean mUseStaticIp = false;
- private int mReconnectCount;
- // used to store the (non-persisted) num determined during device boot
- // (from mcc or other phone info) before the driver is started.
- private int mNumAllowedChannels = 0;
// Variables relating to the 'available networks' notification
-
/**
* The icon to show in the 'available networks' notification. This will also
* be the ID of the Notification given to the NotificationManager.
@@ -276,13 +198,230 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* something other than scanning, we reset this to 0.
*/
private int mNumScansSinceNetworkStateChange;
+
+ // Held during driver load and unload
+ private static PowerManager.WakeLock sWakeLock;
+
+ /* For sending events to connectivity service handler */
+ private Handler mCsHandler;
+ private Context mContext;
+
+ private DhcpInfo mDhcpInfo;
+ private WifiInfo mWifiInfo;
+ private NetworkInfo mNetworkInfo;
+ private SupplicantStateTracker mSupplicantStateTracker;
+
+ // Event log tags (must be in sync with event-log-tags)
+ private static final int EVENTLOG_WIFI_STATE_CHANGED = 50021;
+ private static final int EVENTLOG_WIFI_EVENT_HANDLED = 50022;
+ private static final int EVENTLOG_SUPPLICANT_STATE_CHANGED = 50023;
+
+ /* Load the driver */
+ private static final int CMD_LOAD_DRIVER = 1;
+ /* Unload the driver */
+ private static final int CMD_UNLOAD_DRIVER = 2;
+ /* Indicates driver load succeeded */
+ private static final int CMD_LOAD_DRIVER_SUCCESS = 3;
+ /* Indicates driver load failed */
+ private static final int CMD_LOAD_DRIVER_FAILURE = 4;
+ /* Indicates driver unload succeeded */
+ private static final int CMD_UNLOAD_DRIVER_SUCCESS = 5;
+ /* Indicates driver unload failed */
+ private static final int CMD_UNLOAD_DRIVER_FAILURE = 6;
+
+ /* Start the supplicant */
+ private static final int CMD_START_SUPPLICANT = 11;
+ /* Stop the supplicant */
+ private static final int CMD_STOP_SUPPLICANT = 12;
+ /* Start the driver */
+ private static final int CMD_START_DRIVER = 13;
+ /* Start the driver */
+ private static final int CMD_STOP_DRIVER = 14;
+ /* Indicates DHCP succeded */
+ private static final int CMD_IP_CONFIG_SUCCESS = 15;
+ /* Indicates DHCP failed */
+ private static final int CMD_IP_CONFIG_FAILURE = 16;
+ /* Re-configure interface */
+ private static final int CMD_RECONFIGURE_IP = 17;
+
+
+ /* Start the soft access point */
+ private static final int CMD_START_AP = 21;
+ /* Stop the soft access point */
+ private static final int CMD_STOP_AP = 22;
+
+
+ /* Supplicant events */
+ /* Connection to supplicant established */
+ private static final int SUP_CONNECTION_EVENT = 31;
+ /* Connection to supplicant lost */
+ private static final int SUP_DISCONNECTION_EVENT = 32;
+ /* Driver start completed */
+ private static final int DRIVER_START_EVENT = 33;
+ /* Driver stop completed */
+ private static final int DRIVER_STOP_EVENT = 34;
+ /* Network connection completed */
+ private static final int NETWORK_CONNECTION_EVENT = 36;
+ /* Network disconnection completed */
+ private static final int NETWORK_DISCONNECTION_EVENT = 37;
+ /* Scan results are available */
+ private static final int SCAN_RESULTS_EVENT = 38;
+ /* Supplicate state changed */
+ private static final int SUPPLICANT_STATE_CHANGE_EVENT = 39;
+ /* Password may be incorrect */
+ private static final int PASSWORD_MAY_BE_INCORRECT_EVENT = 40;
+
+ /* Supplicant commands */
+ /* Is supplicant alive ? */
+ private static final int CMD_PING_SUPPLICANT = 51;
+ /* Add/update a network configuration */
+ private static final int CMD_ADD_OR_UPDATE_NETWORK = 52;
+ /* Delete a network */
+ private static final int CMD_REMOVE_NETWORK = 53;
+ /* Enable a network. The device will attempt a connection to the given network. */
+ private static final int CMD_ENABLE_NETWORK = 54;
+ /* Disable a network. The device does not attempt a connection to the given network. */
+ private static final int CMD_DISABLE_NETWORK = 55;
+ /* Blacklist network. De-prioritizes the given BSSID for connection. */
+ private static final int CMD_BLACKLIST_NETWORK = 56;
+ /* Clear the blacklist network list */
+ private static final int CMD_CLEAR_BLACKLIST = 57;
+ /* Get the configured networks */
+ private static final int CMD_GET_NETWORK_CONFIG = 58;
+ /* Save configuration */
+ private static final int CMD_SAVE_CONFIG = 59;
+ /* Connection status */
+ private static final int CMD_CONNECTION_STATUS = 60;
+
+ /* Supplicant commands after driver start*/
+ /* Initiate a scan */
+ private static final int CMD_START_SCAN = 71;
+ /* Set scan mode. CONNECT_MODE or SCAN_ONLY_MODE */
+ private static final int CMD_SET_SCAN_MODE = 72;
+ /* Set scan type. SCAN_ACTIVE or SCAN_PASSIVE */
+ private static final int CMD_SET_SCAN_TYPE = 73;
+ /* Disconnect from a network */
+ private static final int CMD_DISCONNECT = 74;
+ /* Reconnect to a network */
+ private static final int CMD_RECONNECT = 75;
+ /* Reassociate to a network */
+ private static final int CMD_REASSOCIATE = 76;
+ /* Set power mode
+ * POWER_MODE_ACTIVE
+ * POWER_MODE_AUTO
+ */
+ private static final int CMD_SET_POWER_MODE = 77;
+ /* Set bluetooth co-existence
+ * BLUETOOTH_COEXISTENCE_MODE_ENABLED
+ * BLUETOOTH_COEXISTENCE_MODE_DISABLED
+ * BLUETOOTH_COEXISTENCE_MODE_SENSE
+ */
+ private static final int CMD_SET_BLUETOOTH_COEXISTENCE = 78;
+ /* Enable/disable bluetooth scan mode
+ * true(1)
+ * false(0)
+ */
+ private static final int CMD_SET_BLUETOOTH_SCAN_MODE = 79;
+ /* Set number of allowed channels */
+ private static final int CMD_SET_NUM_ALLOWED_CHANNELS = 80;
+ /* Request connectivity manager wake lock before driver stop */
+ private static final int CMD_REQUEST_CM_WAKELOCK = 81;
+ /* Enables RSSI poll */
+ private static final int CMD_ENABLE_RSSI_POLL = 82;
+ /* RSSI poll */
+ private static final int CMD_RSSI_POLL = 83;
+ /* Get current RSSI */
+ private static final int CMD_GET_RSSI = 84;
+ /* Get approx current RSSI */
+ private static final int CMD_GET_RSSI_APPROX = 85;
+ /* Get link speed on connection */
+ private static final int CMD_GET_LINK_SPEED = 86;
+ /* Radio mac address */
+ private static final int CMD_GET_MAC_ADDR = 87;
+ /* Set up packet filtering */
+ private static final int CMD_START_PACKET_FILTERING = 88;
+ /* Clear packet filter */
+ private static final int CMD_STOP_PACKET_FILTERING = 89;
+
+ /* Connectivity service commands */
+ /* Bring down wifi connection */
+ private static final int CM_CMD_TEARDOWN = 110;
+ /* Reconnect to wifi */
+ private static final int CM_CMD_RECONNECT = 111;
+
/**
- * Observes the static IP address settings.
+ * Interval in milliseconds between polling for connection
+ * status items that are not sent via asynchronous events.
+ * An example is RSSI (signal strength).
*/
- private SettingsObserver mSettingsObserver;
-
- private boolean mIsScanModeActive;
- private boolean mEnableRssiPolling;
+ private static final int POLL_RSSI_INTERVAL_MSECS = 3000;
+
+ private static final int CONNECT_MODE = 1;
+ private static final int SCAN_ONLY_MODE = 2;
+
+ private static final int SCAN_ACTIVE = 1;
+ private static final int SCAN_PASSIVE = 2;
+
+ /**
+ * The maximum number of times we will retry a connection to an access point
+ * for which we have failed in acquiring an IP address from DHCP. A value of
+ * N means that we will make N+1 connection attempts in all.
+ * <p>
+ * See {@link Settings.Secure#WIFI_MAX_DHCP_RETRY_COUNT}. This is the default
+ * value if a Settings value is not present.
+ */
+ private static final int DEFAULT_MAX_DHCP_RETRIES = 9;
+
+ private static final int DRIVER_POWER_MODE_ACTIVE = 1;
+ private static final int DRIVER_POWER_MODE_AUTO = 0;
+
+ /* Default parent state */
+ private HierarchicalState mDefaultState = new DefaultState();
+ /* Temporary initial state */
+ private HierarchicalState mInitialState = new InitialState();
+ /* Unloading the driver */
+ private HierarchicalState mDriverUnloadingState = new DriverUnloadingState();
+ /* Loading the driver */
+ private HierarchicalState mDriverUnloadedState = new DriverUnloadedState();
+ /* Driver load/unload failed */
+ private HierarchicalState mDriverFailedState = new DriverFailedState();
+ /* Driver loading */
+ private HierarchicalState mDriverLoadingState = new DriverLoadingState();
+ /* Driver loaded */
+ private HierarchicalState mDriverLoadedState = new DriverLoadedState();
+ /* Driver loaded, waiting for supplicant to start */
+ private HierarchicalState mWaitForSupState = new WaitForSupState();
+
+ /* Driver loaded and supplicant ready */
+ private HierarchicalState mDriverSupReadyState = new DriverSupReadyState();
+ /* Driver start issued, waiting for completed event */
+ private HierarchicalState mDriverStartingState = new DriverStartingState();
+ /* Driver started */
+ private HierarchicalState mDriverStartedState = new DriverStartedState();
+ /* Driver stopping */
+ private HierarchicalState mDriverStoppingState = new DriverStoppingState();
+ /* Driver stopped */
+ private HierarchicalState mDriverStoppedState = new DriverStoppedState();
+ /* Scan for networks, no connection will be established */
+ private HierarchicalState mScanModeState = new ScanModeState();
+ /* Connecting to an access point */
+ private HierarchicalState mConnectModeState = new ConnectModeState();
+ /* Fetching IP after network connection (assoc+auth complete) */
+ private HierarchicalState mConnectingState = new ConnectingState();
+ /* Connected with IP addr */
+ private HierarchicalState mConnectedState = new ConnectedState();
+ /* disconnect issued, waiting for network disconnect confirmation */
+ private HierarchicalState mDisconnectingState = new DisconnectingState();
+ /* Network is not connected, supplicant assoc+auth is not complete */
+ private HierarchicalState mDisconnectedState = new DisconnectedState();
+
+ /* Soft Ap is running */
+ private HierarchicalState mSoftApStartedState = new SoftApStartedState();
+
+ /* Argument for Message object to indicate a synchronous call */
+ private static final int SYNCHRONOUS_CALL = 1;
+ private static final int ASYNCHRONOUS_CALL = 0;
+
/**
* One of {@link WifiManager#WIFI_STATE_DISABLED},
@@ -291,242 +430,153 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* {@link WifiManager#WIFI_STATE_ENABLING},
* {@link WifiManager#WIFI_STATE_UNKNOWN}
*
- * getWifiState() is not synchronized to make sure it's always fast,
- * even when the instance lock is held on other slow operations.
- * Use a atomic variable for state.
- */
- private final AtomicInteger mWifiState = new AtomicInteger(WIFI_STATE_UNKNOWN);
-
- // Wi-Fi run states:
- private static final int RUN_STATE_STARTING = 1;
- private static final int RUN_STATE_RUNNING = 2;
- private static final int RUN_STATE_STOPPING = 3;
- private static final int RUN_STATE_STOPPED = 4;
-
- private static final String mRunStateNames[] = {
- "Starting",
- "Running",
- "Stopping",
- "Stopped"
- };
- private int mRunState;
+ */
+ private final AtomicInteger mWifiState = new AtomicInteger(WIFI_STATE_DISABLED);
- private final IBatteryStats mBatteryStats;
+ /**
+ * One of {@link WifiManager#WIFI_AP_STATE_DISABLED},
+ * {@link WifiManager#WIFI_AP_STATE_DISABLING},
+ * {@link WifiManager#WIFI_AP_STATE_ENABLED},
+ * {@link WifiManager#WIFI_AP_STATE_ENABLING},
+ * {@link WifiManager#WIFI_AP_STATE_FAILED}
+ *
+ */
+ private final AtomicInteger mWifiApState = new AtomicInteger(WIFI_AP_STATE_DISABLED);
- private boolean mIsScanOnly;
+ private final AtomicInteger mLastEnableUid = new AtomicInteger(Process.myUid());
+ private final AtomicInteger mLastApEnableUid = new AtomicInteger(Process.myUid());
- private BluetoothA2dp mBluetoothA2dp;
+ private final IBatteryStats mBatteryStats;
- private String mInterfaceName;
- private static String LS = System.getProperty("line.separator");
+ public WifiStateTracker(Context context, Handler target) {
+ super(NETWORKTYPE);
- private Handler mTarget;
- private Context mContext;
- private boolean mPrivateDnsRouteSet = false;
- private int mDefaultGatewayAddr = 0;
- private boolean mDefaultRouteSet = false;
+ mCsHandler = target;
+ mContext = context;
- /**
- * A structure for supplying information about a supplicant state
- * change in the STATE_CHANGE event message that comes from the
- * WifiMonitor
- * thread.
- */
- private static class SupplicantStateChangeResult {
- SupplicantStateChangeResult(int networkId, String BSSID, SupplicantState state) {
- this.state = state;
- this.BSSID = BSSID;
- this.networkId = networkId;
- }
- int networkId;
- String BSSID;
- SupplicantState state;
- }
+ mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, NETWORKTYPE, "");
+ mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService("batteryinfo"));
- /**
- * A structure for supplying information about a connection in
- * the CONNECTED event message that comes from the WifiMonitor
- * thread.
- */
- private static class NetworkStateChangeResult {
- NetworkStateChangeResult(DetailedState state, String BSSID, int networkId) {
- this.state = state;
- this.BSSID = BSSID;
- this.networkId = networkId;
- }
- DetailedState state;
- String BSSID;
- int networkId;
- }
+ IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
+ nwService = INetworkManagementService.Stub.asInterface(b);
- public WifiStateTracker(Context context, Handler target) {
- mTarget = target;
- mContext = context;
- mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, "WIFI", "");
- mWifiInfo = new WifiInfo();
mWifiMonitor = new WifiMonitor(this);
- mHaveIpAddress = false;
- mObtainingIpAddress = false;
- setTornDownByConnMgr(false);
- mDisconnectPending = false;
- mScanResults = new ArrayList<ScanResult>();
- // Allocate DHCP info object once, and fill it in on each request
mDhcpInfo = new DhcpInfo();
- mRunState = RUN_STATE_STARTING;
+ mWifiInfo = new WifiInfo();
+ mInterfaceName = SystemProperties.get("wifi.interface", "tiwlan0");
+ mSupplicantStateTracker = new SupplicantStateTracker(context, getHandler());
+
+ mBluetoothHeadset = new BluetoothHeadset(mContext, null);
+ mNetworkProperties = new NetworkProperties();
+
+ mNetworkInfo.setIsAvailable(false);
+ mNetworkProperties.clear();
+ resetNotificationTimer();
+ setTeardownRequested(false);
+ mLastBssid = null;
+ mLastNetworkId = -1;
+ mLastSignalLevel = -1;
+
+ mScanResultCache = new LinkedHashMap<String, ScanResult>(
+ SCAN_RESULT_CACHE_SIZE, 0.75f, true) {
+ /*
+ * Limit the cache size by SCAN_RESULT_CACHE_SIZE
+ * elements
+ */
+ @Override
+ public boolean removeEldestEntry(Map.Entry eldest) {
+ return SCAN_RESULT_CACHE_SIZE < this.size();
+ }
+ };
// Setting is in seconds
- NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
+ NOTIFICATION_REPEAT_DELAY_MS = Settings.Secure.getInt(context.getContentResolver(),
Settings.Secure.WIFI_NETWORKS_AVAILABLE_REPEAT_DELAY, 900) * 1000l;
- mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(new Handler());
+ mNotificationEnabledSettingObserver = new NotificationEnabledSettingObserver(target);
mNotificationEnabledSettingObserver.register();
mSettingsObserver = new SettingsObserver(new Handler());
- mInterfaceName = SystemProperties.get("wifi.interface", "tiwlan0");
- mNetworkProperties = new NetworkProperties();
- mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService("batteryinfo"));
-
- }
+ PowerManager powerManager = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
+ sWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
- /**
- * Helper method: sets the supplicant state and keeps the network
- * info updated.
- * @param state the new state
- */
- private void setSupplicantState(SupplicantState state) {
- mWifiInfo.setSupplicantState(state);
- updateNetworkInfo();
- checkPollTimer();
- }
+ addState(mDefaultState);
+ addState(mInitialState, mDefaultState);
+ addState(mDriverUnloadingState, mDefaultState);
+ addState(mDriverUnloadedState, mDefaultState);
+ addState(mDriverFailedState, mDriverUnloadedState);
+ addState(mDriverLoadingState, mDefaultState);
+ addState(mDriverLoadedState, mDefaultState);
+ addState(mWaitForSupState, mDriverLoadedState);
+ addState(mDriverSupReadyState, mDefaultState);
+ addState(mDriverStartingState, mDriverSupReadyState);
+ addState(mDriverStartedState, mDriverSupReadyState);
+ addState(mScanModeState, mDriverStartedState);
+ addState(mConnectModeState, mDriverStartedState);
+ addState(mConnectingState, mConnectModeState);
+ addState(mConnectedState, mConnectModeState);
+ addState(mDisconnectingState, mConnectModeState);
+ addState(mDisconnectedState, mConnectModeState);
+ addState(mDriverStoppingState, mDriverSupReadyState);
+ addState(mDriverStoppedState, mDriverSupReadyState);
+ addState(mSoftApStartedState, mDefaultState);
- public SupplicantState getSupplicantState() {
- return mWifiInfo.getSupplicantState();
- }
+ setInitialState(mInitialState);
- /**
- * Helper method: sets the supplicant state and keeps the network
- * info updated (string version).
- * @param stateName the string name of the new state
- */
- private void setSupplicantState(String stateName) {
- mWifiInfo.setSupplicantState(stateName);
- updateNetworkInfo();
- checkPollTimer();
- }
+ if (DBG) setDbg(true);
- /**
- * Record the detailed state of a network, and if it is a
- * change from the previous state, send a notification to
- * any listeners.
- * @param state the new @{code DetailedState}
- */
- private void setDetailedState(NetworkInfo.DetailedState state) {
- setDetailedState(state, null, null);
+ //start the state machine
+ start();
}
- /**
- * Record the detailed state of a network, and if it is a
- * change from the previous state, send a notification to
- * any listeners.
- * @param state the new @{code DetailedState}
- * @param reason a {@code String} indicating a reason for the state change,
- * if one was supplied. May be {@code null}.
- * @param extraInfo optional {@code String} providing extra information about the state change
- */
- private void setDetailedState(NetworkInfo.DetailedState state, String reason, String extraInfo) {
- if (LOCAL_LOGD) Log.d(TAG, "setDetailed state, old ="
- + mNetworkInfo.getDetailedState() + " and new state=" + state);
- if (state != mNetworkInfo.getDetailedState()) {
- boolean wasConnecting = (mNetworkInfo.getState() == NetworkInfo.State.CONNECTING);
- String lastReason = mNetworkInfo.getReason();
- /*
- * If a reason was supplied when the CONNECTING state was entered, and no
- * reason was supplied for entering the CONNECTED state, then retain the
- * reason that was supplied when going to CONNECTING.
- */
- if (wasConnecting && state == NetworkInfo.DetailedState.CONNECTED && reason == null
- && lastReason != null)
- reason = lastReason;
- mNetworkInfo.setDetailedState(state, reason, extraInfo);
- Message msg = mTarget.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo);
- msg.sendToTarget();
- }
- }
- private void setDetailedStateInternal(NetworkInfo.DetailedState state) {
- mNetworkInfo.setDetailedState(state, null, null);
- }
+ /*********************************************************
+ * NetworkStateTracker interface implementation
+ ********************************************************/
public void setTeardownRequested(boolean isRequested) {
- mTeardownRequested = isRequested;
+ mTeardownRequested.set(isRequested);
}
public boolean isTeardownRequested() {
- return mTeardownRequested;
+ return mTeardownRequested.get();
}
/**
- * Helper method: sets the boolean indicating that the connection
- * manager asked the network to be torn down (and so only the connection
- * manager can set it up again).
- * network info updated.
- * @param flag {@code true} if explicitly disabled.
+ * Begin monitoring wifi connectivity
+ * @deprecated
+ *
+ * TODO: remove this from callers
*/
- private void setTornDownByConnMgr(boolean flag) {
- mTornDownByConnMgr = flag;
- updateNetworkInfo();
+ public void startMonitoring() {
}
/**
- * Return the name of our WLAN network interface.
- * @return the name of our interface.
+ * Disable connectivity to a network
+ * TODO: do away with return value after making MobileDataStateTracker async
*/
- public String getInterfaceName() {
- return mInterfaceName;
- }
-
- public boolean isPrivateDnsRouteSet() {
- return mPrivateDnsRouteSet;
- }
-
- public void privateDnsRouteSet(boolean enabled) {
- mPrivateDnsRouteSet = enabled;
- }
-
- public NetworkInfo getNetworkInfo() {
- return mNetworkInfo;
- }
-
- public int getDefaultGatewayAddr() {
- return mDefaultGatewayAddr;
- }
-
- public boolean isDefaultRouteSet() {
- return mDefaultRouteSet;
- }
-
- public void defaultRouteSet(boolean enabled) {
- mDefaultRouteSet = enabled;
+ public boolean teardown() {
+ sendMessage(CM_CMD_TEARDOWN);
+ return true;
}
/**
- * Return the system properties name associated with the tcp buffer sizes
- * for this network.
+ * Re-enable connectivity to a network after a {@link #teardown()}.
+ * TODO: do away with return value after making MobileDataStateTracker async
*/
- public String getTcpBufferSizesPropName() {
- return "net.tcp.buffersize.wifi";
- }
-
- public void startMonitoring() {
- /*
- * Get a handle on the WifiManager. This cannot be done in our
- * constructor, because the Wifi service is not yet registered.
- */
- mWM = (WifiManager)mContext.getSystemService(Context.WIFI_SERVICE);
+ public boolean reconnect() {
+ sendMessage(CM_CMD_RECONNECT);
+ return true;
}
- public void startEventLoop() {
- mWifiMonitor.startMonitoring();
+ /**
+ * Turn the wireless radio off for a network.
+ * @param turnOn {@code true} to turn the radio on, {@code false}
+ * TODO: do away with return value after making MobileDataStateTracker async
+ */
+ public boolean setRadio(boolean turnOn) {
+ setWifiEnabled(turnOn);
+ return true;
}
/**
@@ -538,1279 +588,334 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* unavailable.
* @return {@code true} if Wi-Fi connections are possible
*/
- public synchronized boolean isAvailable() {
- /*
- * TODO: Need to also look at scan results to see whether we're
- * in range of any access points. If we have scan results that
- * are no more than N seconds old, use those, otherwise, initiate
- * a scan and wait for the results. This only matters if we
- * allow mobile to be the preferred network.
- */
- SupplicantState suppState = mWifiInfo.getSupplicantState();
- return suppState != SupplicantState.UNINITIALIZED &&
- suppState != SupplicantState.INACTIVE &&
- (mTornDownByConnMgr || !isDriverStopped());
- }
-
- /**
- * {@inheritDoc}
- * There are currently no defined Wi-Fi subtypes.
- */
- public int getNetworkSubtype() {
- return 0;
- }
-
- /**
- * Helper method: updates the network info object to keep it in sync with
- * the Wi-Fi state tracker.
- */
- private void updateNetworkInfo() {
- mNetworkInfo.setIsAvailable(isAvailable());
- }
-
- /**
- * Report whether the Wi-Fi connection is fully configured for data.
- * @return {@code true} if the {@link SupplicantState} is
- * {@link android.net.wifi.SupplicantState#COMPLETED COMPLETED}.
- */
- public boolean isConnectionCompleted() {
- return mWifiInfo.getSupplicantState() == SupplicantState.COMPLETED;
- }
-
- /**
- * Report whether the Wi-Fi connection has successfully acquired an IP address.
- * @return {@code true} if the Wi-Fi connection has been assigned an IP address.
- */
- public boolean hasIpAddress() {
- return mHaveIpAddress;
- }
-
- /**
- * Send the tracker a notification that a user-entered password key
- * may be incorrect (i.e., caused authentication to fail).
- */
- void notifyPasswordKeyMayBeIncorrect() {
- sendEmptyMessage(EVENT_PASSWORD_KEY_MAY_BE_INCORRECT);
- }
-
- /**
- * Send the tracker a notification that a connection to the supplicant
- * daemon has been established.
- */
- void notifySupplicantConnection() {
- sendEmptyMessage(EVENT_SUPPLICANT_CONNECTION);
- }
-
- /**
- * Send the tracker a notification that the state of the supplicant
- * has changed.
- * @param networkId the configured network on which the state change occurred
- * @param newState the new {@code SupplicantState}
- */
- void notifyStateChange(int networkId, String BSSID, SupplicantState newState) {
- Message msg = Message.obtain(
- this, EVENT_SUPPLICANT_STATE_CHANGED,
- new SupplicantStateChangeResult(networkId, BSSID, newState));
- msg.sendToTarget();
- }
-
- /**
- * Send the tracker a notification that the state of Wifi connectivity
- * has changed.
- * @param networkId the configured network on which the state change occurred
- * @param newState the new network state
- * @param BSSID when the new state is {@link DetailedState#CONNECTED
- * NetworkInfo.DetailedState.CONNECTED},
- * this is the MAC address of the access point. Otherwise, it
- * is {@code null}.
- */
- void notifyStateChange(DetailedState newState, String BSSID, int networkId) {
- Message msg = Message.obtain(
- this, EVENT_NETWORK_STATE_CHANGED,
- new NetworkStateChangeResult(newState, BSSID, networkId));
- msg.sendToTarget();
+ public boolean isAvailable() {
+ return mNetworkInfo.isAvailable();
}
/**
- * Send the tracker a notification that a scan has completed, and results
- * are available.
+ * Tells the underlying networking system that the caller wants to
+ * begin using the named feature. The interpretation of {@code feature}
+ * is completely up to each networking implementation.
+ * @param feature the name of the feature to be used
+ * @param callingPid the process ID of the process that is issuing this request
+ * @param callingUid the user ID of the process that is issuing this request
+ * @return an integer value representing the outcome of the request.
+ * The interpretation of this value is specific to each networking
+ * implementation+feature combination, except that the value {@code -1}
+ * always indicates failure.
+ * TODO: needs to go away
*/
- void notifyScanResultsAvailable() {
- // reset the supplicant's handling of scan results to "normal" mode
- setScanResultHandling(SUPPL_SCAN_HANDLING_NORMAL);
- sendEmptyMessage(EVENT_SCAN_RESULTS_AVAILABLE);
+ public int startUsingNetworkFeature(String feature, int callingPid, int callingUid) {
+ return -1;
}
/**
- * Send the tracker a notification that we can no longer communicate with
- * the supplicant daemon.
+ * Tells the underlying networking system that the caller is finished
+ * using the named feature. The interpretation of {@code feature}
+ * is completely up to each networking implementation.
+ * @param feature the name of the feature that is no longer needed.
+ * @param callingPid the process ID of the process that is issuing this request
+ * @param callingUid the user ID of the process that is issuing this request
+ * @return an integer value representing the outcome of the request.
+ * The interpretation of this value is specific to each networking
+ * implementation+feature combination, except that the value {@code -1}
+ * always indicates failure.
+ * TODO: needs to go away
*/
- void notifySupplicantLost() {
- sendEmptyMessage(EVENT_SUPPLICANT_DISCONNECT);
+ public int stopUsingNetworkFeature(String feature, int callingPid, int callingUid) {
+ return -1;
}
- /**
- * Send the tracker a notification that the Wi-Fi driver has been stopped.
+ /* TODO: will go away.
+ * Notifications are directly handled in WifiStateTracker at checkAndSetNotification()
*/
- void notifyDriverStopped() {
- mRunState = RUN_STATE_STOPPED;
+ public void interpretScanResultsAvailable() {
- // Send a driver stopped message to our handler
- Message.obtain(this, EVENT_DRIVER_STATE_CHANGED, DRIVER_STOPPED, 0).sendToTarget();
}
/**
- * Send the tracker a notification that the Wi-Fi driver has been restarted after
- * having been stopped.
- */
- void notifyDriverStarted() {
- // Send a driver started message to our handler
- Message.obtain(this, EVENT_DRIVER_STATE_CHANGED, DRIVER_STARTED, 0).sendToTarget();
- }
-
- /**
- * Send the tracker a notification that the Wi-Fi driver has hung and needs restarting.
+ * Return the name of our WLAN network interface.
+ * @return the name of our interface.
*/
- void notifyDriverHung() {
- // Send a driver hanged message to our handler
- Message.obtain(this, EVENT_DRIVER_STATE_CHANGED, DRIVER_HUNG, 0).sendToTarget();
+ public String getInterfaceName() {
+ return mInterfaceName;
}
/**
- * Set the interval timer for polling connection information
- * that is not delivered asynchronously.
+ * Check if private DNS route is set for the network
*/
- private synchronized void checkPollTimer() {
- if (mEnableRssiPolling &&
- mWifiInfo.getSupplicantState() == SupplicantState.COMPLETED &&
- !hasMessages(EVENT_POLL_INTERVAL)) {
- sendEmptyMessageDelayed(EVENT_POLL_INTERVAL, POLL_STATUS_INTERVAL_MSECS);
- }
+ public boolean isPrivateDnsRouteSet() {
+ return mPrivateDnsRouteSet.get();
}
/**
- * TODO: mRunState is not synchronized in some places
- * address this as part of re-architect.
- *
- * TODO: We are exposing an additional public synchronized call
- * for a wakelock optimization in WifiService. Remove it
- * when we handle the wakelock in ConnectivityService.
+ * Set a flag indicating private DNS route is set
*/
- public synchronized boolean isDriverStopped() {
- return mRunState == RUN_STATE_STOPPED || mRunState == RUN_STATE_STOPPING;
- }
-
- private void noteRunState() {
- try {
- if (mRunState == RUN_STATE_RUNNING) {
- mBatteryStats.noteWifiRunning();
- } else if (mRunState == RUN_STATE_STOPPED) {
- mBatteryStats.noteWifiStopped();
- }
- } catch (RemoteException ignore) {
- }
+ public void privateDnsRouteSet(boolean enabled) {
+ mPrivateDnsRouteSet.set(enabled);
}
/**
- * Set the run state to either "normal" or "scan-only".
- * @param scanOnlyMode true if the new mode should be scan-only.
+ * Fetch NetworkInfo for the network
*/
- public synchronized void setScanOnlyMode(boolean scanOnlyMode) {
- // do nothing unless scan-only mode is changing
- if (mIsScanOnly != scanOnlyMode) {
- int scanType = (scanOnlyMode ?
- SUPPL_SCAN_HANDLING_LIST_ONLY : SUPPL_SCAN_HANDLING_NORMAL);
- if (LOCAL_LOGD) Log.v(TAG, "Scan-only mode changing to " + scanOnlyMode + " scanType=" + scanType);
- if (setScanResultHandling(scanType)) {
- mIsScanOnly = scanOnlyMode;
- if (!isDriverStopped()) {
- if (scanOnlyMode) {
- disconnect();
- } else {
- reconnectCommand();
- }
- }
- }
- }
- }
-
-
- private void checkIsBluetoothPlaying() {
- boolean isBluetoothPlaying = false;
- Set<BluetoothDevice> connected = mBluetoothA2dp.getConnectedSinks();
-
- for (BluetoothDevice device : connected) {
- if (mBluetoothA2dp.getSinkState(device) == BluetoothA2dp.STATE_PLAYING) {
- isBluetoothPlaying = true;
- break;
- }
- }
- setBluetoothScanMode(isBluetoothPlaying);
- }
-
- public void enableRssiPolling(boolean enable) {
- if (mEnableRssiPolling != enable) {
- mEnableRssiPolling = enable;
- checkPollTimer();
- }
+ public NetworkInfo getNetworkInfo() {
+ return mNetworkInfo;
}
/**
- * Tracks the WPA supplicant states to detect "loop" situations.
- * @param newSupplicantState The new WPA supplicant state.
- * @return {@code true} if the supplicant loop should be stopped
- * and {@code false} if it should continue.
+ * Fetch NetworkProperties for the network
*/
- private boolean isSupplicantLooping(SupplicantState newSupplicantState) {
- if (SupplicantState.ASSOCIATING.ordinal() <= newSupplicantState.ordinal()
- && newSupplicantState.ordinal() < SupplicantState.COMPLETED.ordinal()) {
- if (mSupplicantLoopState != newSupplicantState) {
- if (newSupplicantState.ordinal() < mSupplicantLoopState.ordinal()) {
- ++mNumSupplicantLoopIterations;
- }
-
- mSupplicantLoopState = newSupplicantState;
- }
- } else if (newSupplicantState == SupplicantState.COMPLETED) {
- resetSupplicantLoopState();
- }
-
- return mNumSupplicantLoopIterations >= MAX_SUPPLICANT_LOOP_ITERATIONS;
+ public NetworkProperties getNetworkProperties() {
+ return mNetworkProperties;
}
/**
- * Resets the WPA supplicant loop state.
+ * Fetch default gateway address for the network
*/
- private void resetSupplicantLoopState() {
- mNumSupplicantLoopIterations = 0;
- }
-
- @Override
- public void handleMessage(Message msg) {
- Intent intent;
-
- switch (msg.what) {
- case EVENT_SUPPLICANT_CONNECTION:
- mRunState = RUN_STATE_RUNNING;
- noteRunState();
- checkUseStaticIp();
- /* Reset notification state on new connection */
- resetNotificationTimer();
- /*
- * DHCP requests are blocking, so run them in a separate thread.
- */
- HandlerThread dhcpThread = new HandlerThread("DHCP Handler Thread");
- dhcpThread.start();
- mDhcpTarget = new DhcpHandler(dhcpThread.getLooper(), this);
- mIsScanModeActive = true;
- mTornDownByConnMgr = false;
- mLastBssid = null;
- mLastSsid = null;
- requestConnectionInfo();
- SupplicantState supplState = mWifiInfo.getSupplicantState();
- /**
- * The MAC address isn't going to change, so just request it
- * once here.
- */
- String macaddr = getMacAddress();
-
- if (macaddr != null) {
- mWifiInfo.setMacAddress(macaddr);
- }
- if (LOCAL_LOGD) Log.v(TAG, "Connection to supplicant established, state=" +
- supplState);
- // Wi-Fi supplicant connection state changed:
- // [31- 2] Reserved for future use
- // [ 1- 0] Connected to supplicant (1), disconnected from supplicant (0) ,
- // or supplicant died (2)
- EventLog.writeEvent(EVENTLOG_SUPPLICANT_CONNECTION_STATE_CHANGED, 1);
- /*
- * The COMPLETED state change from the supplicant may have occurred
- * in between polling for supplicant availability, in which case
- * we didn't perform a DHCP request to get an IP address.
- */
- if (supplState == SupplicantState.COMPLETED) {
- mLastBssid = mWifiInfo.getBSSID();
- mLastSsid = mWifiInfo.getSSID();
- configureInterface();
- }
- if (ActivityManagerNative.isSystemReady()) {
- intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
- intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, true);
- mContext.sendBroadcast(intent);
- }
- if (supplState == SupplicantState.COMPLETED && mHaveIpAddress) {
- setDetailedState(DetailedState.CONNECTED);
- } else {
- setDetailedState(WifiInfo.getDetailedStateOf(supplState));
- }
- /*
- * Filter out multicast packets. This saves battery power, since
- * the CPU doesn't have to spend time processing packets that
- * are going to end up being thrown away.
- */
- mWM.initializeMulticastFiltering();
-
- if (mBluetoothA2dp == null) {
- mBluetoothA2dp = new BluetoothA2dp(mContext);
- }
- checkIsBluetoothPlaying();
-
- // initialize this after the supplicant is alive
- setNumAllowedChannels();
- break;
-
- case EVENT_SUPPLICANT_DISCONNECT:
- mRunState = RUN_STATE_STOPPED;
- noteRunState();
- boolean died = mWifiState.get() != WIFI_STATE_DISABLED &&
- mWifiState.get() != WIFI_STATE_DISABLING;
- if (died) {
- if (LOCAL_LOGD) Log.v(TAG, "Supplicant died unexpectedly");
- } else {
- if (LOCAL_LOGD) Log.v(TAG, "Connection to supplicant lost");
- }
- // Wi-Fi supplicant connection state changed:
- // [31- 2] Reserved for future use
- // [ 1- 0] Connected to supplicant (1), disconnected from supplicant (0) ,
- // or supplicant died (2)
- EventLog.writeEvent(EVENTLOG_SUPPLICANT_CONNECTION_STATE_CHANGED, died ? 2 : 0);
- closeSupplicantConnection();
-
- if (died) {
- resetConnections(true);
- }
- // When supplicant dies, kill the DHCP thread
- if (mDhcpTarget != null) {
- mDhcpTarget.getLooper().quit();
- mDhcpTarget = null;
- }
- mContext.removeStickyBroadcast(new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION));
- if (ActivityManagerNative.isSystemReady()) {
- intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
- intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
- mContext.sendBroadcast(intent);
- }
- setDetailedState(DetailedState.DISCONNECTED);
- setSupplicantState(SupplicantState.UNINITIALIZED);
- mNetworkProperties.clear();
- mHaveIpAddress = false;
- mObtainingIpAddress = false;
- if (died) {
- mWM.setWifiEnabled(false);
- }
- break;
-
- case EVENT_MAYBE_START_SCAN_POST_DISCONNECT:
- // Only do this if we haven't gotten a new supplicant status since the timer
- // started
- if (mNumSupplicantStateChanges == msg.arg1) {
- scan(false); // do a passive scan
- }
- break;
-
- case EVENT_SUPPLICANT_STATE_CHANGED:
- mNumSupplicantStateChanges++;
- SupplicantStateChangeResult supplicantStateResult =
- (SupplicantStateChangeResult) msg.obj;
- SupplicantState newState = supplicantStateResult.state;
- SupplicantState currentState = mWifiInfo.getSupplicantState();
-
- // Wi-Fi supplicant state changed:
- // [31- 6] Reserved for future use
- // [ 5- 0] Supplicant state ordinal (as defined by SupplicantState)
- int eventLogParam = (newState.ordinal() & 0x3f);
- EventLog.writeEvent(EVENTLOG_SUPPLICANT_STATE_CHANGED, eventLogParam);
-
- if (LOCAL_LOGD) Log.v(TAG, "Changing supplicant state: "
- + currentState +
- " ==> " + newState);
-
- int networkId = supplicantStateResult.networkId;
-
- /**
- * The SupplicantState BSSID value is valid in ASSOCIATING state only.
- * The NetworkState BSSID value comes upon a successful connection.
- */
- if (supplicantStateResult.state == SupplicantState.ASSOCIATING) {
- mLastBssid = supplicantStateResult.BSSID;
- }
- /*
- * If we get disconnect or inactive we need to start our
- * watchdog timer to start a scan
- */
- if (newState == SupplicantState.DISCONNECTED ||
- newState == SupplicantState.INACTIVE) {
- sendMessageDelayed(obtainMessage(EVENT_MAYBE_START_SCAN_POST_DISCONNECT,
- mNumSupplicantStateChanges, 0), KICKSTART_SCANNING_DELAY_MSECS);
- }
-
-
- /*
- * Did we get to DISCONNECTED state due to an
- * authentication (password) failure?
- */
- boolean failedToAuthenticate = false;
- if (newState == SupplicantState.DISCONNECTED) {
- failedToAuthenticate = mPasswordKeyMayBeIncorrect;
- }
- mPasswordKeyMayBeIncorrect = false;
-
- /*
- * Keep track of the supplicant state and check if we should
- * disable the network
- */
- boolean disabledNetwork = false;
- if (isSupplicantLooping(newState)) {
- if (LOCAL_LOGD) {
- Log.v(TAG,
- "Stop WPA supplicant loop and disable network");
- }
- disabledNetwork = wifiManagerDisableNetwork(networkId);
- }
-
- if (disabledNetwork) {
- /*
- * Reset the loop state if we disabled the network
- */
- resetSupplicantLoopState();
- } else if (newState != currentState ||
- (newState == SupplicantState.DISCONNECTED && isDriverStopped())) {
- setSupplicantState(newState);
- if (newState == SupplicantState.DORMANT) {
- DetailedState newDetailedState;
- Message reconnectMsg = obtainMessage(EVENT_DEFERRED_RECONNECT, mLastBssid);
- if (mIsScanOnly || mRunState == RUN_STATE_STOPPING) {
- newDetailedState = DetailedState.IDLE;
- } else {
- newDetailedState = DetailedState.FAILED;
- }
- handleDisconnectedState(newDetailedState, true);
- /**
- * If we were associated with a network (networkId != -1),
- * assume we reached this state because of a failed attempt
- * to acquire an IP address, and attempt another connection
- * and IP address acquisition in RECONNECT_DELAY_MSECS
- * milliseconds.
- */
- if (mRunState == RUN_STATE_RUNNING && !mIsScanOnly && networkId != -1) {
- sendMessageDelayed(reconnectMsg, RECONNECT_DELAY_MSECS);
- } else if (mRunState == RUN_STATE_STOPPING) {
- stopDriver();
- } else if (mRunState == RUN_STATE_STARTING && !mIsScanOnly) {
- reconnectCommand();
- }
- } else if (newState == SupplicantState.DISCONNECTED) {
- mNetworkProperties.clear();
- mHaveIpAddress = false;
- if (isDriverStopped() || mDisconnectExpected) {
- handleDisconnectedState(DetailedState.DISCONNECTED, true);
- } else {
- scheduleDisconnect();
- }
- } else if (newState != SupplicantState.COMPLETED && !mDisconnectPending) {
- /**
- * Ignore events that don't change the connectivity state,
- * such as WPA rekeying operations.
- */
- if (!(currentState == SupplicantState.COMPLETED &&
- (newState == SupplicantState.ASSOCIATING ||
- newState == SupplicantState.ASSOCIATED ||
- newState == SupplicantState.FOUR_WAY_HANDSHAKE ||
- newState == SupplicantState.GROUP_HANDSHAKE))) {
- setDetailedState(WifiInfo.getDetailedStateOf(newState));
- }
- }
-
- mDisconnectExpected = false;
- intent = new Intent(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
- intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
- | Intent.FLAG_RECEIVER_REPLACE_PENDING);
- intent.putExtra(WifiManager.EXTRA_NEW_STATE, (Parcelable)newState);
- if (failedToAuthenticate) {
- if (LOCAL_LOGD) Log.d(TAG, "Failed to authenticate, disabling network " + networkId);
- wifiManagerDisableNetwork(networkId);
- intent.putExtra(
- WifiManager.EXTRA_SUPPLICANT_ERROR,
- WifiManager.ERROR_AUTHENTICATING);
- }
- mContext.sendStickyBroadcast(intent);
- }
- break;
-
- case EVENT_NETWORK_STATE_CHANGED:
- /*
- * Each CONNECT or DISCONNECT generates a pair of events.
- * One is a supplicant state change event, and the other
- * is a network state change event. For connects, the
- * supplicant event always arrives first, followed by
- * the network state change event. Only the latter event
- * has the BSSID, which we are interested in capturing.
- * For disconnects, the order is the opposite -- the
- * network state change event comes first, followed by
- * the supplicant state change event.
- */
- NetworkStateChangeResult result =
- (NetworkStateChangeResult) msg.obj;
-
- // Wi-Fi network state changed:
- // [31- 6] Reserved for future use
- // [ 5- 0] Detailed state ordinal (as defined by NetworkInfo.DetailedState)
- eventLogParam = (result.state.ordinal() & 0x3f);
- EventLog.writeEvent(EVENTLOG_NETWORK_STATE_CHANGED, eventLogParam);
-
- if (LOCAL_LOGD) Log.v(TAG, "New network state is " + result.state);
- /*
- * If we're in scan-only mode, don't advance the state machine, and
- * don't report the state change to clients.
- */
- if (mIsScanOnly) {
- if (LOCAL_LOGD) Log.v(TAG, "Dropping event in scan-only mode");
- break;
- }
- if (result.state != DetailedState.SCANNING) {
- /*
- * Reset the scan count since there was a network state
- * change. This could be from supplicant trying to associate
- * with a network.
- */
- mNumScansSinceNetworkStateChange = 0;
- }
- /*
- * If the supplicant sent us a CONNECTED event, we don't
- * want to send out an indication of overall network
- * connectivity until we have our IP address. If the
- * supplicant sent us a DISCONNECTED event, we delay
- * sending a notification in case a reconnection to
- * the same access point occurs within a short time.
- */
- if (result.state == DetailedState.DISCONNECTED) {
- if (mWifiInfo.getSupplicantState() != SupplicantState.DORMANT) {
- scheduleDisconnect();
- }
- break;
- }
- requestConnectionStatus(mWifiInfo);
- if (!(result.state == DetailedState.CONNECTED &&
- (!mHaveIpAddress || mDisconnectPending))) {
- setDetailedState(result.state);
- }
-
- if (result.state == DetailedState.CONNECTED) {
- /*
- * Remove the 'available networks' notification when we
- * successfully connect to a network.
- */
- setNotificationVisible(false, 0, false, 0);
- boolean wasDisconnectPending = mDisconnectPending;
- cancelDisconnect();
- /*
- * The connection is fully configured as far as link-level
- * connectivity is concerned, but we may still need to obtain
- * an IP address.
- */
- if (wasDisconnectPending) {
- DetailedState saveState = getNetworkInfo().getDetailedState();
- handleDisconnectedState(DetailedState.DISCONNECTED, false);
- setDetailedStateInternal(saveState);
- }
-
- configureInterface();
- mLastBssid = result.BSSID;
- mLastSsid = mWifiInfo.getSSID();
- mLastNetworkId = result.networkId;
- if (mHaveIpAddress) {
- setDetailedState(DetailedState.CONNECTED);
- } else {
- setDetailedState(DetailedState.OBTAINING_IPADDR);
- }
- }
- sendNetworkStateChangeBroadcast(mWifiInfo.getBSSID());
- break;
-
- case EVENT_SCAN_RESULTS_AVAILABLE:
- if (ActivityManagerNative.isSystemReady()) {
- mContext.sendBroadcast(new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
- }
- sendScanResultsAvailable();
- /**
- * On receiving the first scan results after connecting to
- * the supplicant, switch scan mode over to passive.
- */
- setScanMode(false);
- break;
-
- case EVENT_POLL_INTERVAL:
- if (mWifiInfo.getSupplicantState() != SupplicantState.UNINITIALIZED) {
- requestPolledInfo(mWifiInfo, true);
- checkPollTimer();
- }
- break;
-
- case EVENT_DEFERRED_DISCONNECT:
- if (mWifiInfo.getSupplicantState() != SupplicantState.UNINITIALIZED) {
- handleDisconnectedState(DetailedState.DISCONNECTED, true);
- }
- break;
-
- case EVENT_DEFERRED_RECONNECT:
- /**
- * mLastBssid can be null when there is a reconnect
- * request on the first BSSID we connect to
- */
- String BSSID = (msg.obj != null) ? msg.obj.toString() : null;
- /**
- * If we've exceeded the maximum number of retries for reconnecting
- * to a given network, disable the network
- */
- if (mWifiInfo.getSupplicantState() != SupplicantState.UNINITIALIZED) {
- if (++mReconnectCount > getMaxDhcpRetries()) {
- if (LOCAL_LOGD) {
- Log.d(TAG, "Failed reconnect count: " +
- mReconnectCount + " Disabling " + BSSID);
- }
- mWM.disableNetwork(mLastNetworkId);
- }
- reconnectCommand();
- }
- break;
-
- case EVENT_INTERFACE_CONFIGURATION_SUCCEEDED:
- /**
- * Since this event is sent from another thread, it might have been
- * sent after we closed our connection to the supplicant in the course
- * of disabling Wi-Fi. In that case, we should just ignore the event.
- */
- if (mWifiInfo.getSupplicantState() == SupplicantState.UNINITIALIZED) {
- break;
- }
- mReconnectCount = 0;
- mHaveIpAddress = true;
- configureNetworkProperties();
- mObtainingIpAddress = false;
- mWifiInfo.setIpAddress(mDhcpInfo.ipAddress);
- mLastSignalLevel = -1; // force update of signal strength
- if (mNetworkInfo.getDetailedState() != DetailedState.CONNECTED) {
- setDetailedState(DetailedState.CONNECTED);
- sendNetworkStateChangeBroadcast(mWifiInfo.getBSSID());
- } else {
- mTarget.sendEmptyMessage(EVENT_CONFIGURATION_CHANGED);
- }
- if (LOCAL_LOGD) Log.v(TAG, "IP configuration: " + mDhcpInfo);
- // Wi-Fi interface configuration state changed:
- // [31- 1] Reserved for future use
- // [ 0- 0] Interface configuration succeeded (1) or failed (0)
- EventLog.writeEvent(EVENTLOG_INTERFACE_CONFIGURATION_STATE_CHANGED, 1);
-
- // We've connected successfully, so allow the notification again in the future
- resetNotificationTimer();
- break;
-
- case EVENT_INTERFACE_CONFIGURATION_FAILED:
- if (mWifiInfo.getSupplicantState() != SupplicantState.UNINITIALIZED) {
- // Wi-Fi interface configuration state changed:
- // [31- 1] Reserved for future use
- // [ 0- 0] Interface configuration succeeded (1) or failed (0)
- EventLog.writeEvent(EVENTLOG_INTERFACE_CONFIGURATION_STATE_CHANGED, 0);
- mNetworkProperties.clear();
- mHaveIpAddress = false;
- mWifiInfo.setIpAddress(0);
- mObtainingIpAddress = false;
- disconnect();
- }
- break;
-
- case EVENT_DRIVER_STATE_CHANGED:
- // Wi-Fi driver state changed:
- // 0 STARTED
- // 1 STOPPED
- // 2 HUNG
- EventLog.writeEvent(EVENTLOG_DRIVER_STATE_CHANGED, msg.arg1);
-
- switch (msg.arg1) {
- case DRIVER_STARTED:
- /**
- * Set the number of allowed radio channels according
- * to the system setting, since it gets reset by the
- * driver upon changing to the STARTED state.
- */
- setNumAllowedChannels();
- synchronized (this) {
- if (mRunState == RUN_STATE_STARTING) {
- mRunState = RUN_STATE_RUNNING;
- if (!mIsScanOnly) {
- reconnectCommand();
- } else {
- // In some situations, supplicant needs to be kickstarted to
- // start the background scanning
- scan(true);
- }
- }
- }
- break;
- case DRIVER_HUNG:
- Log.e(TAG, "Wifi Driver reports HUNG - reloading.");
- /**
- * restart the driver - toggle off and on
- */
- mWM.setWifiEnabled(false);
- mWM.setWifiEnabled(true);
- break;
- }
- noteRunState();
- break;
-
- case EVENT_PASSWORD_KEY_MAY_BE_INCORRECT:
- mPasswordKeyMayBeIncorrect = true;
- break;
- }
- }
-
- private boolean wifiManagerDisableNetwork(int networkId) {
- boolean disabledNetwork = false;
- if (0 <= networkId) {
- disabledNetwork = mWM.disableNetwork(networkId);
- if (LOCAL_LOGD) {
- if (disabledNetwork) {
- Log.v(TAG, "Disabled network: " + networkId);
- }
- }
- }
- if (LOCAL_LOGD) {
- if (!disabledNetwork) {
- Log.e(TAG, "Failed to disable network:" +
- " invalid network id: " + networkId);
- }
- }
- return disabledNetwork;
- }
-
-
- private void configureNetworkProperties() {
- try {
- mNetworkProperties.setInterface(NetworkInterface.getByName(mInterfaceName));
- } catch (SocketException e) {
- Log.e(TAG, "SocketException creating NetworkInterface from " + mInterfaceName +
- ". e=" + e);
- return;
- } catch (NullPointerException e) {
- Log.e(TAG, "NPE creating NetworkInterface. e=" + e);
- return;
- }
- // TODO - fix this for v6
- try {
- mNetworkProperties.addAddress(InetAddress.getByAddress(
- NetworkUtils.v4IntToArray(mDhcpInfo.ipAddress)));
- } catch (UnknownHostException e) {
- Log.e(TAG, "Exception setting IpAddress using " + mDhcpInfo + ", e=" + e);
- }
-
- try {
- mNetworkProperties.setGateway(InetAddress.getByAddress(NetworkUtils.v4IntToArray(
- mDhcpInfo.gateway)));
- } catch (UnknownHostException e) {
- Log.e(TAG, "Exception setting Gateway using " + mDhcpInfo + ", e=" + e);
- }
-
- try {
- mNetworkProperties.addDns(InetAddress.getByAddress(
- NetworkUtils.v4IntToArray(mDhcpInfo.dns1)));
- } catch (UnknownHostException e) {
- Log.e(TAG, "Exception setting Dns1 using " + mDhcpInfo + ", e=" + e);
- }
- try {
- mNetworkProperties.addDns(InetAddress.getByAddress(
- NetworkUtils.v4IntToArray(mDhcpInfo.dns2)));
-
- } catch (UnknownHostException e) {
- Log.e(TAG, "Exception setting Dns2 using " + mDhcpInfo + ", e=" + e);
- }
- // TODO - add proxy info
- }
-
- private void configureInterface() {
- checkPollTimer();
- mLastSignalLevel = -1;
- if (!mUseStaticIp) {
- if (!mHaveIpAddress && !mObtainingIpAddress) {
- mObtainingIpAddress = true;
- mDhcpTarget.sendEmptyMessage(EVENT_DHCP_START);
- }
- } else {
- int event;
- if (NetworkUtils.configureInterface(mInterfaceName, mDhcpInfo)) {
- event = EVENT_INTERFACE_CONFIGURATION_SUCCEEDED;
- if (LOCAL_LOGD) Log.v(TAG, "Static IP configuration succeeded");
- } else {
- event = EVENT_INTERFACE_CONFIGURATION_FAILED;
- if (LOCAL_LOGD) Log.v(TAG, "Static IP configuration failed");
- }
- sendEmptyMessage(event);
- }
+ public int getDefaultGatewayAddr() {
+ return mDefaultGatewayAddr.get();
}
/**
- * Reset our IP state and send out broadcasts following a disconnect.
- * @param newState the {@code DetailedState} to set. Should be either
- * {@code DISCONNECTED} or {@code FAILED}.
- * @param disableInterface indicates whether the interface should
- * be disabled
+ * Check if default route is set
*/
- private void handleDisconnectedState(DetailedState newState, boolean disableInterface) {
- if (mDisconnectPending) {
- cancelDisconnect();
- }
- mDisconnectExpected = false;
- resetConnections(disableInterface);
- setDetailedState(newState);
- sendNetworkStateChangeBroadcast(mLastBssid);
- mWifiInfo.setBSSID(null);
- mLastBssid = null;
- mLastSsid = null;
- mDisconnectPending = false;
+ public boolean isDefaultRouteSet() {
+ return mDefaultRouteSet.get();
}
/**
- * Resets the Wi-Fi Connections by clearing any state, resetting any sockets
- * using the interface, stopping DHCP, and disabling the interface.
+ * Set a flag indicating default route is set for the network
*/
- public void resetConnections(boolean disableInterface) {
- if (LOCAL_LOGD) Log.d(TAG, "Reset connections and stopping DHCP");
- mNetworkProperties.clear();
- mHaveIpAddress = false;
- mObtainingIpAddress = false;
- mWifiInfo.setIpAddress(0);
-
- /*
- * Reset connection depends on both the interface and the IP assigned,
- * so it should be done before any chance of the IP being lost.
- */
- NetworkUtils.resetConnections(mInterfaceName);
-
- // Stop DHCP
- if (mDhcpTarget != null) {
- mDhcpTarget.setCancelCallback(true);
- mDhcpTarget.removeMessages(EVENT_DHCP_START);
- }
- if (!NetworkUtils.stopDhcp(mInterfaceName)) {
- Log.e(TAG, "Could not stop DHCP");
- }
-
- /**
- * Interface is re-enabled in the supplicant
- * when moving out of ASSOCIATING state
- */
- if(disableInterface) {
- if (LOCAL_LOGD) Log.d(TAG, "Disabling interface");
- NetworkUtils.disableInterface(mInterfaceName);
- }
+ public void defaultRouteSet(boolean enabled) {
+ mDefaultRouteSet.set(enabled);
}
/**
- * The supplicant is reporting that we are disconnected from the current
- * access point. Often, however, a disconnect will be followed very shortly
- * by a reconnect to the same access point. Therefore, we delay resetting
- * the connection's IP state for a bit.
+ * Return the system properties name associated with the tcp buffer sizes
+ * for this network.
*/
- private void scheduleDisconnect() {
- mDisconnectPending = true;
- if (!hasMessages(EVENT_DEFERRED_DISCONNECT)) {
- sendEmptyMessageDelayed(EVENT_DEFERRED_DISCONNECT, DISCONNECT_DELAY_MSECS);
- }
- }
-
- private void cancelDisconnect() {
- mDisconnectPending = false;
- removeMessages(EVENT_DEFERRED_DISCONNECT);
- }
-
- public DhcpInfo getDhcpInfo() {
- return mDhcpInfo;
+ public String getTcpBufferSizesPropName() {
+ return "net.tcp.buffersize.wifi";
}
- public synchronized List<ScanResult> getScanResultsList() {
- return mScanResults;
- }
- public synchronized void setScanResultsList(List<ScanResult> scanList) {
- mScanResults = scanList;
- }
+ /*********************************************************
+ * Methods exposed for public use
+ ********************************************************/
/**
- * Get status information for the current connection, if any.
- * @return a {@link WifiInfo} object containing information about the current connection
+ * TODO: doc
*/
- public WifiInfo requestConnectionInfo() {
- requestConnectionStatus(mWifiInfo);
- requestPolledInfo(mWifiInfo, false);
- return mWifiInfo;
- }
-
- private void requestConnectionStatus(WifiInfo info) {
- String reply = status();
- if (reply == null) {
- return;
- }
- /*
- * Parse the reply from the supplicant to the status command, and update
- * local state accordingly. The reply is a series of lines of the form
- * "name=value".
- */
- String SSID = null;
- String BSSID = null;
- String suppState = null;
- int netId = -1;
- String[] lines = reply.split("\n");
- for (String line : lines) {
- String[] prop = line.split(" *= *", 2);
- if (prop.length < 2)
- continue;
- String name = prop[0];
- String value = prop[1];
- if (name.equalsIgnoreCase("id"))
- netId = Integer.parseInt(value);
- else if (name.equalsIgnoreCase("ssid"))
- SSID = value;
- else if (name.equalsIgnoreCase("bssid"))
- BSSID = value;
- else if (name.equalsIgnoreCase("wpa_state"))
- suppState = value;
- }
- info.setNetworkId(netId);
- info.setSSID(SSID);
- info.setBSSID(BSSID);
- /*
- * We only set the supplicant state if the previous state was
- * UNINITIALIZED. This should only happen when we first connect to
- * the supplicant. Once we're connected, we should always receive
- * an event upon any state change, but in this case, we want to
- * make sure any listeners are made aware of the state change.
- */
- if (mWifiInfo.getSupplicantState() == SupplicantState.UNINITIALIZED && suppState != null)
- setSupplicantState(suppState);
+ public boolean pingSupplicant() {
+ return sendSyncMessage(CMD_PING_SUPPLICANT).boolValue;
}
/**
- * Get the dynamic information that is not reported via events.
- * @param info the object into which the information should be captured.
+ * TODO: doc
*/
- private synchronized void requestPolledInfo(WifiInfo info, boolean polling)
- {
- int newRssi = (polling ? getRssiApprox() : getRssi());
- if (newRssi != -1 && -200 < newRssi && newRssi < 256) { // screen out invalid values
- /* some implementations avoid negative values by adding 256
- * so we need to adjust for that here.
- */
- if (newRssi > 0) newRssi -= 256;
- info.setRssi(newRssi);
- /*
- * Rather then sending the raw RSSI out every time it
- * changes, we precalculate the signal level that would
- * be displayed in the status bar, and only send the
- * broadcast if that much more coarse-grained number
- * changes. This cuts down greatly on the number of
- * broadcasts, at the cost of not informing others
- * interested in RSSI of all the changes in signal
- * level.
- */
- // TODO: The second arg to the call below needs to be a symbol somewhere, but
- // it's actually the size of an array of icons that's private
- // to StatusBar Policy.
- int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, 4);
- if (newSignalLevel != mLastSignalLevel) {
- sendRssiChangeBroadcast(newRssi);
- }
- mLastSignalLevel = newSignalLevel;
- } else {
- info.setRssi(-200);
- }
- int newLinkSpeed = getLinkSpeed();
- if (newLinkSpeed != -1) {
- info.setLinkSpeed(newLinkSpeed);
- }
- }
-
- private void sendRssiChangeBroadcast(final int newRssi) {
- if (ActivityManagerNative.isSystemReady()) {
- Intent intent = new Intent(WifiManager.RSSI_CHANGED_ACTION);
- intent.putExtra(WifiManager.EXTRA_NEW_RSSI, newRssi);
- mContext.sendBroadcast(intent);
- }
- }
-
- private void sendNetworkStateChangeBroadcast(String bssid) {
- Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION);
- intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
- | Intent.FLAG_RECEIVER_REPLACE_PENDING);
- intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, mNetworkInfo);
- if (bssid != null)
- intent.putExtra(WifiManager.EXTRA_BSSID, bssid);
- mContext.sendStickyBroadcast(intent);
+ public boolean startScan(boolean forceActive) {
+ return sendSyncMessage(obtainMessage(CMD_START_SCAN, forceActive ?
+ SCAN_ACTIVE : SCAN_PASSIVE, 0)).boolValue;
}
/**
- * Disable Wi-Fi connectivity by stopping the driver.
+ * TODO: doc
*/
- public boolean teardown() {
- if (!mTornDownByConnMgr) {
- if (disconnectAndStop()) {
- setTornDownByConnMgr(true);
- return true;
- } else {
- return false;
- }
+ public void setWifiEnabled(boolean enable) {
+ mLastEnableUid.set(Binder.getCallingUid());
+ if (enable) {
+ /* Argument is the state that is entered prior to load */
+ sendMessage(obtainMessage(CMD_LOAD_DRIVER, WIFI_STATE_ENABLING, 0));
+ sendMessage(CMD_START_SUPPLICANT);
} else {
- return true;
+ sendMessage(CMD_STOP_SUPPLICANT);
+ /* Argument is the state that is entered upon success */
+ sendMessage(obtainMessage(CMD_UNLOAD_DRIVER, WIFI_STATE_DISABLED, 0));
}
}
/**
- * Reenable Wi-Fi connectivity by restarting the driver.
+ * TODO: doc
*/
- public boolean reconnect() {
- if (mTornDownByConnMgr) {
- if (restart()) {
- setTornDownByConnMgr(false);
- return true;
- } else {
- return false;
- }
+ public void setWifiApEnabled(WifiConfiguration wifiConfig, boolean enable) {
+ mLastApEnableUid.set(Binder.getCallingUid());
+ if (enable) {
+ /* Argument is the state that is entered prior to load */
+ sendMessage(obtainMessage(CMD_LOAD_DRIVER, WIFI_AP_STATE_ENABLING, 0));
+ sendMessage(obtainMessage(CMD_START_AP, wifiConfig));
} else {
- return true;
+ sendMessage(CMD_STOP_AP);
+ /* Argument is the state that is entered upon success */
+ sendMessage(obtainMessage(CMD_UNLOAD_DRIVER, WIFI_AP_STATE_DISABLED, 0));
}
}
/**
- * We want to stop the driver, but if we're connected to a network,
- * we first want to disconnect, so that the supplicant is always in
- * a known state (DISCONNECTED) when the driver is stopped.
- * @return {@code true} if the operation succeeds, which means that the
- * disconnect or stop command was initiated.
+ * TODO: doc
*/
- public synchronized boolean disconnectAndStop() {
- boolean ret = true;;
- if (mRunState != RUN_STATE_STOPPING && mRunState != RUN_STATE_STOPPED) {
- // Take down any open network notifications
- setNotificationVisible(false, 0, false, 0);
-
- if (mWifiInfo.getSupplicantState() == SupplicantState.DORMANT) {
- ret = stopDriver();
- } else {
- ret = disconnect();
- }
- mRunState = RUN_STATE_STOPPING;
- }
- return ret;
- }
-
- public synchronized boolean restart() {
- if (mRunState == RUN_STATE_STOPPED) {
- mRunState = RUN_STATE_STARTING;
- resetConnections(true);
- return startDriver();
- } else if (mRunState == RUN_STATE_STOPPING) {
- mRunState = RUN_STATE_STARTING;
- }
- return true;
- }
-
public int getWifiState() {
return mWifiState.get();
}
- public void setWifiState(int wifiState) {
- mWifiState.set(wifiState);
- }
-
- /**
- * The WifiNative interface functions are listed below.
- * The only native call that is not synchronized on
- * WifiStateTracker is waitForEvent() which waits on a
- * seperate monitor channel.
- *
- * All supplicant commands need the wifi to be in an
- * enabled state. This can be done by checking the
- * mWifiState to be WIFI_STATE_ENABLED.
- *
- * All commands that can cause commands to driver
- * initiated need the driver state to be started.
- * This is done by checking isDriverStopped() to
- * be false.
- */
-
/**
- * Load the driver and firmware
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * TODO: doc
*/
- public synchronized boolean loadDriver() {
- return WifiNative.loadDriver();
+ public String getWifiStateByName() {
+ switch (mWifiState.get()) {
+ case WIFI_STATE_DISABLING:
+ return "disabling";
+ case WIFI_STATE_DISABLED:
+ return "disabled";
+ case WIFI_STATE_ENABLING:
+ return "enabling";
+ case WIFI_STATE_ENABLED:
+ return "enabled";
+ case WIFI_STATE_UNKNOWN:
+ return "unknown state";
+ default:
+ return "[invalid state]";
+ }
}
/**
- * Unload the driver and firmware
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * TODO: doc
*/
- public synchronized boolean unloadDriver() {
- return WifiNative.unloadDriver();
+ public int getWifiApState() {
+ return mWifiApState.get();
}
/**
- * Check the supplicant config and
- * start the supplicant daemon
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * TODO: doc
*/
- public synchronized boolean startSupplicant() {
- return WifiNative.startSupplicant();
+ public String getWifiApStateByName() {
+ switch (mWifiApState.get()) {
+ case WIFI_AP_STATE_DISABLING:
+ return "disabling";
+ case WIFI_AP_STATE_DISABLED:
+ return "disabled";
+ case WIFI_AP_STATE_ENABLING:
+ return "enabling";
+ case WIFI_AP_STATE_ENABLED:
+ return "enabled";
+ case WIFI_AP_STATE_FAILED:
+ return "failed";
+ default:
+ return "[invalid state]";
+ }
}
/**
- * Stop the supplicant daemon
+ * Get status information for the current connection, if any.
+ * @return a {@link WifiInfo} object containing information about the current connection
*
- * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean stopSupplicant() {
- return WifiNative.stopSupplicant();
+ public WifiInfo requestConnectionInfo() {
+ return mWifiInfo;
}
- /**
- * Establishes two channels - control channel for commands
- * and monitor channel for notifying WifiMonitor
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- */
- public synchronized boolean connectToSupplicant() {
- return WifiNative.connectToSupplicant();
+ public DhcpInfo getDhcpInfo() {
+ return mDhcpInfo;
}
/**
- * Close the control/monitor channels to supplicant
+ * TODO: doc
*/
- public synchronized void closeSupplicantConnection() {
- WifiNative.closeSupplicantConnection();
+ public void startWifi(boolean enable) {
+ if (enable) {
+ sendMessage(CMD_START_DRIVER);
+ } else {
+ sendMessage(CMD_STOP_DRIVER);
+ }
}
/**
- * Check if the supplicant is alive
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * TODO: doc
*/
- public synchronized boolean ping() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.pingCommand();
+ public void disconnectAndStop() {
+ sendMessage(CMD_DISCONNECT);
+ sendMessage(CMD_STOP_DRIVER);
}
/**
- * initiate an active or passive scan
- *
- * @param forceActive true if it is a active scan
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * TODO: doc
*/
- public synchronized boolean scan(boolean forceActive) {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.scanCommand(forceActive);
+ public void setScanOnlyMode(boolean enable) {
+ if (enable) {
+ sendMessage(obtainMessage(CMD_SET_SCAN_MODE, SCAN_ONLY_MODE, 0));
+ } else {
+ sendMessage(obtainMessage(CMD_SET_SCAN_MODE, CONNECT_MODE, 0));
+ }
}
/**
- * Specifies whether the supplicant or driver
- * take care of initiating scan and doing AP selection
- *
- * @param mode
- * SUPPL_SCAN_HANDLING_NORMAL
- * SUPPL_SCAN_HANDLING_LIST_ONLY
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * TODO: doc
*/
- public synchronized boolean setScanResultHandling(int mode) {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.setScanResultHandlingCommand(mode);
+ public void setScanType(boolean active) {
+ if (active) {
+ sendMessage(obtainMessage(CMD_SET_SCAN_TYPE, SCAN_ACTIVE, 0));
+ } else {
+ sendMessage(obtainMessage(CMD_SET_SCAN_TYPE, SCAN_PASSIVE, 0));
+ }
}
/**
- * Fetch the scan results from the supplicant
- *
- * @return example result string
- * 00:bb:cc:dd:cc:ee 2427 166 [WPA-EAP-TKIP][WPA2-EAP-CCMP] Net1
- * 00:bb:cc:dd:cc:ff 2412 165 [WPA-EAP-TKIP][WPA2-EAP-CCMP] Net2
+ * TODO: doc
*/
- public synchronized String scanResults() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return null;
- }
- return WifiNative.scanResultsCommand();
+ public List<ScanResult> getScanResultsList() {
+ return mScanResults;
}
/**
- * Set the scan mode - active or passive
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * Disconnect from Access Point
*/
- public synchronized boolean setScanMode(boolean isScanModeActive) {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- if (mIsScanModeActive != isScanModeActive) {
- return WifiNative.setScanModeCommand(mIsScanModeActive = isScanModeActive);
- }
- return true;
+ public boolean disconnectCommand() {
+ return sendSyncMessage(CMD_DISCONNECT).boolValue;
}
/**
- * Disconnect from Access Point
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * Initiate a reconnection to AP
*/
- public synchronized boolean disconnect() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.disconnectCommand();
+ public boolean reconnectCommand() {
+ return sendSyncMessage(CMD_RECONNECT).boolValue;
}
/**
- * Initiate a reconnection to AP
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * Initiate a re-association to AP
*/
- public synchronized boolean reconnectCommand() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.reconnectCommand();
+ public boolean reassociateCommand() {
+ return sendSyncMessage(CMD_REASSOCIATE).boolValue;
}
/**
- * Add a network
+ * Add a network synchronously
*
* @return network id of the new network
*/
- public synchronized int addNetwork() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return -1;
- }
- return WifiNative.addNetworkCommand();
+ public int addOrUpdateNetwork(WifiConfiguration config) {
+ return sendSyncMessage(CMD_ADD_OR_UPDATE_NETWORK, config).intValue;
+ }
+
+ public List<WifiConfiguration> getConfiguredNetworks() {
+ return sendSyncMessage(CMD_GET_NETWORK_CONFIG).configList;
}
/**
* Delete a network
*
* @param networkId id of the network to be removed
- * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean removeNetwork(int networkId) {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return mDisconnectExpected = WifiNative.removeNetworkCommand(networkId);
+ public boolean removeNetwork(int networkId) {
+ return sendSyncMessage(obtainMessage(CMD_REMOVE_NETWORK, networkId, 0)).boolValue;
}
+ private class EnableNetParams {
+ private int netId;
+ private boolean disableOthers;
+ EnableNetParams(int n, boolean b) {
+ netId = n;
+ disableOthers = b;
+ }
+ }
/**
* Enable a network
*
@@ -1818,11 +923,9 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* @param disableOthers true, if all other networks have to be disabled
* @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean enableNetwork(int netId, boolean disableOthers) {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.enableNetworkCommand(netId, disableOthers);
+ public boolean enableNetwork(int netId, boolean disableOthers) {
+ return sendSyncMessage(CMD_ENABLE_NETWORK,
+ new EnableNetParams(netId, disableOthers)).boolValue;
}
/**
@@ -1831,23 +934,8 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* @param netId network id of the network
* @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean disableNetwork(int netId) {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.disableNetworkCommand(netId);
- }
-
- /**
- * Initiate a re-association in supplicant
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- */
- public synchronized boolean reassociate() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.reassociateCommand();
+ public boolean disableNetwork(int netId) {
+ return sendSyncMessage(obtainMessage(CMD_DISABLE_NETWORK, netId, 0)).boolValue;
}
/**
@@ -1855,66 +943,17 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* alternate APs to connect
*
* @param bssid BSSID of the network
- * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean addToBlacklist(String bssid) {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.addToBlacklistCommand(bssid);
+ public void addToBlacklist(String bssid) {
+ sendMessage(obtainMessage(CMD_BLACKLIST_NETWORK, bssid));
}
/**
* Clear the blacklist list
*
- * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean clearBlacklist() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.clearBlacklistCommand();
- }
-
- /**
- * List all configured networks
- *
- * @return list of networks or null on failure
- */
- public synchronized String listNetworks() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return null;
- }
- return WifiNative.listNetworksCommand();
- }
-
- /**
- * Get network setting by name
- *
- * @param netId network id of the network
- * @param name network variable key
- * @return value corresponding to key
- */
- public synchronized String getNetworkVariable(int netId, String name) {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return null;
- }
- return WifiNative.getNetworkVariableCommand(netId, name);
- }
-
- /**
- * Set network setting by name
- *
- * @param netId network id of the network
- * @param name network variable key
- * @param value network variable value
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- */
- public synchronized boolean setNetworkVariable(int netId, String name, String value) {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.setNetworkVariableCommand(netId, name, value);
+ public void clearBlacklist() {
+ sendMessage(obtainMessage(CMD_CLEAR_BLACKLIST));
}
/**
@@ -1930,23 +969,20 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* wpa_state=COMPLETED
* ip_address=X.X.X.X
*/
- public synchronized String status() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return null;
- }
- return WifiNative.statusCommand();
+ public String status() {
+ return sendSyncMessage(CMD_CONNECTION_STATUS).stringValue;
}
+ public void enableRssiPolling(boolean enabled) {
+ sendMessage(obtainMessage(CMD_ENABLE_RSSI_POLL, enabled ? 1 : 0, 0));
+ }
/**
* Get RSSI to currently connected network
*
* @return RSSI value, -1 on failure
*/
- public synchronized int getRssi() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return -1;
- }
- return WifiNative.getRssiApproxCommand();
+ public int getRssi() {
+ return sendSyncMessage(CMD_GET_RSSI).intValue;
}
/**
@@ -1954,11 +990,8 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
*
* @return RSSI value, -1 on failure
*/
- public synchronized int getRssiApprox() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return -1;
- }
- return WifiNative.getRssiApproxCommand();
+ public int getRssiApprox() {
+ return sendSyncMessage(CMD_GET_RSSI_APPROX).intValue;
}
/**
@@ -1966,11 +999,8 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
*
* @return link speed, -1 on failure
*/
- public synchronized int getLinkSpeed() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return -1;
- }
- return WifiNative.getLinkSpeedCommand();
+ public int getLinkSpeed() {
+ return sendSyncMessage(CMD_GET_LINK_SPEED).intValue;
}
/**
@@ -1978,72 +1008,22 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
*
* @return MAC address, null on failure
*/
- public synchronized String getMacAddress() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return null;
- }
- return WifiNative.getMacAddressCommand();
- }
-
- /**
- * Start driver
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- */
- public synchronized boolean startDriver() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
- }
- return WifiNative.startDriverCommand();
- }
-
- /**
- * Stop driver
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- */
- public synchronized boolean stopDriver() {
- /* Driver stop should not happen only when supplicant event
- * DRIVER_STOPPED has already been handled */
- if (mWifiState.get() != WIFI_STATE_ENABLED || mRunState == RUN_STATE_STOPPED) {
- return false;
- }
- return WifiNative.stopDriverCommand();
+ public String getMacAddress() {
+ return sendSyncMessage(CMD_GET_MAC_ADDR).stringValue;
}
/**
* Start packet filtering
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean startPacketFiltering() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.startPacketFiltering();
+ public void startPacketFiltering() {
+ sendMessage(CMD_START_PACKET_FILTERING);
}
/**
* Stop packet filtering
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- */
- public synchronized boolean stopPacketFiltering() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.stopPacketFiltering();
- }
-
- /**
- * Get power mode
- * @return power mode
*/
- public synchronized int getPowerMode() {
- if (mWifiState.get() != WIFI_STATE_ENABLED && !isDriverStopped()) {
- return -1;
- }
- return WifiNative.getPowerModeCommand();
+ public void stopPacketFiltering() {
+ sendMessage(CMD_STOP_PACKET_FILTERING);
}
/**
@@ -2051,36 +1031,26 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* @param mode
* DRIVER_POWER_MODE_AUTO
* DRIVER_POWER_MODE_ACTIVE
- * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean setPowerMode(int mode) {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.setPowerModeCommand(mode);
+ public void setPowerMode(int mode) {
+ sendMessage(obtainMessage(CMD_SET_POWER_MODE, mode, 0));
}
/**
* Set the number of allowed radio frequency channels from the system
* setting value, if any.
- * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
- * the number of channels is invalid.
*/
- public synchronized boolean setNumAllowedChannels() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
+ public void setNumAllowedChannels() {
try {
- return setNumAllowedChannels(
+ setNumAllowedChannels(
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.WIFI_NUM_ALLOWED_CHANNELS));
} catch (Settings.SettingNotFoundException e) {
if (mNumAllowedChannels != 0) {
- WifiNative.setNumAllowedChannelsCommand(mNumAllowedChannels);
+ setNumAllowedChannels(mNumAllowedChannels);
}
// otherwise, use the driver default
}
- return true;
}
/**
@@ -2088,27 +1058,21 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* in the current regulatory domain.
* @param numChannels the number of allowed channels. Must be greater than 0
* and less than or equal to 16.
- * @return {@code true} if the operation succeeds, {@code false} otherwise, e.g.,
- * {@code numChannels} is outside the valid range.
*/
- public synchronized boolean setNumAllowedChannels(int numChannels) {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- mNumAllowedChannels = numChannels;
- return WifiNative.setNumAllowedChannelsCommand(numChannels);
+ public void setNumAllowedChannels(int numChannels) {
+ sendMessage(obtainMessage(CMD_SET_NUM_ALLOWED_CHANNELS, numChannels, 0));
}
/**
* Get number of allowed channels
*
* @return channel count, -1 on failure
+ *
+ * TODO: this is not a public API and needs to be removed in favor
+ * of asynchronous reporting. unused for now.
*/
- public synchronized int getNumAllowedChannels() {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return -1;
- }
- return WifiNative.getNumAllowedChannelsCommand();
+ public int getNumAllowedChannels() {
+ return -1;
}
/**
@@ -2118,13 +1082,9 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* BLUETOOTH_COEXISTENCE_MODE_ENABLED
* BLUETOOTH_COEXISTENCE_MODE_DISABLED
* BLUETOOTH_COEXISTENCE_MODE_SENSE
- * @return {@code true} if the operation succeeds, {@code false} otherwise
*/
- public synchronized boolean setBluetoothCoexistenceMode(int mode) {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return false;
- }
- return WifiNative.setBluetoothCoexistenceModeCommand(mode);
+ public void setBluetoothCoexistenceMode(int mode) {
+ sendMessage(obtainMessage(CMD_SET_BLUETOOTH_COEXISTENCE, mode, 0));
}
/**
@@ -2134,75 +1094,292 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
*
* @param isBluetoothPlaying whether to enable or disable this mode
*/
- public synchronized void setBluetoothScanMode(boolean isBluetoothPlaying) {
- if (mWifiState.get() != WIFI_STATE_ENABLED || isDriverStopped()) {
- return;
- }
- WifiNative.setBluetoothCoexistenceScanModeCommand(isBluetoothPlaying);
+ public void setBluetoothScanMode(boolean isBluetoothPlaying) {
+ sendMessage(obtainMessage(CMD_SET_BLUETOOTH_SCAN_MODE, isBluetoothPlaying ? 1 : 0, 0));
}
/**
* Save configuration on supplicant
*
* @return {@code true} if the operation succeeds, {@code false} otherwise
+ *
+ * TODO: deprecate this
*/
- public synchronized boolean saveConfig() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
+ public boolean saveConfig() {
+ return sendSyncMessage(CMD_SAVE_CONFIG).boolValue;
+ }
+
+ /**
+ * TODO: doc
+ */
+ public void requestCmWakeLock() {
+ sendMessage(CMD_REQUEST_CM_WAKELOCK);
+ }
+
+ /*********************************************************
+ * Internal private functions
+ ********************************************************/
+
+ class SyncReturn {
+ boolean boolValue;
+ int intValue;
+ String stringValue;
+ Object objValue;
+ List<WifiConfiguration> configList;
+ }
+
+ class SyncParams {
+ Object mParameter;
+ SyncReturn mSyncReturn;
+ SyncParams() {
+ mSyncReturn = new SyncReturn();
+ }
+ SyncParams(Object p) {
+ mParameter = p;
+ mSyncReturn = new SyncReturn();
}
- return WifiNative.saveConfigCommand();
}
/**
- * Reload the configuration from file
- *
- * @return {@code true} if the operation succeeds, {@code false} otherwise
+ * message.arg2 is reserved to indicate synchronized
+ * message.obj is used to store SyncParams
*/
- public synchronized boolean reloadConfig() {
- if (mWifiState.get() != WIFI_STATE_ENABLED) {
- return false;
+ private SyncReturn syncedSend(Message msg) {
+ SyncParams syncParams = (SyncParams) msg.obj;
+ msg.arg2 = SYNCHRONOUS_CALL;
+ synchronized(syncParams) {
+ if (DBG) Log.d(TAG, "syncedSend " + msg);
+ sendMessage(msg);
+ try {
+ syncParams.wait();
+ } catch (InterruptedException e) {
+ Log.e(TAG, "sendSyncMessage: unexpected interruption of wait()");
+ return null;
+ }
}
- return WifiNative.reloadConfigCommand();
+ return syncParams.mSyncReturn;
}
- public boolean setRadio(boolean turnOn) {
- return mWM.setWifiEnabled(turnOn);
+ private SyncReturn sendSyncMessage(Message msg) {
+ SyncParams syncParams = new SyncParams();
+ msg.obj = syncParams;
+ return syncedSend(msg);
+ }
+
+ private SyncReturn sendSyncMessage(int what, Object param) {
+ SyncParams syncParams = new SyncParams(param);
+ Message msg = obtainMessage(what, syncParams);
+ return syncedSend(msg);
+ }
+
+
+ private SyncReturn sendSyncMessage(int what) {
+ return sendSyncMessage(obtainMessage(what));
+ }
+
+ private void notifyOnMsgObject(Message msg) {
+ SyncParams syncParams = (SyncParams) msg.obj;
+ if (syncParams != null) {
+ synchronized(syncParams) {
+ if (DBG) Log.d(TAG, "notifyOnMsgObject " + msg);
+ syncParams.notify();
+ }
+ }
+ else {
+ Log.e(TAG, "Error! syncParams in notifyOnMsgObject is null");
+ }
+ }
+
+ private void setWifiState(int wifiState) {
+ final int previousWifiState = mWifiState.get();
+
+ try {
+ if (wifiState == WIFI_STATE_ENABLED) {
+ mBatteryStats.noteWifiOn(mLastEnableUid.get());
+ } else if (wifiState == WIFI_STATE_DISABLED) {
+ mBatteryStats.noteWifiOff(mLastEnableUid.get());
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to note battery stats in wifi");
+ }
+
+ mWifiState.set(wifiState);
+
+ if (DBG) Log.d(TAG, "setWifiState: " + getWifiStateByName());
+
+ if (!ActivityManagerNative.isSystemReady()) return;
+
+ final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
+ intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
+ intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
+ intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
+ mContext.sendStickyBroadcast(intent);
+ }
+
+ private void setWifiApState(int wifiApState) {
+ final int previousWifiApState = mWifiApState.get();
+
+ try {
+ if (wifiApState == WIFI_AP_STATE_ENABLED) {
+ mBatteryStats.noteWifiOn(mLastApEnableUid.get());
+ } else if (wifiApState == WIFI_AP_STATE_DISABLED) {
+ mBatteryStats.noteWifiOff(mLastApEnableUid.get());
+ }
+ } catch (RemoteException e) {
+ Log.d(TAG, "Failed to note battery stats in wifi");
+ }
+
+ // Update state
+ mWifiApState.set(wifiApState);
+
+ if (DBG) Log.d(TAG, "setWifiApState: " + getWifiApStateByName());
+
+ // Broadcast
+ if (!ActivityManagerNative.isSystemReady()) return;
+ final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
+ intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
+ intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiApState);
+ intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
+ mContext.sendStickyBroadcast(intent);
}
/**
- * {@inheritDoc}
- * There are currently no Wi-Fi-specific features supported.
- * @param feature the name of the feature
- * @return {@code -1} indicating failure, always
+ * Parse the scan result line passed to us by wpa_supplicant (helper).
+ * @param line the line to parse
+ * @return the {@link ScanResult} object
*/
- public int startUsingNetworkFeature(String feature, int callingPid, int callingUid) {
- return -1;
+ private ScanResult parseScanResult(String line) {
+ ScanResult scanResult = null;
+ if (line != null) {
+ /*
+ * Cache implementation (LinkedHashMap) is not synchronized, thus,
+ * must synchronized here!
+ */
+ synchronized (mScanResultCache) {
+ String[] result = scanResultPattern.split(line);
+ if (3 <= result.length && result.length <= 5) {
+ String bssid = result[0];
+ // bssid | frequency | level | flags | ssid
+ int frequency;
+ int level;
+ try {
+ frequency = Integer.parseInt(result[1]);
+ level = Integer.parseInt(result[2]);
+ /* some implementations avoid negative values by adding 256
+ * so we need to adjust for that here.
+ */
+ if (level > 0) level -= 256;
+ } catch (NumberFormatException e) {
+ frequency = 0;
+ level = 0;
+ }
+
+ /*
+ * The formatting of the results returned by
+ * wpa_supplicant is intended to make the fields
+ * line up nicely when printed,
+ * not to make them easy to parse. So we have to
+ * apply some heuristics to figure out which field
+ * is the SSID and which field is the flags.
+ */
+ String ssid;
+ String flags;
+ if (result.length == 4) {
+ if (result[3].charAt(0) == '[') {
+ flags = result[3];
+ ssid = "";
+ } else {
+ flags = "";
+ ssid = result[3];
+ }
+ } else if (result.length == 5) {
+ flags = result[3];
+ ssid = result[4];
+ } else {
+ // Here, we must have 3 fields: no flags and ssid
+ // set
+ flags = "";
+ ssid = "";
+ }
+
+ // bssid + ssid is the hash key
+ String key = bssid + ssid;
+ scanResult = mScanResultCache.get(key);
+ if (scanResult != null) {
+ scanResult.level = level;
+ scanResult.SSID = ssid;
+ scanResult.capabilities = flags;
+ scanResult.frequency = frequency;
+ } else {
+ // Do not add scan results that have no SSID set
+ if (0 < ssid.trim().length()) {
+ scanResult =
+ new ScanResult(
+ ssid, bssid, flags, level, frequency);
+ mScanResultCache.put(key, scanResult);
+ }
+ }
+ } else {
+ Log.w(TAG, "Misformatted scan result text with " +
+ result.length + " fields: " + line);
+ }
+ }
+ }
+
+ return scanResult;
}
/**
- * {@inheritDoc}
- * There are currently no Wi-Fi-specific features supported.
- * @param feature the name of the feature
- * @return {@code -1} indicating failure, always
+ * scanResults input format
+ * 00:bb:cc:dd:cc:ee 2427 166 [WPA-EAP-TKIP][WPA2-EAP-CCMP] Net1
+ * 00:bb:cc:dd:cc:ff 2412 165 [WPA-EAP-TKIP][WPA2-EAP-CCMP] Net2
*/
- public int stopUsingNetworkFeature(String feature, int callingPid, int callingUid) {
- return -1;
- }
+ private void setScanResults(String scanResults) {
+ if (scanResults == null) {
+ return;
+ }
- public void interpretScanResultsAvailable() {
+ List<ScanResult> scanList = new ArrayList<ScanResult>();
+
+ int lineCount = 0;
+
+ int scanResultsLen = scanResults.length();
+ // Parse the result string, keeping in mind that the last line does
+ // not end with a newline.
+ for (int lineBeg = 0, lineEnd = 0; lineEnd <= scanResultsLen; ++lineEnd) {
+ if (lineEnd == scanResultsLen || scanResults.charAt(lineEnd) == '\n') {
+ ++lineCount;
+
+ if (lineCount == 1) {
+ lineBeg = lineEnd + 1;
+ continue;
+ }
+ if (lineEnd > lineBeg) {
+ String line = scanResults.substring(lineBeg, lineEnd);
+ ScanResult scanResult = parseScanResult(line);
+ if (scanResult != null) {
+ scanList.add(scanResult);
+ } else {
+ Log.w(TAG, "misformatted scan result for: " + line);
+ }
+ }
+ lineBeg = lineEnd + 1;
+ }
+ }
+
+ mScanResults = scanList;
+ }
+ private void checkAndSetNotification() {
// If we shouldn't place a notification on available networks, then
// don't bother doing any of the following
if (!mNotificationEnabled) return;
- NetworkInfo networkInfo = getNetworkInfo();
-
- State state = networkInfo.getState();
+ State state = mNetworkInfo.getState();
if ((state == NetworkInfo.State.DISCONNECTED)
|| (state == NetworkInfo.State.UNKNOWN)) {
-
// Look for an open network
- List<ScanResult> scanResults = getScanResultsList();
+ List<ScanResult> scanResults = mScanResults;
if (scanResults != null) {
int numOpenNetworks = 0;
for (int i = scanResults.size() - 1; i >= 0; i--) {
@@ -2212,7 +1389,7 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
numOpenNetworks++;
}
}
-
+
if (numOpenNetworks > 0) {
if (++mNumScansSinceNetworkStateChange >= NUM_SCANS_BEFORE_ACTUALLY_SCANNING) {
/*
@@ -2228,21 +1405,12 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
}
}
}
-
+
// No open networks in range, remove the notification
setNotificationVisible(false, 0, false, 0);
}
/**
- * Send a notification that the results of a scan for network access
- * points has completed, and results are available.
- */
- private void sendScanResultsAvailable() {
- Message msg = mTarget.obtainMessage(EVENT_SCAN_RESULTS_AVAILABLE, mNetworkInfo);
- msg.sendToTarget();
- }
-
- /**
* Display or don't display a notification that there are open Wi-Fi networks.
* @param visible {@code true} if notification should be visible, {@code false} otherwise
* @param numNetworks the number networks seen
@@ -2251,14 +1419,15 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
* @param delay time in milliseconds after which the notification should be made
* visible or invisible.
*/
- public void setNotificationVisible(boolean visible, int numNetworks, boolean force, int delay) {
-
+ private void setNotificationVisible(boolean visible, int numNetworks, boolean force,
+ int delay) {
+
// Since we use auto cancel on the notification, when the
// mNetworksAvailableNotificationShown is true, the notification may
// have actually been canceled. However, when it is false we know
// for sure that it is not being shown (it will not be shown any other
// place than here)
-
+
// If it should be hidden and it is already hidden, then noop
if (!visible && !mNotificationShown && !force) {
return;
@@ -2266,12 +1435,12 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
Message message;
if (visible) {
-
+
// Not enough time has passed to show the notification again
if (System.currentTimeMillis() < mNotificationRepeatTime) {
return;
}
-
+
if (mNotification == null) {
// Cache the Notification mainly so we can remove the
// EVENT_NOTIFICATION_CHANGED message with this Notification from
@@ -2290,184 +1459,69 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
com.android.internal.R.plurals.wifi_available_detailed, numNetworks);
mNotification.tickerText = title;
mNotification.setLatestEventInfo(mContext, title, details, mNotification.contentIntent);
-
+
mNotificationRepeatTime = System.currentTimeMillis() + NOTIFICATION_REPEAT_DELAY_MS;
- message = mTarget.obtainMessage(EVENT_NOTIFICATION_CHANGED, 1,
+ message = mCsHandler.obtainMessage(EVENT_NOTIFICATION_CHANGED, 1,
ICON_NETWORKS_AVAILABLE, mNotification);
-
+
} else {
// Remove any pending messages to show the notification
- mTarget.removeMessages(EVENT_NOTIFICATION_CHANGED, mNotification);
-
- message = mTarget.obtainMessage(EVENT_NOTIFICATION_CHANGED, 0, ICON_NETWORKS_AVAILABLE);
+ mCsHandler.removeMessages(EVENT_NOTIFICATION_CHANGED, mNotification);
+
+ message = mCsHandler.obtainMessage(EVENT_NOTIFICATION_CHANGED, 0,
+ ICON_NETWORKS_AVAILABLE);
}
- mTarget.sendMessageDelayed(message, delay);
-
- mNotificationShown = visible;
- }
+ mCsHandler.sendMessageDelayed(message, delay);
- /**
- * Clears variables related to tracking whether a notification has been
- * shown recently.
- * <p>
- * After calling this method, the timer that prevents notifications from
- * being shown too often will be cleared.
- */
- private void resetNotificationTimer() {
- mNotificationRepeatTime = 0;
- mNumScansSinceNetworkStateChange = 0;
+ mNotificationShown = visible;
}
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
-
- sb.append(mNetworkProperties.toString());
- sb.append(" runState=");
- if (mRunState >= 1 && mRunState <= mRunStateNames.length) {
- sb.append(mRunStateNames[mRunState-1]);
- } else {
- sb.append(mRunState);
+ private void configureNetworkProperties() {
+ try {
+ mNetworkProperties.setInterface(NetworkInterface.getByName(mInterfaceName));
+ } catch (SocketException e) {
+ Log.e(TAG, "SocketException creating NetworkInterface from " + mInterfaceName +
+ ". e=" + e);
+ return;
+ } catch (NullPointerException e) {
+ Log.e(TAG, "NPE creating NetworkInterface. e=" + e);
+ return;
}
- sb.append(LS).append(mWifiInfo).append(LS);
- sb.append(mDhcpInfo).append(LS);
- sb.append("haveIpAddress=").append(mHaveIpAddress).
- append(", obtainingIpAddress=").append(mObtainingIpAddress).
- append(", scanModeActive=").append(mIsScanModeActive).append(LS).
- append("lastSignalLevel=").append(mLastSignalLevel).
- append(", explicitlyDisabled=").append(mTornDownByConnMgr);
- return sb.toString();
- }
-
- private class DhcpHandler extends Handler {
-
- private Handler mTarget;
-
- /**
- * Whether to skip the DHCP result callback to the target. For example,
- * this could be set if the network we were requesting an IP for has
- * since been disconnected.
- * <p>
- * Note: There is still a chance where the client's intended DHCP
- * request not being canceled. For example, we are request for IP on
- * A, and he queues request for IP on B, and then cancels the request on
- * B while we're still requesting from A.
- */
- private boolean mCancelCallback;
-
- /**
- * Instance of the bluetooth headset helper. This needs to be created
- * early because there is a delay before it actually 'connects', as
- * noted by its javadoc. If we check before it is connected, it will be
- * in an error state and we will not disable coexistence.
- */
- private BluetoothHeadset mBluetoothHeadset;
-
- public DhcpHandler(Looper looper, Handler target) {
- super(looper);
- mTarget = target;
-
- mBluetoothHeadset = new BluetoothHeadset(mContext, null);
+ // TODO - fix this for v6
+ try {
+ mNetworkProperties.addAddress(InetAddress.getByAddress(
+ NetworkUtils.v4IntToArray(mDhcpInfo.ipAddress)));
+ } catch (UnknownHostException e) {
+ Log.e(TAG, "Exception setting IpAddress using " + mDhcpInfo + ", e=" + e);
}
- public void handleMessage(Message msg) {
- int event;
-
- switch (msg.what) {
- case EVENT_DHCP_START:
-
- boolean modifiedBluetoothCoexistenceMode = false;
- int powerMode = DRIVER_POWER_MODE_AUTO;
-
- if (shouldDisableCoexistenceMode()) {
- /*
- * There are problems setting the Wi-Fi driver's power
- * mode to active when bluetooth coexistence mode is
- * enabled or sense.
- * <p>
- * We set Wi-Fi to active mode when
- * obtaining an IP address because we've found
- * compatibility issues with some routers with low power
- * mode.
- * <p>
- * In order for this active power mode to properly be set,
- * we disable coexistence mode until we're done with
- * obtaining an IP address. One exception is if we
- * are currently connected to a headset, since disabling
- * coexistence would interrupt that connection.
- */
- modifiedBluetoothCoexistenceMode = true;
-
- // Disable the coexistence mode
- setBluetoothCoexistenceMode(
- WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
- }
-
- powerMode = getPowerMode();
- if (powerMode < 0) {
- // Handle the case where supplicant driver does not support
- // getPowerModeCommand.
- powerMode = DRIVER_POWER_MODE_AUTO;
- }
- if (powerMode != DRIVER_POWER_MODE_ACTIVE) {
- setPowerMode(DRIVER_POWER_MODE_ACTIVE);
- }
-
- synchronized (this) {
- // A new request is being made, so assume we will callback
- mCancelCallback = false;
- }
- Log.d(TAG, "DhcpHandler: DHCP request started");
- if (NetworkUtils.runDhcp(mInterfaceName, mDhcpInfo)) {
- event = EVENT_INTERFACE_CONFIGURATION_SUCCEEDED;
- if (LOCAL_LOGD) Log.v(TAG, "DhcpHandler: DHCP request succeeded");
- } else {
- event = EVENT_INTERFACE_CONFIGURATION_FAILED;
- Log.i(TAG, "DhcpHandler: DHCP request failed: " +
- NetworkUtils.getDhcpError());
- }
-
- if (powerMode != DRIVER_POWER_MODE_ACTIVE) {
- setPowerMode(powerMode);
- }
-
- if (modifiedBluetoothCoexistenceMode) {
- // Set the coexistence mode back to its default value
- setBluetoothCoexistenceMode(
- WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
- }
-
- synchronized (this) {
- if (!mCancelCallback) {
- mTarget.sendEmptyMessage(event);
- }
- }
- break;
- }
+ try {
+ mNetworkProperties.setGateway(InetAddress.getByAddress(NetworkUtils.v4IntToArray(
+ mDhcpInfo.gateway)));
+ } catch (UnknownHostException e) {
+ Log.e(TAG, "Exception setting Gateway using " + mDhcpInfo + ", e=" + e);
}
- public synchronized void setCancelCallback(boolean cancelCallback) {
- mCancelCallback = cancelCallback;
+ try {
+ mNetworkProperties.addDns(InetAddress.getByAddress(
+ NetworkUtils.v4IntToArray(mDhcpInfo.dns1)));
+ } catch (UnknownHostException e) {
+ Log.e(TAG, "Exception setting Dns1 using " + mDhcpInfo + ", e=" + e);
}
+ try {
+ mNetworkProperties.addDns(InetAddress.getByAddress(
+ NetworkUtils.v4IntToArray(mDhcpInfo.dns2)));
- /**
- * Whether to disable coexistence mode while obtaining IP address. This
- * logic will return true only if the current bluetooth
- * headset/handsfree state is disconnected. This means if it is in an
- * error state, we will NOT disable coexistence mode to err on the side
- * of safety.
- *
- * @return Whether to disable coexistence mode.
- */
- private boolean shouldDisableCoexistenceMode() {
- int state = mBluetoothHeadset.getState(mBluetoothHeadset.getCurrentHeadset());
- return state == BluetoothHeadset.STATE_DISCONNECTED;
+ } catch (UnknownHostException e) {
+ Log.e(TAG, "Exception setting Dns2 using " + mDhcpInfo + ", e=" + e);
}
+ // TODO - add proxy info
}
-
+
+
private void checkUseStaticIp() {
mUseStaticIp = false;
final ContentResolver cr = mContext.getContentResolver();
@@ -2558,6 +1612,7 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
Settings.System.WIFI_STATIC_DNS2), false, this);
}
+ @Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
@@ -2587,15 +1642,2304 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
oDns2 != mDhcpInfo.dns2));
if (changed) {
- resetConnections(true);
- configureInterface();
+ sendMessage(CMD_RECONFIGURE_IP);
if (mUseStaticIp) {
- mTarget.sendEmptyMessage(EVENT_CONFIGURATION_CHANGED);
+ mCsHandler.sendEmptyMessage(EVENT_CONFIGURATION_CHANGED);
}
}
}
}
+
+ /**
+ * Clears variables related to tracking whether a notification has been
+ * shown recently.
+ * <p>
+ * After calling this method, the timer that prevents notifications from
+ * being shown too often will be cleared.
+ */
+ private void resetNotificationTimer() {
+ mNotificationRepeatTime = 0;
+ mNumScansSinceNetworkStateChange = 0;
+ }
+
+
+ /**
+ * Whether to disable coexistence mode while obtaining IP address. This
+ * logic will return true only if the current bluetooth
+ * headset/handsfree state is disconnected. This means if it is in an
+ * error state, we will NOT disable coexistence mode to err on the side
+ * of safety.
+ *
+ * @return Whether to disable coexistence mode.
+ */
+ private boolean shouldDisableCoexistenceMode() {
+ int state = mBluetoothHeadset.getState(mBluetoothHeadset.getCurrentHeadset());
+ return state == BluetoothHeadset.STATE_DISCONNECTED;
+ }
+
+ private void checkIsBluetoothPlaying() {
+ boolean isBluetoothPlaying = false;
+ Set<BluetoothDevice> connected = mBluetoothA2dp.getConnectedSinks();
+
+ for (BluetoothDevice device : connected) {
+ if (mBluetoothA2dp.getSinkState(device) == BluetoothA2dp.STATE_PLAYING) {
+ isBluetoothPlaying = true;
+ break;
+ }
+ }
+ setBluetoothScanMode(isBluetoothPlaying);
+ }
+
+ private void sendScanResultsAvailableBroadcast() {
+ if (!ActivityManagerNative.isSystemReady()) return;
+
+ mContext.sendBroadcast(new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
+ }
+
+ private void sendRssiChangeBroadcast(final int newRssi) {
+ if (!ActivityManagerNative.isSystemReady()) return;
+
+ Intent intent = new Intent(WifiManager.RSSI_CHANGED_ACTION);
+ intent.putExtra(WifiManager.EXTRA_NEW_RSSI, newRssi);
+ mContext.sendBroadcast(intent);
+ }
+
+ private void sendNetworkStateChangeBroadcast(String bssid) {
+ if (!ActivityManagerNative.isSystemReady()) return;
+
+ Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION);
+ intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
+ | Intent.FLAG_RECEIVER_REPLACE_PENDING);
+ intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, mNetworkInfo);
+ if (bssid != null)
+ intent.putExtra(WifiManager.EXTRA_BSSID, bssid);
+ mContext.sendStickyBroadcast(intent);
+ }
+
+ private void sendSupplicantStateChangedBroadcast(StateChangeResult sc, boolean failedAuth) {
+ if (!ActivityManagerNative.isSystemReady()) return;
+
+ Intent intent = new Intent(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
+ intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
+ | Intent.FLAG_RECEIVER_REPLACE_PENDING);
+ intent.putExtra(WifiManager.EXTRA_NEW_STATE, (Parcelable)sc.state);
+ if (failedAuth) {
+ intent.putExtra(
+ WifiManager.EXTRA_SUPPLICANT_ERROR,
+ WifiManager.ERROR_AUTHENTICATING);
+ }
+ mContext.sendStickyBroadcast(intent);
+ }
+
+ private void sendSupplicantConnectionChangedBroadcast(boolean connected) {
+ if (!ActivityManagerNative.isSystemReady()) return;
+
+ Intent intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
+ intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, connected);
+ mContext.sendBroadcast(intent);
+ }
+
+ /**
+ * Record the detailed state of a network, and if it is a
+ * change from the previous state, send a notification to
+ * any listeners.
+ * @param state the new @{code DetailedState}
+ */
+ private void setDetailedState(NetworkInfo.DetailedState state) {
+ Log.d(TAG, "setDetailed state, old ="
+ + mNetworkInfo.getDetailedState() + " and new state=" + state);
+ if (state != mNetworkInfo.getDetailedState()) {
+ mNetworkInfo.setDetailedState(state, null, null);
+ Message msg = mCsHandler.obtainMessage(EVENT_STATE_CHANGED, mNetworkInfo);
+ msg.sendToTarget();
+ }
+ }
+
+ private static String removeDoubleQuotes(String string) {
+ if (string.length() <= 2) return "";
+ return string.substring(1, string.length() - 1);
+ }
+
+ private static String convertToQuotedString(String string) {
+ return "\"" + string + "\"";
+ }
+
+ private static String makeString(BitSet set, String[] strings) {
+ StringBuffer buf = new StringBuffer();
+ int nextSetBit = -1;
+
+ /* Make sure all set bits are in [0, strings.length) to avoid
+ * going out of bounds on strings. (Shouldn't happen, but...) */
+ set = set.get(0, strings.length);
+
+ while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
+ buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
+ }
+
+ // remove trailing space
+ if (set.cardinality() > 0) {
+ buf.setLength(buf.length() - 1);
+ }
+
+ return buf.toString();
+ }
+
+ private static int lookupString(String string, String[] strings) {
+ int size = strings.length;
+
+ string = string.replace('-', '_');
+
+ for (int i = 0; i < size; i++)
+ if (string.equals(strings[i]))
+ return i;
+
+ // if we ever get here, we should probably add the
+ // value to WifiConfiguration to reflect that it's
+ // supported by the WPA supplicant
+ Log.w(TAG, "Failed to look-up a string: " + string);
+
+ return -1;
+ }
+
+ private int addOrUpdateNetworkNative(WifiConfiguration config) {
+ /*
+ * If the supplied networkId is -1, we create a new empty
+ * network configuration. Otherwise, the networkId should
+ * refer to an existing configuration.
+ */
+ int netId = config.networkId;
+ boolean newNetwork = netId == -1;
+ // networkId of -1 means we want to create a new network
+
+ if (newNetwork) {
+ netId = WifiNative.addNetworkCommand();
+ if (netId < 0) {
+ Log.e(TAG, "Failed to add a network!");
+ return -1;
+ }
+ }
+
+ setVariables: {
+
+ if (config.SSID != null &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.ssidVarName,
+ config.SSID)) {
+ Log.d(TAG, "failed to set SSID: "+config.SSID);
+ break setVariables;
+ }
+
+ if (config.BSSID != null &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.bssidVarName,
+ config.BSSID)) {
+ Log.d(TAG, "failed to set BSSID: "+config.BSSID);
+ break setVariables;
+ }
+
+ String allowedKeyManagementString =
+ makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
+ if (config.allowedKeyManagement.cardinality() != 0 &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.KeyMgmt.varName,
+ allowedKeyManagementString)) {
+ Log.d(TAG, "failed to set key_mgmt: "+
+ allowedKeyManagementString);
+ break setVariables;
+ }
+
+ String allowedProtocolsString =
+ makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
+ if (config.allowedProtocols.cardinality() != 0 &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.Protocol.varName,
+ allowedProtocolsString)) {
+ Log.d(TAG, "failed to set proto: "+
+ allowedProtocolsString);
+ break setVariables;
+ }
+
+ String allowedAuthAlgorithmsString =
+ makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
+ if (config.allowedAuthAlgorithms.cardinality() != 0 &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.AuthAlgorithm.varName,
+ allowedAuthAlgorithmsString)) {
+ Log.d(TAG, "failed to set auth_alg: "+
+ allowedAuthAlgorithmsString);
+ break setVariables;
+ }
+
+ String allowedPairwiseCiphersString =
+ makeString(config.allowedPairwiseCiphers,
+ WifiConfiguration.PairwiseCipher.strings);
+ if (config.allowedPairwiseCiphers.cardinality() != 0 &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.PairwiseCipher.varName,
+ allowedPairwiseCiphersString)) {
+ Log.d(TAG, "failed to set pairwise: "+
+ allowedPairwiseCiphersString);
+ break setVariables;
+ }
+
+ String allowedGroupCiphersString =
+ makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
+ if (config.allowedGroupCiphers.cardinality() != 0 &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.GroupCipher.varName,
+ allowedGroupCiphersString)) {
+ Log.d(TAG, "failed to set group: "+
+ allowedGroupCiphersString);
+ break setVariables;
+ }
+
+ // Prevent client screw-up by passing in a WifiConfiguration we gave it
+ // by preventing "*" as a key.
+ if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
+ !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.pskVarName,
+ config.preSharedKey)) {
+ Log.d(TAG, "failed to set psk: "+config.preSharedKey);
+ break setVariables;
+ }
+
+ boolean hasSetKey = false;
+ if (config.wepKeys != null) {
+ for (int i = 0; i < config.wepKeys.length; i++) {
+ // Prevent client screw-up by passing in a WifiConfiguration we gave it
+ // by preventing "*" as a key.
+ if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
+ if (!WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.wepKeyVarNames[i],
+ config.wepKeys[i])) {
+ Log.d(TAG,
+ "failed to set wep_key"+i+": " +
+ config.wepKeys[i]);
+ break setVariables;
+ }
+ hasSetKey = true;
+ }
+ }
+ }
+
+ if (hasSetKey) {
+ if (!WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.wepTxKeyIdxVarName,
+ Integer.toString(config.wepTxKeyIndex))) {
+ Log.d(TAG,
+ "failed to set wep_tx_keyidx: "+
+ config.wepTxKeyIndex);
+ break setVariables;
+ }
+ }
+
+ if (!WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.priorityVarName,
+ Integer.toString(config.priority))) {
+ Log.d(TAG, config.SSID + ": failed to set priority: "
+ +config.priority);
+ break setVariables;
+ }
+
+ if (config.hiddenSSID && !WifiNative.setNetworkVariableCommand(
+ netId,
+ WifiConfiguration.hiddenSSIDVarName,
+ Integer.toString(config.hiddenSSID ? 1 : 0))) {
+ Log.d(TAG, config.SSID + ": failed to set hiddenSSID: "+
+ config.hiddenSSID);
+ break setVariables;
+ }
+
+ for (WifiConfiguration.EnterpriseField field
+ : config.enterpriseFields) {
+ String varName = field.varName();
+ String value = field.value();
+ if (value != null) {
+ if (field != config.eap) {
+ value = (value.length() == 0) ? "NULL" : convertToQuotedString(value);
+ }
+ if (!WifiNative.setNetworkVariableCommand(
+ netId,
+ varName,
+ value)) {
+ Log.d(TAG, config.SSID + ": failed to set " + varName +
+ ": " + value);
+ break setVariables;
+ }
+ }
+ }
+ return netId;
+ }
+
+ if (newNetwork) {
+ WifiNative.removeNetworkCommand(netId);
+ Log.d(TAG,
+ "Failed to set a network variable, removed network: "
+ + netId);
+ }
+
+ return -1;
+ }
+
+ private List<WifiConfiguration> getConfiguredNetworksNative() {
+ String listStr = WifiNative.listNetworksCommand();
+
+ List<WifiConfiguration> networks =
+ new ArrayList<WifiConfiguration>();
+ if (listStr == null)
+ return networks;
+
+ String[] lines = listStr.split("\n");
+ // Skip the first line, which is a header
+ for (int i = 1; i < lines.length; i++) {
+ String[] result = lines[i].split("\t");
+ // network-id | ssid | bssid | flags
+ WifiConfiguration config = new WifiConfiguration();
+ try {
+ config.networkId = Integer.parseInt(result[0]);
+ } catch(NumberFormatException e) {
+ continue;
+ }
+ if (result.length > 3) {
+ if (result[3].indexOf("[CURRENT]") != -1)
+ config.status = WifiConfiguration.Status.CURRENT;
+ else if (result[3].indexOf("[DISABLED]") != -1)
+ config.status = WifiConfiguration.Status.DISABLED;
+ else
+ config.status = WifiConfiguration.Status.ENABLED;
+ } else {
+ config.status = WifiConfiguration.Status.ENABLED;
+ }
+ readNetworkVariables(config);
+ networks.add(config);
+ }
+ return networks;
+ }
+
+ /**
+ * Read the variables from the supplicant daemon that are needed to
+ * fill in the WifiConfiguration object.
+ *
+ * @param config the {@link WifiConfiguration} object to be filled in.
+ */
+ private void readNetworkVariables(WifiConfiguration config) {
+
+ int netId = config.networkId;
+ if (netId < 0)
+ return;
+
+ /*
+ * TODO: maybe should have a native method that takes an array of
+ * variable names and returns an array of values. But we'd still
+ * be doing a round trip to the supplicant daemon for each variable.
+ */
+ String value;
+
+ value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.ssidVarName);
+ if (!TextUtils.isEmpty(value)) {
+ config.SSID = removeDoubleQuotes(value);
+ } else {
+ config.SSID = null;
+ }
+
+ value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.bssidVarName);
+ if (!TextUtils.isEmpty(value)) {
+ config.BSSID = value;
+ } else {
+ config.BSSID = null;
+ }
+
+ value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.priorityVarName);
+ config.priority = -1;
+ if (!TextUtils.isEmpty(value)) {
+ try {
+ config.priority = Integer.parseInt(value);
+ } catch (NumberFormatException ignore) {
+ }
+ }
+
+ value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.hiddenSSIDVarName);
+ config.hiddenSSID = false;
+ if (!TextUtils.isEmpty(value)) {
+ try {
+ config.hiddenSSID = Integer.parseInt(value) != 0;
+ } catch (NumberFormatException ignore) {
+ }
+ }
+
+ value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.wepTxKeyIdxVarName);
+ config.wepTxKeyIndex = -1;
+ if (!TextUtils.isEmpty(value)) {
+ try {
+ config.wepTxKeyIndex = Integer.parseInt(value);
+ } catch (NumberFormatException ignore) {
+ }
+ }
+
+ for (int i = 0; i < 4; i++) {
+ value = WifiNative.getNetworkVariableCommand(netId,
+ WifiConfiguration.wepKeyVarNames[i]);
+ if (!TextUtils.isEmpty(value)) {
+ config.wepKeys[i] = value;
+ } else {
+ config.wepKeys[i] = null;
+ }
+ }
+
+ value = WifiNative.getNetworkVariableCommand(netId, WifiConfiguration.pskVarName);
+ if (!TextUtils.isEmpty(value)) {
+ config.preSharedKey = value;
+ } else {
+ config.preSharedKey = null;
+ }
+
+ value = WifiNative.getNetworkVariableCommand(config.networkId,
+ WifiConfiguration.Protocol.varName);
+ if (!TextUtils.isEmpty(value)) {
+ String vals[] = value.split(" ");
+ for (String val : vals) {
+ int index =
+ lookupString(val, WifiConfiguration.Protocol.strings);
+ if (0 <= index) {
+ config.allowedProtocols.set(index);
+ }
+ }
+ }
+
+ value = WifiNative.getNetworkVariableCommand(config.networkId,
+ WifiConfiguration.KeyMgmt.varName);
+ if (!TextUtils.isEmpty(value)) {
+ String vals[] = value.split(" ");
+ for (String val : vals) {
+ int index =
+ lookupString(val, WifiConfiguration.KeyMgmt.strings);
+ if (0 <= index) {
+ config.allowedKeyManagement.set(index);
+ }
+ }
+ }
+
+ value = WifiNative.getNetworkVariableCommand(config.networkId,
+ WifiConfiguration.AuthAlgorithm.varName);
+ if (!TextUtils.isEmpty(value)) {
+ String vals[] = value.split(" ");
+ for (String val : vals) {
+ int index =
+ lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
+ if (0 <= index) {
+ config.allowedAuthAlgorithms.set(index);
+ }
+ }
+ }
+
+ value = WifiNative.getNetworkVariableCommand(config.networkId,
+ WifiConfiguration.PairwiseCipher.varName);
+ if (!TextUtils.isEmpty(value)) {
+ String vals[] = value.split(" ");
+ for (String val : vals) {
+ int index =
+ lookupString(val, WifiConfiguration.PairwiseCipher.strings);
+ if (0 <= index) {
+ config.allowedPairwiseCiphers.set(index);
+ }
+ }
+ }
+
+ value = WifiNative.getNetworkVariableCommand(config.networkId,
+ WifiConfiguration.GroupCipher.varName);
+ if (!TextUtils.isEmpty(value)) {
+ String vals[] = value.split(" ");
+ for (String val : vals) {
+ int index =
+ lookupString(val, WifiConfiguration.GroupCipher.strings);
+ if (0 <= index) {
+ config.allowedGroupCiphers.set(index);
+ }
+ }
+ }
+
+ for (WifiConfiguration.EnterpriseField field :
+ config.enterpriseFields) {
+ value = WifiNative.getNetworkVariableCommand(netId,
+ field.varName());
+ if (!TextUtils.isEmpty(value)) {
+ if (field != config.eap) value = removeDoubleQuotes(value);
+ field.setValue(value);
+ }
+ }
+
+ }
+
+ /**
+ * Poll for info not reported via events
+ * RSSI & Linkspeed
+ */
+ private void requestPolledInfo() {
+ int newRssi = WifiNative.getRssiCommand();
+ if (newRssi != -1 && -200 < newRssi && newRssi < 256) { // screen out invalid values
+ /* some implementations avoid negative values by adding 256
+ * so we need to adjust for that here.
+ */
+ if (newRssi > 0) newRssi -= 256;
+ mWifiInfo.setRssi(newRssi);
+ /*
+ * Rather then sending the raw RSSI out every time it
+ * changes, we precalculate the signal level that would
+ * be displayed in the status bar, and only send the
+ * broadcast if that much more coarse-grained number
+ * changes. This cuts down greatly on the number of
+ * broadcasts, at the cost of not mWifiInforming others
+ * interested in RSSI of all the changes in signal
+ * level.
+ */
+ // TODO: The second arg to the call below needs to be a symbol somewhere, but
+ // it's actually the size of an array of icons that's private
+ // to StatusBar Policy.
+ int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, 4);
+ if (newSignalLevel != mLastSignalLevel) {
+ sendRssiChangeBroadcast(newRssi);
+ }
+ mLastSignalLevel = newSignalLevel;
+ } else {
+ mWifiInfo.setRssi(-200);
+ }
+ int newLinkSpeed = WifiNative.getLinkSpeedCommand();
+ if (newLinkSpeed != -1) {
+ mWifiInfo.setLinkSpeed(newLinkSpeed);
+ }
+ }
+
+ /**
+ * Resets the Wi-Fi Connections by clearing any state, resetting any sockets
+ * using the interface, stopping DHCP & disabling interface
+ */
+ private void handleNetworkDisconnect() {
+ Log.d(TAG, "Reset connections and stopping DHCP");
+
+ /*
+ * Reset connections & stop DHCP
+ */
+ NetworkUtils.resetConnections(mInterfaceName);
+
+ if (!NetworkUtils.stopDhcp(mInterfaceName)) {
+ Log.e(TAG, "Could not stop DHCP");
+ }
+
+ /* Disable interface */
+ NetworkUtils.disableInterface(mInterfaceName);
+
+ /* send event to CM & network change broadcast */
+ setDetailedState(DetailedState.DISCONNECTED);
+ sendNetworkStateChangeBroadcast(mLastBssid);
+
+ /* Reset data structures */
+ mWifiInfo.setIpAddress(0);
+ mWifiInfo.setBSSID(null);
+ mWifiInfo.setSSID(null);
+ mWifiInfo.setNetworkId(-1);
+
+ /* Clear network properties */
+ mNetworkProperties.clear();
+
+ mLastBssid= null;
+ mLastNetworkId = -1;
+
+ }
+
+
+ /*********************************************************
+ * Notifications from WifiMonitor
+ ********************************************************/
+
+ /**
+ * A structure for supplying information about a supplicant state
+ * change in the STATE_CHANGE event message that comes from the
+ * WifiMonitor
+ * thread.
+ */
+ private static class StateChangeResult {
+ StateChangeResult(int networkId, String BSSID, Object state) {
+ this.state = state;
+ this.BSSID = BSSID;
+ this.networkId = networkId;
+ }
+ int networkId;
+ String BSSID;
+ Object state;
+ }
+
+ /**
+ * Send the tracker a notification that a user-entered password key
+ * may be incorrect (i.e., caused authentication to fail).
+ */
+ void notifyPasswordKeyMayBeIncorrect() {
+ sendMessage(PASSWORD_MAY_BE_INCORRECT_EVENT);
+ }
+
+ /**
+ * Send the tracker a notification that a connection to the supplicant
+ * daemon has been established.
+ */
+ void notifySupplicantConnection() {
+ sendMessage(SUP_CONNECTION_EVENT);
+ }
+
+ /**
+ * Send the tracker a notification that a connection to the supplicant
+ * daemon has been established.
+ */
+ void notifySupplicantLost() {
+ sendMessage(SUP_DISCONNECTION_EVENT);
+ }
+
+ /**
+ * Send the tracker a notification that the state of Wifi connectivity
+ * has changed.
+ * @param networkId the configured network on which the state change occurred
+ * @param newState the new network state
+ * @param BSSID when the new state is {@link DetailedState#CONNECTED
+ * NetworkInfo.DetailedState.CONNECTED},
+ * this is the MAC address of the access point. Otherwise, it
+ * is {@code null}.
+ */
+ void notifyNetworkStateChange(DetailedState newState, String BSSID, int networkId) {
+ if (newState == NetworkInfo.DetailedState.CONNECTED) {
+ sendMessage(obtainMessage(NETWORK_CONNECTION_EVENT,
+ new StateChangeResult(networkId, BSSID, newState)));
+ } else {
+ sendMessage(obtainMessage(NETWORK_DISCONNECTION_EVENT,
+ new StateChangeResult(networkId, BSSID, newState)));
+ }
+ }
+
+ /**
+ * Send the tracker a notification that the state of the supplicant
+ * has changed.
+ * @param networkId the configured network on which the state change occurred
+ * @param newState the new {@code SupplicantState}
+ */
+ void notifySupplicantStateChange(int networkId, String BSSID, SupplicantState newState) {
+ sendMessage(obtainMessage(SUPPLICANT_STATE_CHANGE_EVENT,
+ new StateChangeResult(networkId, BSSID, newState)));
+ }
+
+ /**
+ * Send the tracker a notification that a scan has completed, and results
+ * are available.
+ */
+ void notifyScanResultsAvailable() {
+ /**
+ * Switch scan mode over to passive.
+ * Turning off scan-only mode happens only in "Connect" mode
+ */
+ setScanType(false);
+ sendMessage(SCAN_RESULTS_EVENT);
+ }
+
+ void notifyDriverStarted() {
+ sendMessage(DRIVER_START_EVENT);
+ }
+
+ void notifyDriverStopped() {
+ sendMessage(DRIVER_STOP_EVENT);
+ }
+
+ void notifyDriverHung() {
+ setWifiEnabled(false);
+ setWifiEnabled(true);
+ }
+
+
+ /********************************************************
+ * HSM states
+ *******************************************************/
+
+ class DefaultState extends HierarchicalState {
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ SyncParams syncParams;
+ switch (message.what) {
+ /* Synchronous call returns */
+ case CMD_PING_SUPPLICANT:
+ case CMD_START_SCAN:
+ case CMD_DISCONNECT:
+ case CMD_RECONNECT:
+ case CMD_REASSOCIATE:
+ case CMD_REMOVE_NETWORK:
+ case CMD_ENABLE_NETWORK:
+ case CMD_DISABLE_NETWORK:
+ case CMD_ADD_OR_UPDATE_NETWORK:
+ case CMD_GET_RSSI:
+ case CMD_GET_RSSI_APPROX:
+ case CMD_GET_LINK_SPEED:
+ case CMD_GET_MAC_ADDR:
+ case CMD_SAVE_CONFIG:
+ case CMD_CONNECTION_STATUS:
+ case CMD_GET_NETWORK_CONFIG:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = false;
+ syncParams.mSyncReturn.intValue = -1;
+ syncParams.mSyncReturn.stringValue = null;
+ syncParams.mSyncReturn.configList = null;
+ notifyOnMsgObject(message);
+ }
+ break;
+ case CM_CMD_TEARDOWN:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ mTeardownRequested.set(true);
+ sendMessage(CMD_DISCONNECT);
+ sendMessage(CMD_STOP_DRIVER);
+ /* Mark wifi available when CM tears down */
+ mNetworkInfo.setIsAvailable(true);
+ break;
+ case CM_CMD_RECONNECT:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ mTeardownRequested.set(false);
+ sendMessage(CMD_START_DRIVER);
+ sendMessage(CMD_RECONNECT);
+ break;
+ case CMD_ENABLE_RSSI_POLL:
+ mEnableRssiPolling = (message.arg1 == 1);
+ mSupplicantStateTracker.sendMessage(CMD_ENABLE_RSSI_POLL);
+ break;
+ default:
+ if (DBG) Log.w(TAG, "Unhandled " + message);
+ break;
+ }
+ return HANDLED;
+ }
+ }
+
+ class InitialState extends HierarchicalState {
+ @Override
+ //TODO: could move logging into a common class
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ // [31-8] Reserved for future use
+ // [7 - 0] HSM state change
+ // 50021 wifi_state_changed (custom|1|5)
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+
+ if (WifiNative.isDriverLoaded()) {
+ transitionTo(mDriverLoadedState);
+ }
+ else {
+ transitionTo(mDriverUnloadedState);
+ }
+ }
+ }
+
+ class DriverLoadingState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+
+ final Message message = new Message();
+ message.copyFrom(getCurrentMessage());
+ new Thread(new Runnable() {
+ public void run() {
+ sWakeLock.acquire();
+ //enabling state
+ switch(message.arg1) {
+ case WIFI_STATE_ENABLING:
+ setWifiState(WIFI_STATE_ENABLING);
+ break;
+ case WIFI_AP_STATE_ENABLING:
+ setWifiApState(WIFI_AP_STATE_ENABLING);
+ break;
+ }
+
+ if(WifiNative.loadDriver()) {
+ Log.d(TAG, "Driver load successful");
+ sendMessage(CMD_LOAD_DRIVER_SUCCESS);
+ } else {
+ Log.e(TAG, "Failed to load driver!");
+ switch(message.arg1) {
+ case WIFI_STATE_ENABLING:
+ setWifiState(WIFI_STATE_UNKNOWN);
+ break;
+ case WIFI_AP_STATE_ENABLING:
+ setWifiApState(WIFI_AP_STATE_FAILED);
+ break;
+ }
+ sendMessage(CMD_LOAD_DRIVER_FAILURE);
+ }
+ sWakeLock.release();
+ }
+ }).start();
+ }
+
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch (message.what) {
+ case CMD_LOAD_DRIVER_SUCCESS:
+ transitionTo(mDriverLoadedState);
+ break;
+ case CMD_LOAD_DRIVER_FAILURE:
+ transitionTo(mDriverFailedState);
+ break;
+ case CMD_LOAD_DRIVER:
+ case CMD_UNLOAD_DRIVER:
+ case CMD_START_SUPPLICANT:
+ case CMD_STOP_SUPPLICANT:
+ case CMD_START_AP:
+ case CMD_STOP_AP:
+ case CMD_START_DRIVER:
+ case CMD_STOP_DRIVER:
+ case CMD_SET_SCAN_MODE:
+ case CMD_SET_SCAN_TYPE:
+ case CMD_SET_POWER_MODE:
+ case CMD_SET_BLUETOOTH_COEXISTENCE:
+ case CMD_SET_BLUETOOTH_SCAN_MODE:
+ case CMD_SET_NUM_ALLOWED_CHANNELS:
+ case CMD_START_PACKET_FILTERING:
+ case CMD_STOP_PACKET_FILTERING:
+ deferMessage(message);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DriverLoadedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch(message.what) {
+ case CMD_UNLOAD_DRIVER:
+ transitionTo(mDriverUnloadingState);
+ break;
+ case CMD_START_SUPPLICANT:
+ if(WifiNative.startSupplicant()) {
+ Log.d(TAG, "Supplicant start successful");
+ mWifiMonitor.startMonitoring();
+ setWifiState(WIFI_STATE_ENABLED);
+ transitionTo(mWaitForSupState);
+ } else {
+ Log.e(TAG, "Failed to start supplicant!");
+ sendMessage(obtainMessage(CMD_UNLOAD_DRIVER, WIFI_STATE_UNKNOWN, 0));
+ }
+ break;
+ case CMD_START_AP:
+ try {
+ nwService.startAccessPoint((WifiConfiguration) message.obj,
+ mInterfaceName,
+ SOFTAP_IFACE);
+ } catch(Exception e) {
+ Log.e(TAG, "Exception in startAccessPoint()");
+ sendMessage(obtainMessage(CMD_UNLOAD_DRIVER, WIFI_AP_STATE_FAILED, 0));
+ break;
+ }
+ Log.d(TAG, "Soft AP start successful");
+ setWifiApState(WIFI_AP_STATE_ENABLED);
+ transitionTo(mSoftApStartedState);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DriverUnloadingState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+
+ final Message message = new Message();
+ message.copyFrom(getCurrentMessage());
+ new Thread(new Runnable() {
+ public void run() {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ sWakeLock.acquire();
+ if(WifiNative.unloadDriver()) {
+ Log.d(TAG, "Driver unload successful");
+ sendMessage(CMD_UNLOAD_DRIVER_SUCCESS);
+
+ switch(message.arg1) {
+ case WIFI_STATE_DISABLED:
+ case WIFI_STATE_UNKNOWN:
+ setWifiState(message.arg1);
+ break;
+ case WIFI_AP_STATE_DISABLED:
+ case WIFI_AP_STATE_FAILED:
+ setWifiApState(message.arg1);
+ break;
+ }
+ } else {
+ Log.e(TAG, "Failed to unload driver!");
+ sendMessage(CMD_UNLOAD_DRIVER_FAILURE);
+
+ switch(message.arg1) {
+ case WIFI_STATE_DISABLED:
+ case WIFI_STATE_UNKNOWN:
+ setWifiState(WIFI_STATE_UNKNOWN);
+ break;
+ case WIFI_AP_STATE_DISABLED:
+ case WIFI_AP_STATE_FAILED:
+ setWifiApState(WIFI_AP_STATE_FAILED);
+ break;
+ }
+ }
+ sWakeLock.release();
+ }
+ }).start();
+ }
+
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch (message.what) {
+ case CMD_UNLOAD_DRIVER_SUCCESS:
+ transitionTo(mDriverUnloadedState);
+ break;
+ case CMD_UNLOAD_DRIVER_FAILURE:
+ transitionTo(mDriverFailedState);
+ break;
+ case CMD_LOAD_DRIVER:
+ case CMD_UNLOAD_DRIVER:
+ case CMD_START_SUPPLICANT:
+ case CMD_STOP_SUPPLICANT:
+ case CMD_START_AP:
+ case CMD_STOP_AP:
+ case CMD_START_DRIVER:
+ case CMD_STOP_DRIVER:
+ case CMD_SET_SCAN_MODE:
+ case CMD_SET_SCAN_TYPE:
+ case CMD_SET_POWER_MODE:
+ case CMD_SET_BLUETOOTH_COEXISTENCE:
+ case CMD_SET_BLUETOOTH_SCAN_MODE:
+ case CMD_SET_NUM_ALLOWED_CHANNELS:
+ case CMD_START_PACKET_FILTERING:
+ case CMD_STOP_PACKET_FILTERING:
+ deferMessage(message);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DriverUnloadedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch (message.what) {
+ case CMD_LOAD_DRIVER:
+ transitionTo(mDriverLoadingState);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DriverFailedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ Log.e(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ return NOT_HANDLED;
+ }
+ }
+
+
+ class WaitForSupState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch(message.what) {
+ case SUP_CONNECTION_EVENT:
+ Log.d(TAG, "Supplicant connection established");
+ mSupplicantStateTracker.resetSupplicantState();
+ /* Initialize data structures */
+ resetNotificationTimer();
+ setTeardownRequested(false);
+ mLastBssid = null;
+ mLastNetworkId = -1;
+ mLastSignalLevel = -1;
+
+ mWifiInfo.setMacAddress(WifiNative.getMacAddressCommand());
+
+ //TODO: initialize and fix multicast filtering
+ //mWM.initializeMulticastFiltering();
+
+ if (mBluetoothA2dp == null) {
+ mBluetoothA2dp = new BluetoothA2dp(mContext);
+ }
+ checkIsBluetoothPlaying();
+
+ checkUseStaticIp();
+ sendSupplicantConnectionChangedBroadcast(true);
+ transitionTo(mDriverSupReadyState);
+ break;
+ case CMD_STOP_SUPPLICANT:
+ Log.d(TAG, "Stop supplicant received");
+ WifiNative.stopSupplicant();
+ transitionTo(mDriverLoadedState);
+ break;
+ /* Fail soft ap when waiting for supplicant start */
+ case CMD_START_AP:
+ Log.d(TAG, "Failed to start soft AP with a running supplicant");
+ setWifiApState(WIFI_AP_STATE_FAILED);
+ break;
+ case CMD_START_DRIVER:
+ case CMD_STOP_DRIVER:
+ case CMD_SET_SCAN_MODE:
+ case CMD_SET_SCAN_TYPE:
+ case CMD_SET_POWER_MODE:
+ case CMD_SET_BLUETOOTH_COEXISTENCE:
+ case CMD_SET_BLUETOOTH_SCAN_MODE:
+ case CMD_SET_NUM_ALLOWED_CHANNELS:
+ case CMD_START_PACKET_FILTERING:
+ case CMD_STOP_PACKET_FILTERING:
+ deferMessage(message);
+ break;
+ case CMD_STOP_AP:
+ case CMD_START_SUPPLICANT:
+ case CMD_UNLOAD_DRIVER:
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DriverSupReadyState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ /* Initialize for connect mode operation at start */
+ mIsScanMode = false;
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ SyncParams syncParams;
+ switch(message.what) {
+ case CMD_STOP_SUPPLICANT: /* Supplicant stopped by user */
+ Log.d(TAG, "Stop supplicant received");
+ WifiNative.stopSupplicant();
+ //$FALL-THROUGH$
+ case SUP_DISCONNECTION_EVENT: /* Supplicant died */
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ //Remove any notifications on disconnection
+ setNotificationVisible(false, 0, false, 0);
+ WifiNative.closeSupplicantConnection();
+ handleNetworkDisconnect();
+ sendSupplicantConnectionChangedBroadcast(false);
+ mSupplicantStateTracker.resetSupplicantState();
+ transitionTo(mDriverLoadedState);
+
+ /* When supplicant dies, unload driver and enter failed state */
+ //TODO: consider bringing up supplicant again
+ if (message.what == SUP_DISCONNECTION_EVENT) {
+ Log.d(TAG, "Supplicant died, unloading driver");
+ sendMessage(obtainMessage(CMD_UNLOAD_DRIVER, WIFI_STATE_UNKNOWN, 0));
+ }
+ break;
+ case CMD_START_DRIVER:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ WifiNative.startDriverCommand();
+ transitionTo(mDriverStartingState);
+ break;
+ case SCAN_RESULTS_EVENT:
+ setScanResults(WifiNative.scanResultsCommand());
+ sendScanResultsAvailableBroadcast();
+ checkAndSetNotification();
+ break;
+ case CMD_PING_SUPPLICANT:
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.pingCommand();
+ notifyOnMsgObject(message);
+ break;
+ case CMD_ADD_OR_UPDATE_NETWORK:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ syncParams = (SyncParams) message.obj;
+ WifiConfiguration config = (WifiConfiguration) syncParams.mParameter;
+ syncParams.mSyncReturn.intValue = addOrUpdateNetworkNative(config);
+ notifyOnMsgObject(message);
+ break;
+ case CMD_REMOVE_NETWORK:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.removeNetworkCommand(
+ message.arg1);
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.removeNetworkCommand(message.arg1);
+ }
+ break;
+ case CMD_ENABLE_NETWORK:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ EnableNetParams enableNetParams = (EnableNetParams) syncParams.mParameter;
+ syncParams.mSyncReturn.boolValue = WifiNative.enableNetworkCommand(
+ enableNetParams.netId, enableNetParams.disableOthers);
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.enableNetworkCommand(message.arg1, message.arg2 == 1);
+ }
+ break;
+ case CMD_DISABLE_NETWORK:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.disableNetworkCommand(
+ message.arg1);
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.disableNetworkCommand(message.arg1);
+ }
+ break;
+ case CMD_BLACKLIST_NETWORK:
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ WifiNative.addToBlacklistCommand((String)message.obj);
+ break;
+ case CMD_CLEAR_BLACKLIST:
+ WifiNative.clearBlacklistCommand();
+ break;
+ case CMD_GET_NETWORK_CONFIG:
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.configList = getConfiguredNetworksNative();
+ notifyOnMsgObject(message);
+ break;
+ case CMD_SAVE_CONFIG:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.saveConfigCommand();
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.saveConfigCommand();
+ }
+ // Inform the backup manager about a data change
+ IBackupManager ibm = IBackupManager.Stub.asInterface(
+ ServiceManager.getService(Context.BACKUP_SERVICE));
+ if (ibm != null) {
+ try {
+ ibm.dataChanged("com.android.providers.settings");
+ } catch (Exception e) {
+ // Try again later
+ }
+ }
+ break;
+ case CMD_CONNECTION_STATUS:
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.stringValue = WifiNative.statusCommand();
+ notifyOnMsgObject(message);
+ break;
+ case CMD_GET_MAC_ADDR:
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.stringValue = WifiNative.getMacAddressCommand();
+ notifyOnMsgObject(message);
+ break;
+ /* Cannot start soft AP while in client mode */
+ case CMD_START_AP:
+ Log.d(TAG, "Failed to start soft AP with a running supplicant");
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ setWifiApState(WIFI_AP_STATE_FAILED);
+ break;
+ case CMD_SET_SCAN_MODE:
+ mIsScanMode = (message.arg1 == SCAN_ONLY_MODE);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ return HANDLED;
+ }
+ }
+
+ class DriverStartingState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch(message.what) {
+ case DRIVER_START_EVENT:
+ transitionTo(mDriverStartedState);
+ break;
+ /* Queue driver commands & connection events */
+ case CMD_START_DRIVER:
+ case CMD_STOP_DRIVER:
+ case SUPPLICANT_STATE_CHANGE_EVENT:
+ case NETWORK_CONNECTION_EVENT:
+ case NETWORK_DISCONNECTION_EVENT:
+ case PASSWORD_MAY_BE_INCORRECT_EVENT:
+ case CMD_SET_SCAN_TYPE:
+ case CMD_SET_POWER_MODE:
+ case CMD_SET_BLUETOOTH_COEXISTENCE:
+ case CMD_SET_BLUETOOTH_SCAN_MODE:
+ case CMD_SET_NUM_ALLOWED_CHANNELS:
+ case CMD_START_PACKET_FILTERING:
+ case CMD_STOP_PACKET_FILTERING:
+ deferMessage(message);
+ break;
+ /* Queue the asynchronous version of these commands */
+ case CMD_START_SCAN:
+ case CMD_DISCONNECT:
+ case CMD_REASSOCIATE:
+ case CMD_RECONNECT:
+ if (message.arg2 != SYNCHRONOUS_CALL) {
+ deferMessage(message);
+ }
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DriverStartedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+
+ try {
+ mBatteryStats.noteWifiRunning();
+ } catch (RemoteException ignore) {}
+
+ /* Initialize channel count */
+ setNumAllowedChannels();
+
+ if (mIsScanMode) {
+ WifiNative.setScanResultHandlingCommand(SCAN_ONLY_MODE);
+ WifiNative.disconnectCommand();
+ transitionTo(mScanModeState);
+ } else {
+ WifiNative.setScanResultHandlingCommand(CONNECT_MODE);
+ WifiNative.reconnectCommand();
+ transitionTo(mConnectModeState);
+ }
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ SyncParams syncParams;
+ switch(message.what) {
+ case CMD_SET_SCAN_TYPE:
+ if (message.arg1 == SCAN_ACTIVE) {
+ WifiNative.setScanModeCommand(true);
+ } else {
+ WifiNative.setScanModeCommand(false);
+ }
+ break;
+ case CMD_SET_POWER_MODE:
+ WifiNative.setPowerModeCommand(message.arg1);
+ break;
+ case CMD_SET_BLUETOOTH_COEXISTENCE:
+ WifiNative.setBluetoothCoexistenceModeCommand(message.arg1);
+ break;
+ case CMD_SET_BLUETOOTH_SCAN_MODE:
+ WifiNative.setBluetoothCoexistenceScanModeCommand(message.arg1 == 1);
+ break;
+ case CMD_SET_NUM_ALLOWED_CHANNELS:
+ mNumAllowedChannels = message.arg1;
+ WifiNative.setNumAllowedChannelsCommand(message.arg1);
+ break;
+ case CMD_START_DRIVER:
+ /* Ignore another driver start */
+ break;
+ case CMD_STOP_DRIVER:
+ WifiNative.stopDriverCommand();
+ transitionTo(mDriverStoppingState);
+ break;
+ case CMD_REQUEST_CM_WAKELOCK:
+ if (mCm == null) {
+ mCm = (ConnectivityManager)mContext.getSystemService(
+ Context.CONNECTIVITY_SERVICE);
+ }
+ mCm.requestNetworkTransitionWakelock(TAG);
+ break;
+ case CMD_START_PACKET_FILTERING:
+ WifiNative.startPacketFiltering();
+ break;
+ case CMD_STOP_PACKET_FILTERING:
+ WifiNative.stopPacketFiltering();
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ @Override
+ public void exit() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ try {
+ mBatteryStats.noteWifiStopped();
+ } catch (RemoteException ignore) { }
+ }
+ }
+
+ class DriverStoppingState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch(message.what) {
+ case DRIVER_STOP_EVENT:
+ transitionTo(mDriverStoppedState);
+ break;
+ /* Queue driver commands */
+ case CMD_START_DRIVER:
+ case CMD_STOP_DRIVER:
+ case CMD_SET_SCAN_TYPE:
+ case CMD_SET_POWER_MODE:
+ case CMD_SET_BLUETOOTH_COEXISTENCE:
+ case CMD_SET_BLUETOOTH_SCAN_MODE:
+ case CMD_SET_NUM_ALLOWED_CHANNELS:
+ case CMD_START_PACKET_FILTERING:
+ case CMD_STOP_PACKET_FILTERING:
+ deferMessage(message);
+ break;
+ /* Queue the asynchronous version of these commands */
+ case CMD_START_SCAN:
+ case CMD_DISCONNECT:
+ case CMD_REASSOCIATE:
+ case CMD_RECONNECT:
+ if (message.arg2 != SYNCHRONOUS_CALL) {
+ deferMessage(message);
+ }
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DriverStoppedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+
+ // Take down any open network notifications on driver stop
+ setNotificationVisible(false, 0, false, 0);
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ return NOT_HANDLED;
+ }
+ }
+
+ class ScanModeState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ SyncParams syncParams;
+ switch(message.what) {
+ case CMD_SET_SCAN_MODE:
+ if (message.arg1 == SCAN_ONLY_MODE) {
+ /* Ignore */
+ return HANDLED;
+ } else {
+ WifiNative.setScanResultHandlingCommand(message.arg1);
+ WifiNative.reconnectCommand();
+ mIsScanMode = false;
+ transitionTo(mDisconnectedState);
+ }
+ break;
+ case CMD_START_SCAN:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.scanCommand(
+ message.arg1 == SCAN_ACTIVE);
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.scanCommand(message.arg1 == SCAN_ACTIVE);
+ }
+ break;
+ /* Ignore */
+ case CMD_DISCONNECT:
+ case CMD_RECONNECT:
+ case CMD_REASSOCIATE:
+ case SUPPLICANT_STATE_CHANGE_EVENT:
+ case NETWORK_CONNECTION_EVENT:
+ case NETWORK_DISCONNECTION_EVENT:
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class ConnectModeState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ SyncParams syncParams;
+ StateChangeResult stateChangeResult;
+ switch(message.what) {
+ case PASSWORD_MAY_BE_INCORRECT_EVENT:
+ mPasswordKeyMayBeIncorrect = true;
+ break;
+ case SUPPLICANT_STATE_CHANGE_EVENT:
+ stateChangeResult = (StateChangeResult) message.obj;
+ mSupplicantStateTracker.handleEvent(stateChangeResult);
+ break;
+ case CMD_START_SCAN:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = true;
+ notifyOnMsgObject(message);
+ }
+ /* We need to set scan type in completed state */
+ Message newMsg = obtainMessage();
+ newMsg.copyFrom(message);
+ mSupplicantStateTracker.sendMessage(newMsg);
+ break;
+ /* Do a redundant disconnect without transition */
+ case CMD_DISCONNECT:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.disconnectCommand();
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.disconnectCommand();
+ }
+ break;
+ case CMD_RECONNECT:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.reconnectCommand();
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.reconnectCommand();
+ }
+ break;
+ case CMD_REASSOCIATE:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.reassociateCommand();
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.reassociateCommand();
+ }
+ break;
+ case SCAN_RESULTS_EVENT:
+ /* Set the scan setting back to "connect" mode */
+ WifiNative.setScanResultHandlingCommand(CONNECT_MODE);
+ /* Handle scan results */
+ return NOT_HANDLED;
+ case NETWORK_CONNECTION_EVENT:
+ Log.d(TAG,"Network connection established");
+ stateChangeResult = (StateChangeResult) message.obj;
+
+ /* Remove any notifications */
+ setNotificationVisible(false, 0, false, 0);
+ resetNotificationTimer();
+
+ mWifiInfo.setBSSID(mLastBssid = stateChangeResult.BSSID);
+ mWifiInfo.setNetworkId(stateChangeResult.networkId);
+ mLastNetworkId = stateChangeResult.networkId;
+
+ /* send event to CM & network change broadcast */
+ setDetailedState(DetailedState.OBTAINING_IPADDR);
+ sendNetworkStateChangeBroadcast(mLastBssid);
+
+ transitionTo(mConnectingState);
+ break;
+ case NETWORK_DISCONNECTION_EVENT:
+ Log.d(TAG,"Network connection lost");
+ handleNetworkDisconnect();
+ transitionTo(mDisconnectedState);
+ break;
+ case CMD_GET_RSSI:
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.intValue = WifiNative.getRssiCommand();
+ notifyOnMsgObject(message);
+ break;
+ case CMD_GET_RSSI_APPROX:
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.intValue = WifiNative.getRssiApproxCommand();
+ notifyOnMsgObject(message);
+ break;
+ case CMD_GET_LINK_SPEED:
+ syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.intValue = WifiNative.getLinkSpeedCommand();
+ notifyOnMsgObject(message);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class ConnectingState extends HierarchicalState {
+ boolean modifiedBluetoothCoexistenceMode;
+ int powerMode;
+ Thread mDhcpThread;
+
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+
+ if (!mUseStaticIp) {
+
+ mDhcpThread = null;
+ modifiedBluetoothCoexistenceMode = false;
+ powerMode = DRIVER_POWER_MODE_AUTO;
+
+ if (shouldDisableCoexistenceMode()) {
+ /*
+ * There are problems setting the Wi-Fi driver's power
+ * mode to active when bluetooth coexistence mode is
+ * enabled or sense.
+ * <p>
+ * We set Wi-Fi to active mode when
+ * obtaining an IP address because we've found
+ * compatibility issues with some routers with low power
+ * mode.
+ * <p>
+ * In order for this active power mode to properly be set,
+ * we disable coexistence mode until we're done with
+ * obtaining an IP address. One exception is if we
+ * are currently connected to a headset, since disabling
+ * coexistence would interrupt that connection.
+ */
+ modifiedBluetoothCoexistenceMode = true;
+
+ // Disable the coexistence mode
+ WifiNative.setBluetoothCoexistenceModeCommand(
+ WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
+ }
+
+ powerMode = WifiNative.getPowerModeCommand();
+ if (powerMode < 0) {
+ // Handle the case where supplicant driver does not support
+ // getPowerModeCommand.
+ powerMode = DRIVER_POWER_MODE_AUTO;
+ }
+ if (powerMode != DRIVER_POWER_MODE_ACTIVE) {
+ WifiNative.setPowerModeCommand(DRIVER_POWER_MODE_ACTIVE);
+ }
+
+ Log.d(TAG, "DHCP request started");
+ mDhcpThread = new Thread(new Runnable() {
+ public void run() {
+ if (NetworkUtils.runDhcp(mInterfaceName, mDhcpInfo)) {
+ Log.d(TAG, "DHCP request succeeded");
+ sendMessage(CMD_IP_CONFIG_SUCCESS);
+ } else {
+ Log.d(TAG, "DHCP request failed: " +
+ NetworkUtils.getDhcpError());
+ sendMessage(CMD_IP_CONFIG_FAILURE);
+ }
+ }
+ });
+ mDhcpThread.start();
+ } else {
+ if (NetworkUtils.configureInterface(mInterfaceName, mDhcpInfo)) {
+ Log.v(TAG, "Static IP configuration succeeded");
+ sendMessage(CMD_IP_CONFIG_SUCCESS);
+ } else {
+ Log.v(TAG, "Static IP configuration failed");
+ sendMessage(CMD_IP_CONFIG_FAILURE);
+ }
+ }
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+
+ switch(message.what) {
+ case CMD_IP_CONFIG_SUCCESS:
+ mReconnectCount = 0;
+ mLastSignalLevel = -1; // force update of signal strength
+ mWifiInfo.setIpAddress(mDhcpInfo.ipAddress);
+ Log.d(TAG, "IP configuration: " + mDhcpInfo);
+ configureNetworkProperties();
+ setDetailedState(DetailedState.CONNECTED);
+ sendNetworkStateChangeBroadcast(mLastBssid);
+ transitionTo(mConnectedState);
+ break;
+ case CMD_IP_CONFIG_FAILURE:
+ mWifiInfo.setIpAddress(0);
+
+ Log.e(TAG, "IP configuration failed");
+ /**
+ * If we've exceeded the maximum number of retries for DHCP
+ * to a given network, disable the network
+ */
+ if (++mReconnectCount > getMaxDhcpRetries()) {
+ Log.e(TAG, "Failed " +
+ mReconnectCount + " times, Disabling " + mLastNetworkId);
+ WifiNative.disableNetworkCommand(mLastNetworkId);
+ }
+
+ /* DHCP times out after about 30 seconds, we do a
+ * disconnect and an immediate reconnect to try again
+ */
+ WifiNative.disconnectCommand();
+ WifiNative.reconnectCommand();
+ transitionTo(mDisconnectingState);
+ break;
+ case CMD_DISCONNECT:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ SyncParams syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.disconnectCommand();
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.disconnectCommand();
+ }
+ transitionTo(mDisconnectingState);
+ break;
+ /* Ignore */
+ case NETWORK_CONNECTION_EVENT:
+ break;
+ case CMD_STOP_DRIVER:
+ sendMessage(CMD_DISCONNECT);
+ deferMessage(message);
+ break;
+ case CMD_SET_SCAN_MODE:
+ if (message.arg1 == SCAN_ONLY_MODE) {
+ sendMessage(CMD_DISCONNECT);
+ deferMessage(message);
+ }
+ break;
+ case CMD_RECONFIGURE_IP:
+ deferMessage(message);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+
+ @Override
+ public void exit() {
+ /* reset power state & bluetooth coexistence if on DHCP */
+ if (!mUseStaticIp) {
+ if (powerMode != DRIVER_POWER_MODE_ACTIVE) {
+ WifiNative.setPowerModeCommand(powerMode);
+ }
+
+ if (modifiedBluetoothCoexistenceMode) {
+ // Set the coexistence mode back to its default value
+ WifiNative.setBluetoothCoexistenceModeCommand(
+ WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
+ }
+ }
+
+ }
+ }
+
+ class ConnectedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch (message.what) {
+ case CMD_DISCONNECT:
+ if (message.arg2 == SYNCHRONOUS_CALL) {
+ SyncParams syncParams = (SyncParams) message.obj;
+ syncParams.mSyncReturn.boolValue = WifiNative.disconnectCommand();
+ notifyOnMsgObject(message);
+ } else {
+ /* asynchronous handling */
+ WifiNative.disconnectCommand();
+ }
+ transitionTo(mDisconnectingState);
+ break;
+ case CMD_RECONFIGURE_IP:
+ Log.d(TAG,"Reconfiguring IP on connection");
+ NetworkUtils.resetConnections(mInterfaceName);
+ transitionTo(mConnectingState);
+ break;
+ case CMD_STOP_DRIVER:
+ sendMessage(CMD_DISCONNECT);
+ deferMessage(message);
+ break;
+ case CMD_SET_SCAN_MODE:
+ if (message.arg1 == SCAN_ONLY_MODE) {
+ sendMessage(CMD_DISCONNECT);
+ deferMessage(message);
+ }
+ break;
+ /* Ignore */
+ case NETWORK_CONNECTION_EVENT:
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DisconnectingState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch (message.what) {
+ case CMD_STOP_DRIVER: /* Stop driver only after disconnect handled */
+ deferMessage(message);
+ break;
+ case CMD_SET_SCAN_MODE:
+ if (message.arg1 == SCAN_ONLY_MODE) {
+ deferMessage(message);
+ }
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class DisconnectedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch (message.what) {
+ case CMD_SET_SCAN_MODE:
+ if (message.arg1 == SCAN_ONLY_MODE) {
+ WifiNative.setScanResultHandlingCommand(message.arg1);
+ //Supplicant disconnect to prevent further connects
+ WifiNative.disconnectCommand();
+ mIsScanMode = true;
+ transitionTo(mScanModeState);
+ }
+ break;
+ /* Ignore network disconnect */
+ case NETWORK_DISCONNECTION_EVENT:
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+ class SoftApStartedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch(message.what) {
+ case CMD_STOP_AP:
+ Log.d(TAG,"Stopping Soft AP");
+ setWifiApState(WIFI_AP_STATE_DISABLING);
+ try {
+ nwService.stopAccessPoint();
+ } catch(Exception e) {
+ Log.e(TAG, "Exception in stopAccessPoint()");
+ }
+ transitionTo(mDriverLoadedState);
+ break;
+ case CMD_START_AP:
+ Log.d(TAG,"SoftAP set on a running access point");
+ try {
+ nwService.setAccessPoint((WifiConfiguration) message.obj,
+ mInterfaceName,
+ SOFTAP_IFACE);
+ } catch(Exception e) {
+ Log.e(TAG, "Exception in nwService during soft AP set");
+ try {
+ nwService.stopAccessPoint();
+ } catch (Exception ee) {
+ Slog.e(TAG, "Could not stop AP, :" + ee);
+ }
+ sendMessage(obtainMessage(CMD_UNLOAD_DRIVER, WIFI_AP_STATE_FAILED, 0));
+ }
+ break;
+ /* Fail client mode operation when soft AP is enabled */
+ case CMD_START_SUPPLICANT:
+ Log.e(TAG,"Cannot start supplicant with a running soft AP");
+ setWifiState(WIFI_STATE_UNKNOWN);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ EventLog.writeEvent(EVENTLOG_WIFI_EVENT_HANDLED, message.what);
+ return HANDLED;
+ }
+ }
+
+
+ class SupplicantStateTracker extends HierarchicalStateMachine {
+
+ private int mRssiPollToken = 0;
+
+ /**
+ * The max number of the WPA supplicant loop iterations before we
+ * decide that the loop should be terminated:
+ */
+ private static final int MAX_SUPPLICANT_LOOP_ITERATIONS = 4;
+ private int mLoopDetectIndex = 0;
+ private int mLoopDetectCount = 0;
+
+ /**
+ * Supplicant state change commands follow
+ * the ordinal values defined in SupplicantState.java
+ */
+ private static final int DISCONNECTED = 0;
+ private static final int INACTIVE = 1;
+ private static final int SCANNING = 2;
+ private static final int ASSOCIATING = 3;
+ private static final int ASSOCIATED = 4;
+ private static final int FOUR_WAY_HANDSHAKE = 5;
+ private static final int GROUP_HANDSHAKE = 6;
+ private static final int COMPLETED = 7;
+ private static final int DORMANT = 8;
+ private static final int UNINITIALIZED = 9;
+ private static final int INVALID = 10;
+
+ private HierarchicalState mUninitializedState;
+ private HierarchicalState mInitializedState;
+ private HierarchicalState mInactiveState;
+ private HierarchicalState mDisconnectState;
+ private HierarchicalState mScanState;
+ private HierarchicalState mConnectState;
+ private HierarchicalState mHandshakeState;
+ private HierarchicalState mCompletedState;
+ private HierarchicalState mDormantState;
+
+
+ public SupplicantStateTracker(Context context, Handler target) {
+ super(TAG, target.getLooper());
+
+ mUninitializedState = new UninitializedState();
+ mInitializedState = new InitializedState();
+ mInactiveState = new InactiveState();
+ mDisconnectState = new DisconnectedState();
+ mScanState = new ScanState();
+ mConnectState = new ConnectState();
+ mHandshakeState = new HandshakeState();
+ mCompletedState = new CompletedState();
+ mDormantState = new DormantState();
+
+
+ addState(mUninitializedState);
+ addState(mInitializedState);
+ addState(mInactiveState, mInitializedState);
+ addState(mDisconnectState, mInitializedState);
+ addState(mScanState, mInitializedState);
+ addState(mConnectState, mInitializedState);
+ addState(mHandshakeState, mConnectState);
+ addState(mCompletedState, mConnectState);
+ addState(mDormantState, mInitializedState);
+
+ setInitialState(mUninitializedState);
+
+ //start the state machine
+ start();
+ }
+
+ public void handleEvent(StateChangeResult stateChangeResult) {
+ SupplicantState newState = (SupplicantState) stateChangeResult.state;
+
+ // Supplicant state change
+ // [31-13] Reserved for future use
+ // [8 - 0] Supplicant state (as defined in SupplicantState.java)
+ // 50023 supplicant_state_changed (custom|1|5)
+ EventLog.writeEvent(EVENTLOG_SUPPLICANT_STATE_CHANGED, newState.ordinal());
+
+ sendMessage(obtainMessage(newState.ordinal(), stateChangeResult));
+ }
+
+ public void resetSupplicantState() {
+ transitionTo(mUninitializedState);
+ }
+
+ private void resetLoopDetection() {
+ mLoopDetectCount = 0;
+ mLoopDetectIndex = 0;
+ }
+
+ private boolean handleTransition(Message msg) {
+ if (DBG) Log.d(TAG, getName() + msg.toString() + "\n");
+ switch (msg.what) {
+ case DISCONNECTED:
+ transitionTo(mDisconnectState);
+ break;
+ case SCANNING:
+ transitionTo(mScanState);
+ break;
+ case ASSOCIATING:
+ StateChangeResult stateChangeResult = (StateChangeResult) msg.obj;
+ /* BSSID is valid only in ASSOCIATING state */
+ mWifiInfo.setBSSID(stateChangeResult.BSSID);
+ //$FALL-THROUGH$
+ case ASSOCIATED:
+ case FOUR_WAY_HANDSHAKE:
+ case GROUP_HANDSHAKE:
+ transitionTo(mHandshakeState);
+ break;
+ case COMPLETED:
+ transitionTo(mCompletedState);
+ break;
+ case DORMANT:
+ transitionTo(mDormantState);
+ break;
+ case INACTIVE:
+ transitionTo(mInactiveState);
+ break;
+ case UNINITIALIZED:
+ case INVALID:
+ transitionTo(mUninitializedState);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ StateChangeResult stateChangeResult = (StateChangeResult) msg.obj;
+ SupplicantState supState = (SupplicantState) stateChangeResult.state;
+ setDetailedState(WifiInfo.getDetailedStateOf(supState));
+ mWifiInfo.setSupplicantState(supState);
+ mWifiInfo.setNetworkId(stateChangeResult.networkId);
+ //TODO: Modify WifiMonitor to report SSID on events
+ //mWifiInfo.setSSID()
+ return HANDLED;
+ }
+
+ /********************************************************
+ * HSM states
+ *******************************************************/
+
+ class InitializedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
+ switch (message.what) {
+ case CMD_START_SCAN:
+ WifiNative.scanCommand(message.arg1 == SCAN_ACTIVE);
+ break;
+ default:
+ if (DBG) Log.w(TAG, "Ignoring " + message);
+ break;
+ }
+ return HANDLED;
+ }
+ }
+
+ class UninitializedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ mNetworkInfo.setIsAvailable(false);
+ resetLoopDetection();
+ mPasswordKeyMayBeIncorrect = false;
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ switch(message.what) {
+ default:
+ if (!handleTransition(message)) {
+ if (DBG) Log.w(TAG, "Ignoring " + message);
+ }
+ break;
+ }
+ return HANDLED;
+ }
+ }
+
+ class InactiveState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ Message message = getCurrentMessage();
+ StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
+
+ mNetworkInfo.setIsAvailable(false);
+ resetLoopDetection();
+ mPasswordKeyMayBeIncorrect = false;
+
+ sendSupplicantStateChangedBroadcast(stateChangeResult, false);
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ return handleTransition(message);
+ }
+ }
+
+
+ class DisconnectedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ Message message = getCurrentMessage();
+ StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
+
+ mNetworkInfo.setIsAvailable(true);
+ resetLoopDetection();
+
+ /* If a disconnect event happens after a password key failure
+ * event, disable the network
+ */
+ if (mPasswordKeyMayBeIncorrect) {
+ Log.d(TAG, "Failed to authenticate, disabling network " +
+ mWifiInfo.getNetworkId());
+ WifiNative.disableNetworkCommand(mWifiInfo.getNetworkId());
+ mPasswordKeyMayBeIncorrect = false;
+ sendSupplicantStateChangedBroadcast(stateChangeResult, true);
+ }
+ else {
+ sendSupplicantStateChangedBroadcast(stateChangeResult, false);
+ }
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ return handleTransition(message);
+ }
+ }
+
+ class ScanState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ Message message = getCurrentMessage();
+ StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
+
+ mNetworkInfo.setIsAvailable(true);
+ mPasswordKeyMayBeIncorrect = false;
+ resetLoopDetection();
+ sendSupplicantStateChangedBroadcast(stateChangeResult, false);
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ return handleTransition(message);
+ }
+ }
+
+ class ConnectState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ switch (message.what) {
+ case CMD_START_SCAN:
+ WifiNative.setScanResultHandlingCommand(SCAN_ONLY_MODE);
+ WifiNative.scanCommand(message.arg1 == SCAN_ACTIVE);
+ break;
+ default:
+ return NOT_HANDLED;
+ }
+ return HANDLED;
+ }
+ }
+
+ class HandshakeState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ final Message message = getCurrentMessage();
+ StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
+
+ mNetworkInfo.setIsAvailable(true);
+
+ if (mLoopDetectIndex > message.what) {
+ mLoopDetectCount++;
+ }
+ if (mLoopDetectCount > MAX_SUPPLICANT_LOOP_ITERATIONS) {
+ WifiNative.disableNetworkCommand(stateChangeResult.networkId);
+ mLoopDetectCount = 0;
+ }
+
+ mLoopDetectIndex = message.what;
+
+ mPasswordKeyMayBeIncorrect = false;
+ sendSupplicantStateChangedBroadcast(stateChangeResult, false);
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ return handleTransition(message);
+ }
+ }
+
+ class CompletedState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ Message message = getCurrentMessage();
+ StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
+
+ mNetworkInfo.setIsAvailable(true);
+
+ mRssiPollToken++;
+ if (mEnableRssiPolling) {
+ sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, mRssiPollToken, 0),
+ POLL_RSSI_INTERVAL_MSECS);
+ }
+
+ resetLoopDetection();
+
+ mPasswordKeyMayBeIncorrect = false;
+ sendSupplicantStateChangedBroadcast(stateChangeResult, false);
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ switch(message.what) {
+ case ASSOCIATING:
+ case ASSOCIATED:
+ case FOUR_WAY_HANDSHAKE:
+ case GROUP_HANDSHAKE:
+ case COMPLETED:
+ break;
+ case CMD_RSSI_POLL:
+ if (message.arg1 == mRssiPollToken) {
+ // Get Info and continue polling
+ requestPolledInfo();
+ sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, mRssiPollToken, 0),
+ POLL_RSSI_INTERVAL_MSECS);
+ } else {
+ // Polling has completed
+ }
+ break;
+ case CMD_ENABLE_RSSI_POLL:
+ mRssiPollToken++;
+ if (mEnableRssiPolling) {
+ // first poll
+ requestPolledInfo();
+ sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, mRssiPollToken, 0),
+ POLL_RSSI_INTERVAL_MSECS);
+ }
+ break;
+ default:
+ return handleTransition(message);
+ }
+ return HANDLED;
+ }
+ }
+
+ class DormantState extends HierarchicalState {
+ @Override
+ public void enter() {
+ if (DBG) Log.d(TAG, getName() + "\n");
+ Message message = getCurrentMessage();
+ StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
+
+ mNetworkInfo.setIsAvailable(true);
+ resetLoopDetection();
+ mPasswordKeyMayBeIncorrect = false;
+
+ sendSupplicantStateChangedBroadcast(stateChangeResult, false);
+
+ /* TODO: reconnect is now being handled at DHCP failure handling
+ * If we run into issues with staying in Dormant state, might
+ * need a reconnect here
+ */
+ }
+ @Override
+ public boolean processMessage(Message message) {
+ return handleTransition(message);
+ }
+ }
+ }
+
private class NotificationEnabledSettingObserver extends ContentObserver {
public NotificationEnabledSettingObserver(Handler handler) {
@@ -2627,8 +3971,4 @@ public class WifiStateTracker extends Handler implements NetworkStateTracker {
Settings.Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 1) == 1;
}
}
-
- public NetworkProperties getNetworkProperties() {
- return mNetworkProperties;
- }
}