Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using SDK Samples to Help Avoid Head Scratching

Author: Daniel Fowler
Published? true
FormatLanguage: WikiFormat

Problem:

Sometimes it is a struggle to code up some functionality, especially when the documentation is sketchy or does not provide any examples.

Solution:

Looking at existing working code will help. The SDK has sample programs that can be picked apart to see how they work.

Discussion:

The Android SDK comes with several sample applications that can be useful when trying to write code for specific functionality. If the samples are not installed use the SDK Manager program to get them.

Looking through the sample code can be insightful. There are many samples available.

Before Android Studio became Google's preferred programming environment the Eclipse IDE was used. With the release of Studio the build system moved to Gradle and new Gradle based samples were created. The source code for the previous Eclipse based samples has been moved into the legacy folder. (The SDK API column indicates which SDK release the sample first appeared.)

Android SDK Legacy Examples
Name Folder Name Summary SDK API
Accelerometer Play AccelerometerPlay Use of the Accelerometer 10+
Action Bar Compatibility ActionBarCompat Using the Android 3.0 Action Bar functionality in pre-Android and post-Android 3.0 Apps 14+
Android Beam Demo AndroidBeamDemo Transmission between two devices via NFC 14+
API Demos ApiDemos Demo showing general Android interfaces and topics 7+
App Navigation AppNavigation Navigation scenarios 15+
Backup and Restore BackupRestore Using the BackupAgent API 8+
Basic Open GL to SurfaceView BasicGLSurfaceView Simple Open GL example 10+
Bluetooth Chat BluetoothChat Transmission between devices using Bluetooth 7+
Bluetooth Health Device Profile BluetoothHDP Connect to a Bluetooth enabled health device 14+
Contact Manager ContactManager Interaction with the systems contacts provider 7+
Cross Compatibility CrossCompatibility Testing SDK build version for version specific functionality 10+
Cube Live Wallpaper CubeLiveWallpaper Example of building an packaging a live wallpaper 7+
Gesture Builder GestureBuilder Detect and store gestures 7+
Media Effects HelloEffects Media effects for images and videos 16+
Home Home A home screen replacement 7+
Honeycomb Gallery HoneycombGallery An image gallery built with fragments 11+
JetBoy JetBoy A game that uses JetPlayer to demonstrate SONiVOX JET 7+
Key Chain Demo KeyChainDemo Security certificates and keys management 16+
Lunar Lander LunarLander An example game 7+
Multiple Resolutions MultiResolution How to use the resource qualifiers to support multiple resolutions 7+
NFC Demo NFCDemo Reading Near Field Communication tags 10+
Note Pad NotePad An example App making notes 7+
Random Music Player RandomMusicPlayer How to play music on a device 13+
RenderScript RenderScript An example using RenderScript 11+
SampleSyncAdapter SampleSyncAdapter A example of syncing with web based data 7+
Searchable Dictionary SearchableDictionary Using the Android search framework and Quick Search Box 7+
SIP Demo SipDemo Session Initiation Protocol example (Internet telephony) 10+
Skeleton App SkeletonApp A barebones App 7+
Snake Snake An example game 7+
Soft Keyboard SoftKeyboard A keyboard implementation 7+
Spell Checker SpellChecker Spell checker exmaple 14+
Spinner Spinner The App for the testing tutorial see also SpinnerTest 8+
SpinnerTest SpinnerTest A test program for the Spinner testing App tutorial 8+
TicTacToeLib TicTacToeLib Example of using a library 8+
TicTacToeMain TicTacToeMain App that uses the library project 8+
Toy VPN Client ToyVpn Example of a custom Virtual Private Network 14+
Text to Speech Engine TtsEngine Using the Test to Speech engine 14+
USB USB Use of the USB APIs 12+
Voicemail Provider VoicemailProviderDemo Use of the voicemail content provider APIs 14+
Base Recognition Service VoiceRecognitionService Skeleton App for a new Recognition Service 8+
Weather Widget WeatherListWidget A basic weather Widget example 11+
Widget Preview WidgetPreview Grab a screenshot of a Widget 11+
Wi-Fi Direct Demo WiFiDirectDemo Demonstrating use of the Wi-Fi Direct APIs 14+
Wiktionary Wiktionary Home screen Widget example 7+
Wicktionary (Simplified) WiktionarySimple A simple Widget example 7+
XML Adapters XmlAdapters Using XMLAdapters to bind data to Views 11+

Although the legacy samples do not have project files that can be opened in Studio the source code can still be used. To run a legacy sample create a new Studio project named after the sample. Using the file system copy/merge the contents of the legacy sample's res folder into the main/res folder for the new project. Copy the Java class files from the src folder of the sample to the correct main/java folders in the new App. Studio automatically shows newly added files because the project tree reflects the file system. Correct any references and namespaces in the Java files due to the new project structure. A message is displayed before editing files that are read-only, as the samples may be. Merge the legacy sample's AndroidManifest.xml file with the new project's. Ensuring the correct activity, intent-filters and uses-permissions are copied across. It is not difficult to get the legacy samples built and running.

New Android SDK Examples
App Summary SDK API
admin folder Enterprise device management 21+
AppRestrictionEnforcer Restrictions for managed devices 21+
AppRestrictionSchema UI restrictions demo for managed devices 21+
BasicManagedProfile Managed Profile API demo 21+
DeviceOwner Using device owner features 22+
androidtv folder Demo Apps for Android TV 21+
leanback Example Android TV UI App 21+
sample-inputs Live TV App demo 22+
visual-game-controller Game controller demo 21+
background folder Background tasks demos 19+
JobScheduler Background tasks scheduling 21+
RepeatingAlarmSample Alarm activated intent example 19+
connectivity folder External connectivity demos 18+
BasicNetworkDemo Network connectivity checking 18
BasicNetworking Network connectivity checking 19+
BasicSyncAdapter Background data download 18+
bluetooth Bluetooth chat 20+
BluetoothLeGatt Transfer data via Bluetooth 19+
CardEmulation NFC card emulation 19+
CardReader NFC card reader 19+
NetworkConnect Fetching HTML on background thread 18+
content folder Device content access 18+
AppRestrictions Restrict profile demo 19+
AutoBackupForApps Automatic backups settings demo 23
BasicContactables Contacts search 18+
documentsUI Directory selection demo 22+
StorageClient Document providers access demo 19+
StorageProvider Document provider demo 19+
webview Accessing restricted feature from a WebView 22+
input folder Demos detecting touch actions 18+
BasicGestureDetect Gesture detection 18+
BasicMultitouch Multi-touch points demo 18+
media folder Media demos 18+
BasicMediaDecoder Video decode and rendering 19+
BasicMediaRouter Route media to secondary display 18+
Camera2Basic Access the camera 21+
Camera2Raw Camera access for frame data 21+
Camera2Video Record video 21+
HdrViewfinder High dynamic range demo 21+
MediaEffects Using the media effects API 20+
MediaRecorder Using the MediaRecorder API for the camera 19+
MediaRouter Custom media router provider 19+
ScreenCapture Media Projection API for device screen capture 22+
nfc folder NFC Provisioning demo 22+
NfcProvisioning Device provisioning via NFC 22+
notification folder Notifications demos 21+
ActiveNotifications count notifications 23
BasicNotifications Show a notification 21-22
CustomNotifications Notifications with custom content views 21-22
LNotifictions New notification types 21-22
MessagingService Notification messages and Android Auto 21-22
renderscript folder RenderScript usage 19+
BasicRenderScript Basic image manipulation 19+
RenderScriptIntrinsic Using RenderScript built in functions (Intrinsics) 19+
security folder Using device security access features 18+
BasicAndroidKeyStore Create and store encryption keys 18+
ConfirmCredential Using device protection in an App 23
FingerprintDialog Fingerprint authentication 23
sensors folder Sensor demo 19+
BatchStepSensor Using the step sensor 19+
system folder App permissions and usage demos 22+
AppUsageStatistics Collecting App usage stats 22+
RuntimePermissions Checking and collecting run-time permissions 23
RuntimePermissionsBasic Basic use of run-time permissions 23
testing folder Testing demo 18+
ActivityInstrumentation Using testing instrumentation 18+
ui folder User Interface demos 18+
ActionBarCompat-Basic Action bar demo 18+
ActionBarCompat-ListPopupMenu Pop-up menu 18+
ActionBarCompat-ShareActionProvider ViewPager with ShareActionProvider 18+
ActionBarCompat-Styled ActionBar styling 18+
AdapterTransition Overlay layout transitions 19-20
activityscenetransition Scene transitions 21+
activitytasks/DocumentCentricApps The new FLAG_ACTIVITY_NEW_DOCUMENT intent action 21+
activitytasks/DocumentCentricRelenquishIdentity Change an activities base activity 21+
AdvancedImmersiveMode Full screen demo 19+
BasicAccessibility Accessibility demo 18+
BasicImmersiveMode Basic full screen demo 19+
BasicNotifications Show a notification 18+
BasicTransition Transitions demo 19+
BorderlessButtons Halo borderless button styling 18+
CustomChoiceList Custom checkable layouts 18+
CustomNotifications Notifications with custom content views 19+
CustomTransition Custom transitions 19+
DisplayingBitmaps Efficient bitmap loading and display 19+
DoneBar ActionBar Done button 18+
DrawableTinting Filters for Drawables 21+
graphics Rendering PDF 21+
HorizontalPaging Tabs swiping 18+
ImmersiveMode Swipe status bar and navigation bar in and out 19+
Interpolator Motion animation 21+
notifications Notification types 23
SlidingTabsBasic SlidingTabLayout with a ViewPager 19+
SlidingTabsColors Customised SlidingTabLayout with a ViewPager 19+
SwipeRefreshLayoutBasic Swipe to refresh demo 19+
SwipeRefreshListFragment ListView swipe to refresh 19+
SwipeRefreshMultipleViews Swipe to refresh child view 19+
TextLinkify Clickable links in a TextView 19+
TextSwitcher Text animations 18+
views/CardView CarView demo 21+
views/Clipping Clipping a View 21+
views/Elevation/ElevationBasic Changing View elevation demo 21+
views/Elevation/ElevationDrag View elevation drag an drop demo 21+
views/FloatingActionButton Checkable floating action button 21+
views/NavigationDrawer DrawerLayout widget 21+
views/RecyclerView Recycle views for datasets 21+
views/RevealEffect Circular reveal effect 21+
wearable folder Android wearables demos 20+
AgendaData Calendar sync 20+
DataLayer Use of DataEvents 20+
DelayedConfirmation Wearable callback to device demo 20+
ElizaChat Wearable notifications demo 20+
FindMyPhone Mislaid device warning demo 20+
EmbeddedApp Embedding a wearable App in a device App 20-21
Flashlight A flashlight demo for wearable 20+
Geofencing Geofencing with a wearable 20+
GridViewPager GridViewPager on a wearable 20+
JumpingJack Using the gravity sensor 20+
Notifications Wearable notifications 20+
Quiz Questions on a wearable from a device 20+
RecipeAssistant Step-by-step instructions 20+
SkeletonWearableApp Basic wearable App 20+
SpeedTracker Calculate wearable device speed 20+
SynchronizedNotifications Wearable and device synchronised notifications 20+
Timer Countdown timer 20+
WatchFace Creating watch faces 21+
WatchViewStub Layouts for circular and square watches 20+
XYZTouristAttractions Wearable and device interaction demo 22+

On Studio's welcome screen there are two import options (to return to the welcome screen close the current project). One for import project, for local files, and one for import code sample, from GitHub. Many of the GitHub projects are duplicated in the SDK samples, though some SDK samples are not on GitHub and vice versa. Using local project import opens an SDK sample App in Studio. The App is opened from the directory it is located.

The Gradle status is shown on Studio's bottom status bar, after a short time Gradle will be completed and the sample will be ready to run. The source code can be browsed to see how it is all done. If not using a physical device for testing it may be necessary to configure an appropriate AVD to run the sample (see Set Up an Android Virtual Device (AVD) for App Testing).

Additional sources of information when stuck on an Android programming problem include:

  • This Cookbook of course.
  • The Android Developers web site at [1]
  • Stack Overflow at [2] using the Tag "android".
  • Doing a web search.
No records found.