summaryrefslogtreecommitdiff
path: root/src/plugins/snippets
diff options
context:
space:
mode:
Diffstat (limited to 'src/plugins/snippets')
-rw-r--r--src/plugins/snippets/.classpath7
-rw-r--r--src/plugins/snippets/.project28
-rw-r--r--src/plugins/snippets/META-INF/MANIFEST.MF19
-rw-r--r--src/plugins/snippets/build.properties6
-rw-r--r--src/plugins/snippets/plugin.properties532
-rw-r--r--src/plugins/snippets/plugin.xml2086
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidPermissionInsertSnippet.java274
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsStartup.java338
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsTooltip.java147
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/CodeSnippetsPlugin.java69
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/SnippetsViewContributionItem.java227
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/TooltipDisplayConfigContriutionItem.java164
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/AndroidSnippetsNLS.java55
-rw-r--r--src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/androidSnippetsNLS.properties7
14 files changed, 3959 insertions, 0 deletions
diff --git a/src/plugins/snippets/.classpath b/src/plugins/snippets/.classpath
new file mode 100644
index 0000000..8a8f166
--- /dev/null
+++ b/src/plugins/snippets/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+ <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
diff --git a/src/plugins/snippets/.project b/src/plugins/snippets/.project
new file mode 100644
index 0000000..38fac4e
--- /dev/null
+++ b/src/plugins/snippets/.project
@@ -0,0 +1,28 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>com.motorola.studio.android.codesnippets</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.ManifestBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.pde.SchemaBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.pde.PluginNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
diff --git a/src/plugins/snippets/META-INF/MANIFEST.MF b/src/plugins/snippets/META-INF/MANIFEST.MF
new file mode 100644
index 0000000..c52e86d
--- /dev/null
+++ b/src/plugins/snippets/META-INF/MANIFEST.MF
@@ -0,0 +1,19 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: %pluginName
+Bundle-SymbolicName: com.motorola.studio.android.codesnippets;singleton:=true
+Bundle-Version: 5.0.0.qualifier
+Bundle-Localization: plugin
+Require-Bundle: org.eclipse.core.runtime,
+ org.eclipse.core.resources,
+ org.eclipse.ui,
+ org.eclipse.ui.ide,
+ org.eclipse.ui.editors,
+ org.eclipse.gef,
+ org.eclipse.jface.text,
+ org.eclipse.jdt.ui,
+ org.eclipse.wst.common.snippets,
+ com.motorola.studio.android.common
+Bundle-Vendor: %providerName
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Export-Package: com.motorola.studio.android.codesnippets.i18n
diff --git a/src/plugins/snippets/build.properties b/src/plugins/snippets/build.properties
new file mode 100644
index 0000000..0dc34f7
--- /dev/null
+++ b/src/plugins/snippets/build.properties
@@ -0,0 +1,6 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+ .,\
+ plugin.xml,\
+ plugin.properties
diff --git a/src/plugins/snippets/plugin.properties b/src/plugins/snippets/plugin.properties
new file mode 100644
index 0000000..221659b
--- /dev/null
+++ b/src/plugins/snippets/plugin.properties
@@ -0,0 +1,532 @@
+#################################################################################
+#
+# Code Snippets properties
+#
+#################################################################################
+
+pluginName=MOTODEV Studio for Android Code Snippets Plug-in
+providerName= Motorola Mobility, Inc.
+
+# -------------------------
+# System Services
+# -------------------------
+
+category.service=System Services
+category.service.description=Obtain handles for system-level services
+
+snippet.service.systemService00=Activity Manager
+snippet.service.systemService01=Alarm Manager
+snippet.service.systemService02=Audio Manager
+snippet.service.systemService03=Clipboard Manager
+snippet.service.systemService04=Connectivity Manager
+snippet.service.systemService05=Input Method Manager
+snippet.service.systemService06=Keyguard Manager
+snippet.service.systemService07=Layout Inflater Manager
+snippet.service.systemService08=Location Manager
+snippet.service.systemService09=Notification Manager
+snippet.service.systemService10=Power Manager
+snippet.service.systemService11=Search Manager
+snippet.service.systemService12=Sensor Manager
+snippet.service.systemService13=Telephony Manager
+snippet.service.systemService14=Vibrator
+snippet.service.systemService15=Wallpaper
+snippet.service.systemService16=Wi-Fi Manager
+snippet.service.systemService17=Window Manager
+
+snippet.service.systemService00.description=Obtain a handle to the manager responsible for interacting with running activities
+snippet.service.systemService01.description=Obtain a handle to the manager responsible for providing access to the system alarm services
+snippet.service.systemService02.description=Obtain a handle to the manager responsible for handling volume, ringer modes, audio routing and so on
+snippet.service.systemService03.description=Obtain a handle to the manager responsible for accessing and modifying the contents of the global clipboard
+snippet.service.systemService04.description=Obtain a handle to the manager responsible for answering queries about the state of network connectivity
+snippet.service.systemService05.description=Obtain a handle to the manager responsible for handling input methods
+snippet.service.systemService06.description=Obtain a handle to the manager responsible for locking and unlocking the keyboard
+snippet.service.systemService07.description=Obtain a handle to the manager responsible for instantiating layout XML files into their corresponding View objects
+snippet.service.systemService08.description=Obtain a handle to the manager responsible for providing access to the system location services (geographical location)
+snippet.service.systemService09.description=Obtain a handle to the manager responsible for informing the user about events that happen in the background
+snippet.service.systemService10.description=Obtain a handle to the manager responsible for controlling power management, including "wake locks"
+snippet.service.systemService11.description=Obtain a handle to the manager responsible for providing access to the system search services
+snippet.service.systemService12.description=Obtain a handle to the manager responsible for accessing sensors, such as those that provide information about device orientation and inclination
+snippet.service.systemService13.description=Obtain a handle to the manager responsible for accessing information about the telephony services on the device
+snippet.service.systemService14.description=Obtain a handle to the manager responsible for interacting with the vibration hardware
+snippet.service.systemService15.description=Obtain a handle to the manager responsible for accessing wallpapers
+snippet.service.systemService16.description=Obtain a handle to the manager responsible for managing all aspects of Wi-Fi connectivity
+snippet.service.systemService17.description=Obtain a handle to the manager responsible for granting apps access to the system window manager
+
+
+# -------------------------
+# General
+# -------------------------
+
+category.general=General
+category.general.description=General snippets to use while building your application
+
+snippet.general.sendSMS=Send an SMS
+snippet.general.toast=Display a Toast
+snippet.general.statusBar=Status Bar Notification
+snippet.general.vibrateTime=Vibrate the phone for a given time
+snippet.general.vibratePattern=Vibrate the phone following an on/off pattern
+snippet.general.strictMode=Turn on Strict Mode
+
+
+snippet.general.sendSMS.description=Construct and send an SMS message
+snippet.general.toast.description=Display a "toast" message to the user
+snippet.general.statusBar.description=Display a message in the status bar
+snippet.general.vibrateTime.description=Trigger the vibration hardware for a limited time
+snippet.general.vibratePattern.description=Trigger the vibration hardware to follow an on/off pattern
+snippet.general.strictMode.description=Detect operations executed in the UI that are not recommended and bring them to the user's attention
+
+
+# -------------------------
+# Preferences
+# -------------------------
+
+category.preferences=Preferences
+category.preferences.description=Snippets used to store and retrieve application preferences as key-value pairs.
+
+snippet.preferences.loadSharedPreference=Retrieve shared preference - named preferences file
+snippet.preferences.loadSharedPreference.description=Retrieve a preference value from a named preferences file.
+
+snippet.preferences.loadSharedPreferenceFromPreferenceManager=Retrieve shared preference - single preference file
+snippet.preferences.loadSharedPreferenceFromPreferenceManager.description=Retrieve a shared preference from Preference Manager
+
+snippet.preferences.writeSharedPreference=Write shared preference - named preferences file
+snippet.preferences.writeSharedPreference.description=Write a preference value to a named preferences file.
+
+snippet.preferences.writeSharedPreferenceFromPreferenceManager=Write shared preference - single preference file
+snippet.preferences.writeSharedPreferenceFromPreferenceManager.description=Write a preference value in the one preferences file used by your Activity.
+
+# -------------------------
+# Database
+# -------------------------
+
+category.database=Database
+category.database.description=Database related snippets which use SQLite
+
+snippet.database.createOrOpenDb=Database - Create/Open
+snippet.database.deleteDb=Database - Delete
+snippet.database.createTbl=Table - Create
+snippet.database.deleteTbl=Table - Delete
+snippet.database.insertEntry=Entry - Insert
+snippet.database.updateEntry=Entry - Update
+snippet.database.deleteEntry=Entry - Delete
+snippet.database.runQuery=Run SQL Query
+
+snippet.database.createOrOpenDb.description=Open or create a new SQLite database
+snippet.database.deleteDb.description=Delete a SQLite database
+snippet.database.createTbl.description=Create a new table within a database
+snippet.database.deleteTbl.description=Delete a table from a database
+snippet.database.insertEntry.description=Insert a table row
+snippet.database.updateEntry.description=Update a table row
+snippet.database.deleteEntry.description=Delete a table row
+snippet.database.runQuery.description=Execute a SQL query
+
+
+# -------------------------
+# Menus and Action Bar
+# -------------------------
+
+category.menus=Menus and Action Bar
+category.menus.description=Snippets for working with menu and action bar
+
+snippet.menus.handleItems=Construct and handle an options menu
+snippet.menus.disableItem=Disable a menu item
+snippet.menus.subItem=Add a sub-menu
+snippet.menus.declareMenuXML=XML menu definition
+snippet.menus.inflateMenu=Inflate menu from XML
+snippet.menus.showActionBar=Show action bar
+snippet.menus.hideActionBar=Hide action bar
+snippet.menus.manage.actionbar.label=Action bar - navigation tab mode
+snippet.menus.toggle.actionbar.label=Toggle action bar visibility
+
+snippet.menus.handleItems.description=Example of how to add items to an options menu and handle menu item selection. Add this to your activity.
+snippet.menus.disableItem.description=Disable a menu item, making it unusable
+snippet.menus.subItem.description=Add a sub-menu to a menu item
+snippet.menus.declareMenuXML.description=A menu definition, in XML. Save this in res/menu/ and name it <nameYouWantToReferToThisMenu>.xml
+snippet.menus.inflateMenu.description=Inflate an XML menu definition for use in an activity.
+snippet.menus.showActionBar.description=Programmatically show the action bar
+snippet.menus.hideActionBar.description=Programmatically hide the action bar
+snippet.menus.manage.actionbar.description=Put the action bar in tab mode for navigation
+snippet.menus.toggle.actionbar.description=Show the action bar if it is hidden, and hide it otherwise.
+
+
+# -------------------------
+# Screen
+# -------------------------
+
+category.screen=Screen
+category.screen.description=Snippets related to screen properties
+
+snippet.screen.fullscreen=Make an activity full-screen
+snippet.screen.size=Get the screen size
+snippet.screen.orientation=Get the screen orientation
+
+snippet.screen.fullscreen.description=Expand the current activity so it fits the device's screen
+snippet.screen.size.description=Retrieve the size of the device's screen
+snippet.screen.orientation.description=Retrieve the current screen orientation
+
+
+
+# -------------------------
+# Log
+# -------------------------
+
+category.log=Log
+category.log.description=Snippets for logging messages from an Android application
+
+snippet.log.error=Log ERROR message
+snippet.log.warning=Log WARNING message
+snippet.log.info=Log INFO message
+snippet.log.debug=Log DEBUG message
+
+snippet.log.error.description=Log an ERROR message
+snippet.log.warning.description=Log a WARNING message
+snippet.log.info.description=Log an INFO message
+snippet.log.debug.description=Log a DEBUG message
+
+
+# -------------------------
+# GPS
+# -------------------------
+
+category.gps=GPS
+category.gps.description=Snippets related to GPS location and status
+
+snippet.gps.currentCoordinates=Get current GPS coordinates
+snippet.gps.lastCoordinates=Get last known GPS coordinates
+snippet.gps.distance=Distance between GPS coordinates
+snippet.gps.listenerChanges=Register for GPS status changes
+snippet.gps.listenerProximity=Register for a proximity alert
+
+snippet.gps.currentCoordinates.description=Get the current location of the device
+snippet.gps.lastCoordinates.description=Get the last known location of the device
+snippet.gps.distance.description=Calculate the distance between two locations
+snippet.gps.listenerChanges.description=Register a listener for changes in GPS status
+snippet.gps.listenerProximity.description=Register a listener to be notified when the device is near a given point
+
+
+# -------------------------
+# Media
+# -------------------------
+
+category.media=Media
+category.media.description=Snippets to play/record media files
+
+snippet.media.playAudioVideoRaw=Play audio or video from a file within the application
+snippet.media.playAudioVideoFile=Play audio or video given a path to a file or a URL
+snippet.media.startRecordingAudio=Start recording audio
+snippet.media.stopRecording=Stop recording audio
+
+snippet.media.playAudioVideoRaw.description=Play a media file that is located in a folder inside the application
+snippet.media.playAudioVideoFile.description=Play a media file that is located in the local file system or on the Internet
+snippet.media.startRecordingAudio.description=Record audio and save to a file
+snippet.media.stopRecording.description=Stop the audio recording
+
+
+# -------------------------
+# MOTOROLA API
+# -------------------------
+
+category.motorolaapi=Motorola APIs
+category.motorolaapi.description=Snippets for Motorola APIs
+
+snippet.motorolaapi.ffcamera=Use Front-Facing Camera
+snippet.motorolaapi.hdmi=Retrieve HDMI Status
+
+snippet.motorolaapi.ffcamera.description=Example of how to obtain the camera object that represents the front-facing camera
+snippet.motorolaapi.hdmi.description=Receive notification of HDMI status changes
+
+
+# -------------------------
+# Resources and Assets
+# -------------------------
+
+category.resources=Resources and Assets
+category.resources.description=Snippets to access resources and assets
+
+snippet.resources.listAssets=List your application's assets
+snippet.resources.readFile=Open an asset as a byte stream
+snippet.resources.readXmlFile=Open an asset for parsing as XML
+
+snippet.resources.listAssets.description=Create a list of assets within your application's package
+snippet.resources.readFile.description=Retrieve an InputStream for a named asset
+snippet.resources.readXmlFile.description=Retrieve an XmlResourceParser for a compiled XML file
+
+
+# -------------------------
+# Dialogs
+# -------------------------
+
+category.dialogs=Dialogs
+category.dialogs.description=Snippets to display dialogs
+
+snippet.dialogs.alert=Alert Dialog
+snippet.dialogs.progressDialog=Progress Dialog
+snippet.dialogs.progressBar=Progress Bar Dialog
+snippet.dialogs.datePicker=Date Picker Dialog
+snippet.dialogs.timePicker=Time Picker Dialog
+snippet.dialogs.custom=Custom Dialog
+snippet.dialogs.customAlert=Custom Alert Dialog
+
+snippet.dialogs.alert.description=Display a simple alert dialog with a Yes/No question
+snippet.dialogs.progressDialog.description=Display a simple progress dialog
+snippet.dialogs.progressBar.description=Display a progress bar
+snippet.dialogs.datePicker.description=Construct and display a dialog that allows the user to select a date
+snippet.dialogs.timePicker.description=Construct and display a dialog that allows the user to select a time
+snippet.dialogs.custom.description=Display a dialog with custom content. This dialog must have a title.
+snippet.dialogs.customAlert.description=Display an alert dialog with custom content. This dialog doesn't have to have a title.
+
+
+# -------------------------
+# Web and WebServices
+
+# -------------------------
+
+category.web=Web and Web Services
+
+category.web.description=Samples of how to access web servers from your Android applications
+
+
+
+snippet.web.post=Executing a POST request
+
+snippet.web.get=Executing a GET request
+
+snippet.web.json=Retrieve JSON from a server response
+
+snippet.web.rest=Query for a REST response
+
+snippet.web.email=Send an email
+
+snippet.web.urlconnection=Retrieve data from a URL
+
+snippet.web.soap= SOAP example
+
+
+
+snippet.web.post.description=Executes a post request using the Apache HTTPClient
+
+snippet.web.get.description=Executes a GET request using the Apache HTTPClient
+
+snippet.web.json.description=Retrieve JSON objects from a RESTful web server response. See the "Query for a REST response" snippet to get the response.
+
+snippet.web.email.description=Send an email message where the subject, body, and destination are all text strings
+
+snippet.web.urlconnection.description=Open a connection to a given URL and get the response as a String
+
+snippet.web.soap.description=Example of accessing and parsing SOAP from a web server using the KSoap project
+snippet.web.rest.description=Query for a REST response from a web server using a GET request
+
+
+
+
+
+# -------------------------
+
+# Sensors
+
+# -------------------------
+
+category.sensors=Sensors
+
+category.sensors.description=Use of sensors, such as accelerometer
+
+
+
+snnipet.sensor.detect=Detect a sensor
+
+snnipet.sensor.getorientation=Read data from a sensor
+
+
+
+snnipet.sensor.detect.description=Determine if your device supports a particular sensor
+
+snnipet.sensor.getorientation.description=Read data from an orientation sensor
+
+
+
+
+
+# -------------------------
+
+# SQL
+
+# -------------------------
+
+category.sql=SQL
+
+category.sql.description=Some SQL samples that you can use to mount your queries
+
+
+
+snippet.sql.update=Update a table
+
+snippet.sql.inner=Inner join example
+
+snippet.sql.left=Left join example
+
+snippet.sql.count=Count example
+
+snippet.sql.insert=Insert example
+
+snippet.sql.createfromtable=Create a table with data from another table
+
+snippet.sql.drop=Delete (drop) a table
+
+snippet.sql.delete=Delete rows
+
+snippet.sql.create=Create table
+
+
+
+snippet.sql.update.description=SQL query for updating a table
+
+snippet.sql.inner.description=SQL query for selecting all students from a table students that are also present in the table math_class
+
+snippet.sql.left.description=SQL query for selecting all students from a table students that has grade bigger than 5 in the table math_class
+
+snippet.sql.count.description=How many different cities do our students come from?
+
+snippet.sql.insert.description=Insert a David Bowie album into a database table
+
+snippet.sql.createfromtable.description=Creates a table composed of rock songs from the "songs" table
+
+snippet.sql.drop.description=Deletes a named table
+
+snippet.sql.delete.description=Deletes from a table all songs that have a rating less than 5
+
+snippet.sql.create.description=Creates a table to store songs
+
+
+
+
+
+# -------------------------
+
+# Bluetooth
+
+# -------------------------
+
+category.bluetooth=Bluetooth
+
+category.bluetooth.description=Snippets to access and use the device bluetooth
+
+
+
+snippet.bluetooth.check=Verify that Bluetooth is supported
+
+snippet.bluetooth.enable=Enable Bluetooth
+
+snippet.bluetooth.discoverable=Ensure that this device is discoverable
+
+snippet.bluetooth.getpaired=Get paired devices
+
+snippet.bluetooth.discover=Register for remote device discovery
+
+snippet.bluetooth.incoming=Wait for incoming connections
+
+snippet.bluetooth.connect=Connect to a device
+
+
+
+snippet.bluetooth.check.description=Verify that the device supports Bluetooth by trying to get the Bluetooth adapter
+
+snippet.bluetooth.enable.description=If Bluetooth is supported, enables it such that you receive a callback when it is enabled
+
+snippet.bluetooth.getpaired.description=Gets the set of devices paired with this one
+
+snippet.bluetooth.discover.description=Registers intents for remote device discovery. Also includes a BroadcastReceiver that is notified as each device is found and when the discovery process completes.
+snippet.bluetooth.discoverable.description=If this device is not discoverable, make it so
+
+snippet.bluetooth.incoming.description=Code (likely to run on a thread) that creates a listening, secure RFCOMM Bluetooth socket, retrieves incoming connections, and opens input and output streams connected to the socket.
+
+snippet.bluetooth.connect.description=Connect to a device
+
+
+
+# -------------------------
+
+# Localization
+# -------------------------
+
+category.localization=Localization
+category.localization.description=Snippets to work with localized resources
+
+snippet.localization.string=Get localized string
+snippet.localization.drawable=Get localized drawable
+snippet.localization.curLocale=Get current locale
+snippet.localization.resLocale=Get resource locale
+snippet.localization.dynamicMsg=Create formatted message
+
+snippet.localization.string.description=Get a localized string resource
+snippet.localization.drawable.description=Get a localized drawable resource
+snippet.localization.curLocale.description=Get the current locale from Java
+snippet.localization.resLocale.description=Get the current locale for your application's package
+snippet.localization.dynamicMsg.description=Create a formatted message containing the full language name in the default locale
+
+# -------------------------
+# General UI
+# -------------------------
+category.ui=General UI Utilities
+category.ui.description=Code for handling UIs in an efficient way
+
+snippet.ui.gestures.string=Pixel density independent touch gestures
+snippet.ui.sizes.string=Adjust widget size
+snippet.ui.background.string=Scale bitmap to view size
+snippet.ui.widget.string=Respond to widget interaction
+snippet.ui.moveout.string=Move code out of UI thread
+snippet.ui.backgroundtaskwithnotification.string=Background task with status bar notification
+snippet.ui.hide.statusbar.label=Hide status bar - lights off mode
+snippet.ui.visible.statusbar.label=Make status bar visible
+
+snippet.ui.gestures.description=Make your touch gestures work the same way, independent of the device pixel density.
+snippet.ui.sizes.description=Adjust the size of a widget (a button, in this example) when the enclosing view changes its size.
+snippet.ui.background.description=Resize a bitmap to the size of a view. Useful for creating background images.
+snippet.ui.widget.description=Handle user interaction with a widget (a button, in this example).
+snippet.ui.moveout.description=Use AsyncTask to perform background operations, thus avoiding UI freezes and improving application responsiveness. This helps with Honeycomb (Android 3.0), which enforces the rule "don't do network access in the UI thread" (throws exception).
+snippet.ui.backgroundtaskwithnotification.description=Use AsyncTask to perform a background operation while the user is notified via the status bar.
+snippet.ui.hide.statusbar.description=Hides status bar
+snippet.ui.visible.statusbar.description=Shows status bar (if it was hidden)
+
+# -------------------------
+# Android Intents for basic building blocks
+# -------------------------
+intents.ui=Android Intents
+intents.ui.description=Intent templates to call Activities, Broadcast Receivers, and Services
+
+intents.start.activity.explicitly.label=Start Activity explicitly
+intents.start.activity.explicitly.description=Starts Activity by calling the class (not using id)
+
+intents.start.activity.implicitly.label=Start Activity implicitly
+intents.start.activity.implicitly.description=Starts Activity by using the id, action and category
+
+intents.start.activity.for.result.label=Start Activity for result
+intents.start.activity.for.result.description=Starts Activity and waits for a result
+
+intents.send.broadcast.label=Send Broadcast
+intents.send.broadcast.description=Sends message for broadcast receivers
+
+intents.start.service.label=Start Service
+intents.start.service.description=Binds and starts service
+
+# -------------------------
+# Fragment snippets
+# -------------------------
+
+fragments.ui=Fragment
+fragments.ui.description=Code to manipulate fragments
+
+fragments.replace.transaction.label=Fragment - Replace transaction
+fragments.replace.transaction.description=Replace one fragment by a new one using a animation
+
+fragments.add.transaction.label=Add Fragment programmatically
+fragments.add.transaction.description=Adds one fragment programmatically
+
+# -------------------------
+# Face recognition
+# -------------------------
+category.facerecog=Face recognition
+category.facerecog.description=Basic code for finding faces in a Bitmap
+
+snippet.facerecog.string=Find faces
+
+snippet.facerecog.description=Find faces in Bitmap and how much confidence can you take on them.
diff --git a/src/plugins/snippets/plugin.xml b/src/plugins/snippets/plugin.xml
new file mode 100644
index 0000000..13dd718
--- /dev/null
+++ b/src/plugins/snippets/plugin.xml
@@ -0,0 +1,2086 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse version="3.2"?>
+<plugin>
+ <extension
+ point="org.eclipse.ui.startup">
+ <startup
+ class="com.motorola.studio.android.codesnippets.AndroidSnippetsStartup"></startup>
+ </extension>
+ <extension point="org.eclipse.wst.common.snippets.SnippetContributions">
+ <category
+ description="%category.service.description"
+ id="android_services"
+ label="%category.service">
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.service.systemService00.description"
+ id="com.motorola.studio.android.codesnippets.item3"
+ label="%snippet.service.systemService00">
+ <content>
+ // To use this ActivityManager method, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.GET_TASKS&quot;/&gt;
+ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService01.description"
+ id="com.motorola.studio.android.codesnippets.item4"
+ label="%snippet.service.systemService01">
+ <content>
+ AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService02.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%snippet.service.systemService02">
+ <content>
+ AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService03.description"
+ id="com.motorola.studio.android.codesnippets.item6"
+ label="%snippet.service.systemService03">
+ <content>
+ ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.service.systemService04.description"
+ id="com.motorola.studio.android.codesnippets.item7"
+ label="%snippet.service.systemService04">
+ <content>
+ // To use this ConectivityManager method, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot;/&gt;
+ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService05.description"
+ id="com.motorola.studio.android.codesnippets.item8"
+ label="%snippet.service.systemService05">
+ <content>
+ InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService06.description"
+ id="com.motorola.studio.android.codesnippets.item9"
+ label="%snippet.service.systemService06">
+ <content>
+ KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService07.description"
+ id="com.motorola.studio.android.codesnippets.item10"
+ label="%snippet.service.systemService07">
+ <content>
+ LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService08.description"
+ id="com.motorola.studio.android.codesnippets.item11"
+ label="%snippet.service.systemService08">
+ <content>
+ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService09.description"
+ id="com.motorola.studio.android.codesnippets.item12"
+ label="%snippet.service.systemService09">
+ <content>
+ NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.service.systemService10.description"
+ id="com.motorola.studio.android.codesnippets.item13"
+ label="%snippet.service.systemService10">
+ <content>
+ // To use this PowerManager method, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.DEVICE_POWER&quot;/&gt;
+PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService11.description"
+ id="com.motorola.studio.android.codesnippets.item14"
+ label="%snippet.service.systemService11">
+ <content>
+ SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService12.description"
+ id="com.motorola.studio.android.codesnippets.item15"
+ label="%snippet.service.systemService12">
+ <content>
+ SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.service.systemService13.description"
+ id="com.motorola.studio.android.codesnippets.item32"
+ label="%snippet.service.systemService13">
+ <content>
+ // To use this TelephonyManager method, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.READ_PHONE_STATE&quot;/&gt;
+TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.service.systemService14.description"
+ id="com.motorola.studio.android.codesnippets.item33"
+ label="%snippet.service.systemService14">
+ <content>
+ // To use this Vibrator method, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.VIBRATE&quot;/&gt;
+Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.service.systemService15.description"
+ id="com.motorola.studio.android.codesnippets.item34"
+ label="%snippet.service.systemService15">
+ <content>
+ // To use this WallpaperService method, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.SET_WALLPAPER&quot;/&gt;
+WallpaperService wallpaperService = (WallpaperService) getSystemService(Context.WALLPAPER_SERVICE);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.service.systemService16.description"
+ id="com.motorola.studio.android.codesnippets.item35"
+ label="%snippet.service.systemService16">
+ <content>
+ // To use this WifiManager method, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.ACCESS_WIFI_STATE&quot;/&gt;
+WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
+ </content>
+ </item>
+ <item
+ description="%snippet.service.systemService17.description"
+ id="com.motorola.studio.android.codesnippets.item36"
+ label="%snippet.service.systemService17">
+ <content>
+ WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
+ </content>
+ </item>
+ </category>
+
+
+
+ <category
+ description="%category.general.description"
+ id="android_general"
+ label="%category.general">
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.general.sendSMS.description"
+ id="com.motorola.studio.android.codesnippets.item9"
+ label="%snippet.general.sendSMS">
+ <content>
+ // To use these SmsManager methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.SEND_SMS&quot;/&gt;
+SmsManager m = SmsManager.getDefault();
+String destinationNumber =&quot;0123456789&quot;;
+String text = &quot;Hello!&quot;;
+m.sendTextMessage(destinationNumber, null, text, null, null);
+ </content>
+ </item>
+ <item
+ description="%snippet.general.toast.description"
+ id="com.motorola.studio.android.codesnippets.item8"
+ label="%snippet.general.toast">
+ <content>
+ Toast.makeText(this, &quot;Put your message here&quot;, Toast.LENGTH_SHORT).show();
+ </content>
+ </item>
+ <item
+ description="%snippet.general.statusBar.description"
+ id="com.motorola.studio.android.codesnippets.item31"
+ label="%snippet.general.statusBar">
+ <content>
+ int notificationID = 10;
+NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+// Create the notification
+Notification notification = new Notification(R.drawable.yourIconId, &quot;Put your notification text here&quot;, System.currentTimeMillis());
+// Create the notification's expanded message
+// When the user clicks on it, it opens your activity
+Intent intent = new Intent(this, YourActivityName.class);
+PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
+notification.setLatestEventInfo(this, &quot;Put your title here&quot;, &quot;Put your text here&quot;, pendingIntent);
+// Show notification
+notificationManager.notify(notificationID, notification);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.general.vibrateTime.description"
+ id="com.motorola.studio.android.codesnippets.item6"
+ label="%snippet.general.vibrateTime">
+ <content>
+ // To use these Vibrator methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.VIBRATE&quot;/&gt;
+// Vibrate for 1 second
+Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
+vibrator.vibrate(1000);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.general.vibratePattern.description"
+ id="com.motorola.studio.android.codesnippets.item25"
+ label="%snippet.general.vibratePattern">
+ <content>
+// To use these Vibrator methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.VIBRATE&quot;/&gt;
+// Vibrate in a pattern with 0ms off(start immediately), 200ms on, 100ms off, 100ms on, 500ms off, 500ms on,
+// repeating the pattern starting from index 4: 100ms on.
+// Note that you'll have to call vibrator.cancel() in order to stop the vibrator.
+// Change the second parameter to -1 if you want play the pattern only once.
+Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
+vibrator.vibrate(new long[] {0, 200, 100, 100, 500, 500}, 4);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.general.strictMode.description"
+ id="com.motorola.studio.android.codesnippets.item25"
+ label="%snippet.general.strictMode">
+ <content>
+ // Add or remove any policies and penalties strict mode checking.
+ // This is for application development and testing and should be
+ // removed before your application reaches the market.
+ // For more details of what each method does, check
+ // http://developer.android.com/reference/android/os/StrictMode.ThreadPolicy.Builder.html
+ StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
+ .detectDiskReads()
+ .detectDiskWrites()
+ .detectNetwork() // or .detectAll() for all detectable problems
+ .penaltyDialog()
+ .penaltyLog()
+ .build());
+ StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
+ .detectLeakedSqlLiteObjects()
+ .penaltyLog()
+ .penaltyDeath()
+ .build());
+ // you can also use the penaltyDropBox() as an alternative to displaying a violation occurrence
+ </content>
+ </item>
+ </category>
+
+
+
+
+ <category
+ description="%category.database.description"
+ id="android_database"
+ label="%category.database">
+ <item
+ description="%snippet.database.createOrOpenDb.description"
+ id="com.motorola.studio.android.codesnippets.item29"
+ label="%snippet.database.createOrOpenDb">
+ <content>
+ SQLiteDatabase db =openOrCreateDatabase(&quot;MyDatabaseName&quot;, MODE_PRIVATE, null);
+ </content>
+ </item>
+ <item
+ description="%snippet.database.deleteDb.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%snippet.database.deleteDb">
+ <content>
+ boolean success = deleteDatabase(&quot;MyDatabaseName&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.database.createTbl.description"
+ id="com.motorola.studio.android.codesnippets.item17"
+ label="%snippet.database.createTbl">
+ <content>
+ db.execSQL(&quot;CREATE TABLE MyTableName (_id INTEGER PRIMARY KEY AUTOINCREMENT, YourColumnName TEXT);&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.database.deleteTbl.description"
+ id="com.motorola.studio.android.codesnippets.item18"
+ label="%snippet.database.deleteTbl">
+ <content>
+ db.execSQL(&quot;DROP TABLE IF EXISTS MyTableName&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.database.insertEntry.description"
+ id="com.motorola.studio.android.codesnippets.item20"
+ label="%snippet.database.insertEntry">
+ <content>
+ // Since SQL doesn&apos;t allow the insertion of a completely empty row, the second parameter of db.insert defines the column that will receive NULL if cv is empty
+ContentValues cv=new ContentValues();
+cv.put(&quot;YourColumnName&quot;, &quot;YourColumnValue&quot;);
+db.insert(&quot;MyTableName&quot;, &quot;YourColumnName&quot;, cv);
+ </content>
+ </item>
+ <item
+ description="%snippet.database.updateEntry.description"
+ id="com.motorola.studio.android.codesnippets.item21"
+ label="%snippet.database.updateEntry">
+ <content>
+ ContentValues cv=new ContentValues();
+cv.put(&quot;YourColumnName&quot;, &quot;YourColumnValue&quot;);
+db.update(&quot;MyTableName&quot;, cv, &quot;_id=?&quot;, new String[]{&quot;1&quot;});
+ </content>
+ </item>
+ <item
+ description="%snippet.database.deleteEntry.description"
+ id="com.motorola.studio.android.codesnippets.item22"
+ label="%snippet.database.deleteEntry">
+ <content>
+ db.delete(&quot;MyTableName&quot;,&quot;_id=?&quot;, new String[]{&quot;1&quot;});
+ </content>
+ </item>
+ <item
+ description="%snippet.database.runQuery.description"
+ id="com.motorola.studio.android.codesnippets.item23"
+ label="%snippet.database.runQuery">
+ <content>
+ Cursor c=db.rawQuery(SQL_COMMAND, null);
+ </content>
+ </item>
+ </category>
+
+
+
+
+
+ <category
+ description="%category.menus.description"
+ id="android_menus"
+ label="%category.menus">
+ <item
+ description="%snippet.menus.handleItems.description"
+ id="com.motorola.studio.android.codesnippets.item3"
+ label="%snippet.menus.handleItems">
+ <content>
+ /*
+* Add this in your Activity
+*/
+private final int MENU_ITEM_0 = 0;
+private final int MENU_ITEM_1 = 1;
+
+
+/**
+ * Add menu items
+ *
+ * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
+ */
+public boolean onCreateOptionsMenu(Menu menu) {
+ menu.add(0, MENU_ITEM_0, 0, &quot;Menu Item 0&quot;);
+ menu.add(0, MENU_ITEM_1, 0, &quot;Menu Item 1&quot;);
+ return true;
+}
+
+/**
+ * Define menu action
+ *
+ * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
+ */
+public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case MENU_ITEM_0:
+ // put your code here
+ break;
+ case MENU_ITEM_1:
+ // put your code here
+ break;
+ default:
+ // put your code here
+ }
+ return false;
+}
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.disableItem.description"
+ id="com.motorola.studio.android.codesnippets.item2"
+ label="%snippet.menus.disableItem">
+ <content>
+ menu.findItem(&quot;yourItemId&quot;).setEnabled(false);
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.subItem.description"
+ id="com.motorola.studio.android.codesnippets.item3"
+ label="%snippet.menus.subItem">
+ <content>
+ SubMenu subMenu = menu.addSubMenu(&quot;YourMenu&quot;);
+ subMenu.add(&quot;YourSubMenu1&quot;);
+
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.declareMenuXML.description"
+ id="com.motorola.studio.android.codesnippets.item4"
+ label="%snippet.menus.declareMenuXML">
+ <content>
+ &lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;
+ &lt;item android:id=&quot;@+id/menu_0&quot;
+ android:title=&quot;Menu Item 0&quot; /&gt;
+ &lt;item android:id=&quot;@+id/menu_1&quot;
+ android:title=&quot;Menu Item 1&quot; /&gt;
+&lt;/menu&gt;
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.inflateMenu.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%snippet.menus.inflateMenu">
+ <content>
+ /**
+* Inflate Menu from XML
+*/
+public boolean onCreateOptionsMenu(Menu menu) {
+ super.onCreateOptionsMenu(menu);
+ MenuInflater inflater = getMenuInflater();
+ inflater.inflate(R.menu.yourXMLName, menu);
+ return true;
+}
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.showActionBar.description"
+ id="com.motorola.studio.android.codesnippets.item6"
+ label="%snippet.menus.showActionBar">
+ <content>
+ //Notes:
+// - The Action Bar was introduced in API level 11.
+// If you set minSDKVersion &lt; 11 or targetSDKVersion &lt; 11 or
+// if you do not set any of these, getActionBar() will return null.
+// - If you removed the Action Bar using a theme,
+// getActionBar() will return null.
+if (getActionBar() != null){
+ getActionBar().show();
+}
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.hideActionBar.description"
+ id="com.motorola.studio.android.codesnippets.item7"
+ label="%snippet.menus.hideActionBar">
+ <content>
+ //Notes:
+// - The Action Bar was introduced in API level 11.
+// If you set minSDKVersion &lt; 11 or targetSDKVersion &lt; 11 or
+// if you do not set any of these, getActionBar() will return null.
+// - If you removed the Action Bar using a theme,
+// getActionBar() will return null.
+if (getActionBar() != null){
+ getActionBar().hide();
+}
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.toggle.actionbar.description"
+ id="com.motorola.studio.android.codesnippets.item9"
+ label="%snippet.menus.toggle.actionbar.label">
+ <content>
+ //Toggles action bar state (If visible, hides it. If hidden, shows it)
+ActionBar bar = getActionBar();
+if (bar != null) {
+ if (bar.isShowing()) {
+ bar.hide();
+ }
+ else {
+ bar.show();
+ }
+}
+ </content>
+ </item>
+ <item
+ description="%snippet.menus.manage.actionbar.description"
+ id="com.motorola.studio.android.codesnippets.item8"
+ label="%snippet.menus.manage.actionbar.label">
+ <content>
+ //Sets the action bar navigation mode
+ActionBar actionBar = getActionBar();
+actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.dialogs.description"
+ id="android_dialogs"
+ label="%category.dialogs">
+ <item
+ description="%snippet.dialogs.alert.description"
+ id="com.motorola.studio.android.codesnippets.item26"
+ label="%snippet.dialogs.alert">
+ <content>
+ AlertDialog.Builder builder = new AlertDialog.Builder(this);
+builder.setMessage(&quot;Put your question here?&quot;)
+ .setCancelable(false)
+ .setPositiveButton(&quot;Yes&quot;, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ // put your code here
+ }
+ })
+ .setNegativeButton(&quot;No&quot;, new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int id) {
+ // put your code here
+ dialog.cancel();
+ }
+ });
+AlertDialog alertDialog = builder.create();
+alertDialog.show();
+ </content>
+ </item>
+ <item
+ description="%snippet.dialogs.progressDialog"
+ id="com.motorola.studio.android.codesnippets.item27"
+ label="%snippet.dialogs.progressDialog">
+ <content>
+ ProgressDialog dialog = ProgressDialog.show(this, &quot;Your Title&quot;, &quot;Put your message here&quot;, true);
+ </content>
+ </item>
+ <item
+ description="%snippet.dialogs.progressBar.description"
+ id="com.motorola.studio.android.codesnippets.item29"
+ label="%snippet.dialogs.progressBar">
+ <content>
+ ProgressDialog progressDialog = new ProgressDialog(this);
+progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
+progressDialog.setMax(PROGRESS_MAX);
+progressDialog.setMessage(&quot;Put your message here&quot;);
+progressDialog.setCancelable(false);
+progressDialog.incrementProgressBy(PROGRESS_INCREMENT);
+ </content>
+ </item>
+ <item
+ description="%snippet.dialogs.datePicker.description"
+ id="com.motorola.studio.android.codesnippets.item28"
+ label="%snippet.dialogs.datePicker">
+ <content>
+ // Define the date picker dialog listener, which will be called after
+// the user picks a date in the displayed dialog
+DatePickerDialog.OnDateSetListener datePickerDialogListener =
+ new DatePickerDialog.OnDateSetListener() {
+
+ public void onDateSet(DatePicker view, int year,
+ int monthOfYear, int dayOfMonth) {
+ // put your code here
+ // update your model/view with the date selected by the user
+ }
+ };
+
+// Get the current date
+Calendar calendar = Calendar.getInstance();
+int year = calendar.get(Calendar.YEAR);
+int month = calendar.get(Calendar.MONTH);
+int day = calendar.get(Calendar.DAY_OF_MONTH);
+
+// Create a date picker dialog
+DatePickerDialog datePickerDialog = new DatePickerDialog(this,
+ datePickerDialogListener,
+ year, month, day);
+
+// Display the date picker dialog
+datePickerDialog.show();
+
+ </content>
+ </item>
+ <item
+ description="%snippet.dialogs.timePicker.description"
+ id="com.motorola.studio.android.codesnippets.item25"
+ label="%snippet.dialogs.timePicker">
+ <content>
+ // Define the date picker dialog listener, which will be called after
+// the user picks a time in the displayed dialog
+TimePickerDialog.OnTimeSetListener timePickerDialogListener =
+ new TimePickerDialog.OnTimeSetListener() {
+ public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
+ // put your code here
+ // update your model/view with the date selected by the user
+ }
+ };
+
+// Get the current time
+Calendar c = Calendar.getInstance();
+int hour = c.get(Calendar.HOUR_OF_DAY);
+int minute = c.get(Calendar.MINUTE);
+
+// Create a time picker dialog
+TimePickerDialog timerPickerDialog = new TimePickerDialog(this,
+ timePickerDialogListener, hour, minute, false);
+
+// Display the time picker dialog
+timerPickerDialog.show();
+
+ </content>
+ </item>
+ <item
+ description="%snippet.dialogs.custom.description"
+ id="com.motorola.studio.android.codesnippets.item30"
+ label="%snippet.dialogs.custom">
+ <content>
+ Dialog dialog = new Dialog(this);
+dialog.setContentView(R.layout.yourLayoutId);
+dialog.show();
+
+ </content>
+ </item>
+ <item
+ id="com.motorola.studio.android.codesnippets.item9"
+ label="%snippet.dialogs.customAlert">
+ <content>
+ LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+View layout = inflater.inflate(R.layout.yourLayoutId, (ViewGroup) findViewById(R.id.yourLayoutRoot));
+AlertDialog.Builder builder = new AlertDialog.Builder(this)
+ .setView(layout);
+AlertDialog alertDialog = builder.create();
+alertDialog.show();
+
+ </content>
+ </item>
+ </category>
+
+
+
+
+ <category
+ description="%category.screen.description"
+ id="android_screen"
+ label="%category.screen">
+ <item
+ description="%snippet.screen.fullscreen.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%snippet.screen.fullscreen">
+ <content>
+ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
+ </content>
+ </item>
+ <item
+ description="%snippet.screen.size.description"
+ id="com.motorola.studio.android.codesnippets.item24"
+ label="%snippet.screen.size">
+ <content>
+ Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
+int width = display.getWidth();
+int height = display.getHeight();
+ </content>
+ </item>
+ <item
+ description="%snippet.screen.orientation.description"
+ id="com.motorola.studio.android.codesnippets.item1"
+ label="%snippet.screen.orientation">
+ <content>
+ Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
+int orientation = display.getOrientation();
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.gps.description"
+ id="android_gps"
+ label="%category.gps">
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.gps.currentCoordinates.description"
+ id="com.motorola.studio.android.codesnippets.item6"
+ label="%snippet.gps.currentCoordinates">
+ <content>
+ // To use these LocationManager methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot;/&gt;
+LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
+locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
+ public void onStatusChanged(String provider, int status, Bundle extras) {
+ // called when the location provider status changes. Possible status: OUT_OF_SERVICE, TEMPORARILY_UNAVAILABLE or AVAILABLE.
+ }
+ public void onProviderEnabled(String provider) {
+ // called when the location provider is enabled by the user
+ }
+ public void onProviderDisabled(String provider) {
+ // called when the location provider is disabled by the user. If it is already disabled, it&apos;s called immediately after requestLocationUpdates
+ }
+
+ public void onLocationChanged(Location location) {
+ double latitute = location.getLatitude();
+ double longitude = location.getLongitude();
+ // do whatever you want with the coordinates
+ }
+});
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.gps.lastCoordinates.description"
+ id="com.motorola.studio.android.codesnippets.item4"
+ label="%snippet.gps.lastCoordinates">
+ <content>
+ // To use these LocationManager methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot;/&gt;
+LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
+Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
+double latitute, longitude = 0;
+if(location != null){
+ latitute = location.getLatitude();
+ longitude = location.getLongitude();
+}
+
+ </content>
+ </item>
+ <item
+ description="%snippet.gps.distance.description"
+ id="com.motorola.studio.android.codesnippets.item7"
+ label="%snippet.gps.distance">
+ <content>
+ Location originLocation = new Location(&quot;gps&quot;);
+Location destinationLocation = new Location(&quot;gps&quot;);
+originLocation.setLatitude(originLatitude);
+originLocation.setLongitude(originLongitude);
+destinationLocation.setLatitude(originLatitude);
+destinationLocation.setLongitude(originLongitude);
+float distance = originLocation.distanceTo(destinationLocation);
+
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.gps.listenerChanges.description"
+ id="com.motorola.studio.android.codesnippets.item1"
+ label="%snippet.gps.listenerChanges">
+ <content>
+ // To use these LocationManager methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot;/&gt;
+LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
+locationManager.addGpsStatusListener(new GpsStatus.Listener(){
+
+ public void onGpsStatusChanged(int event) {
+ switch(event){
+ // Event sent when the GPS system has started
+ case GpsStatus.GPS_EVENT_STARTED:
+ // put your code here
+ break;
+
+ // Event sent when the GPS system has stopped
+ case GpsStatus.GPS_EVENT_STOPPED:
+ // put your code here
+ break;
+
+ // Event sent when the GPS system has received its first fix since starting
+ case GpsStatus.GPS_EVENT_FIRST_FIX:
+ // put your code here
+ break;
+
+ // Event sent periodically to report GPS satellite status
+ case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
+ // put your code here
+ break;
+
+ }
+ }
+});
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.gps.listenerProximity.description"
+ id="com.motorola.studio.android.codesnippets.item2"
+ label="%snippet.gps.listenerProximity">
+ <content>
+ // To use these LocationManager methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.ACCESS_FINE_LOCATION&quot;/&gt;
+// Use PendingIntent.getActivity(Context, int, Intent, int), PendingIntent.getBroadcast(Context, int, Intent, int) or PendingIntent.getService(Context, int, Intent, int) to create the PendingIntent, which will be used to generate an Intent to fire when the proximity condition is satisfied.
+PendingIntent pendingIntent;
+// latitude the latitude of the central point of the alert region
+// longitude the longitude of the central point of the alert region
+// radius the radius of the alert region, in meters
+LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
+locationManager.addProximityAlert(latitude, longitude, radius, -1, pendingIntent);
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.media.description"
+ id="android_media"
+ label="%category.media">
+ <item
+ description="%snippet.media.playAudioVideoRaw.description"
+ id="com.motorola.studio.android.codesnippets.item17"
+ label="%snippet.media.playAudioVideoRaw">
+ <content>
+ // Put the media file into the res/raw folder of your application
+MediaPlayer mp = MediaPlayer.create(this, R.raw.yourSoundId);
+mp.start();
+ </content>
+ </item>
+ <item
+ description="%snippet.media.playAudioVideoFile.description"
+ id="com.motorola.studio.android.codesnippets.item18"
+ label="%snippet.media.playAudioVideoFile">
+ <content>
+ MediaPlayer mp = new MediaPlayer();
+mp.setDataSource(FILE_PATH_OR_URL);
+mp.prepare();
+mp.start();
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.media.startRecordingAudio.description"
+ id="com.motorola.studio.android.codesnippets.item16"
+ label="%snippet.media.startRecordingAudio">
+ <content>
+ // To use these MediaRecorder methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.RECORD_AUDIO&quot;/&gt;
+MediaRecorder recorder = new MediaRecorder();
+recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
+recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
+recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
+recorder.setOutputFile(PATH_NAME); // The file must already exist
+recorder.prepare();
+recorder.start();
+ </content>
+ </item>
+ <item
+ description="%snippet.media.stopRecording.description"
+ id="com.motorola.studio.android.codesnippets.item21"
+ label="%snippet.media.stopRecording">
+ <content>
+ recorder.stop();
+recorder.release();
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.motorolaapi.description"
+ id="android_motorolaapi"
+ label="%category.motorolaapi">
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.motorolaapi.ffcamera.description"
+ id="com.motorola.studio.android.codesnippets.motorolaapi1"
+ label="%snippet.motorolaapi.ffcamera">
+ <content>
+ // To use these Camera methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.CAMERA&quot;/&gt;
+// Add an import com.motorola.hardware.frontcamera.FrontCamera; statement
+// Add an import android.hardware.Camera; statement
+// Note that you need to add a Motorola library to make this work.
+// See more details at:
+// https://developer.motorola.com/docstools/library/motorola-front-facing-camera-api/
+
+Camera frontCam = FrontCamera.getFrontCamera();
+// the frontCam object represents the front-facing camera
+// treat it like any other Camera object
+frontCam.release(); // always release when done with the Camera object
+ </content>
+ </item>
+ <item description="%snippet.motorolaapi.hdmi.description"
+ id="com.motorola.studio.android.codesnippets.motorolaapi2"
+ label="%snippet.motorolaapi.hdmi">
+ <content>
+// Insert the code below into the onReceive method of a BroadcastReceiver class
+// This broadcast receiver must have the following intent filter:
+// &lt;intent-filter&gt;
+// &lt;action android:name="com.motorola.intent.action.externaldisplaystate"/&gt;
+// &lt;/intent-filter&gt;
+// More details about Motorola HDMI Status API are available at:
+// https://developer.motorola.com/docstools/library/motorola-hdmi-status-api/
+final String EXTDISP_PUBLIC_STATE = "com.motorola.intent.action.externaldisplaystate";
+final String EXTRA_HDCP = "";
+final String EXTRA_HDMI = "";
+
+String action = intent.getAction();
+Bundle extras = (intent != null) ? intent.getExtras() : null;
+
+if (action.equals(EXTDISP_PUBLIC_STATE))
+{
+ if (extras != null)
+ {
+ int hdmi = extras.getInt(EXTRA_HDMI);
+ int hdcp = extras.getInt(EXTRA_HDCP);
+ // Application decides what to do with this information
+ }
+}
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.preferences.description"
+ id="com.motorola.studio.android.codesnippets.category2"
+ label="%category.preferences">
+ <item
+ description="%snippet.preferences.loadSharedPreference.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%snippet.preferences.loadSharedPreference">
+ <content>
+// Use MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE to grant access to other applications
+SharedPreferences preferences = getSharedPreferences(&quot;YourPreferencesName&quot;, MODE_PRIVATE);
+String preferenceValue = preferences.getString(&quot;yourPreferenceKey&quot;, &quot;defaultValue&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.preferences.loadSharedPreferenceFromPreferenceManager.description"
+ id="com.motorola.studio.android.codesnippets.item8"
+ label="%snippet.preferences.loadSharedPreferenceFromPreferenceManager">
+ <content>
+// Use MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE to grant access to other applications
+SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+String preferenceValue = preferences.getString(&quot;yourPreferenceKey&quot;, &quot;defaultValue&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.preferences.writeSharedPreference.description"
+ id="com.motorola.studio.android.codesnippets.item7"
+ label="%snippet.preferences.writeSharedPreference">
+ <content>
+// Use MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE to grant access to other applications
+SharedPreferences preferences = getSharedPreferences(&quot;YourPreferencesName&quot;, MODE_PRIVATE);
+SharedPreferences.Editor editor = preferences.edit();
+editor.putString(&quot;yourPreferenceKey&quot;, &quot;Your Preference Value&quot;);
+editor.commit();
+ </content>
+ </item>
+ <item
+ description="%snippet.preferences.writeSharedPreferenceFromPreferenceManager.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%snippet.preferences.writeSharedPreferenceFromPreferenceManager">
+ <content>
+// Use MODE_WORLD_READABLE and/or MODE_WORLD_WRITEABLE to grant access to other applications
+SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
+SharedPreferences.Editor editor = preferences.edit();
+editor.putString(&quot;yourPreferenceKey&quot;, &quot;Your Preference Value&quot;);
+editor.commit();
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.resources.description"
+ id="android_resources"
+ label="%category.resources">
+ <item
+ description="%snippet.resources.listAssets.description"
+ id="com.motorola.studio.android.codesnippets.item24"
+ label="%snippet.resources.listAssets">
+ <content>
+ String fileArray[] = this.getAssets().list(&quot;&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.resources.readFile.description"
+ id="com.motorola.studio.android.codesnippets.item22"
+ label="%snippet.resources.readFile">
+ <content>
+ InputStream is = this.getAssets().open(fileName);
+ </content>
+ </item>
+ <item
+ description="%snippet.resources.readXmlFile.description"
+ id="com.motorola.studio.android.codesnippets.item23"
+ label="%snippet.resources.readXmlFile">
+ <content>
+ XmlResourceParser xmlParser = this.getAssets().openXmlResourceParser(fileName);
+
+ </content>
+ </item>
+ </category>
+
+
+
+ <category
+ description="%category.log.description"
+ id="android_log"
+ label="%category.log">
+ <item
+ description="%snippet.log.error.description"
+ id="com.motorola.studio.android.codesnippets.item16"
+ label="%snippet.log.error">
+ <content>
+ Log.e(&quot;YourIdentifier&quot;,&quot;This is an error message&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.log.warning.description"
+ id="com.motorola.studio.android.codesnippets.item26"
+ label="%snippet.log.warning">
+ <content>
+ Log.w(&quot;YourIdentifier&quot;,&quot;This is a warning message&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.log.info.description"
+ id="com.motorola.studio.android.codesnippets.item27"
+ label="%snippet.log.info">
+ <content>
+ Log.i(&quot;YourIdentifier&quot;,&quot;This is an information message&quot;);
+ </content>
+ </item>
+ <item
+ description="%snippet.log.debug.description"
+ id="com.motorola.studio.android.codesnippets.item28"
+ label="%snippet.log.debug">
+ <content>
+ Log.d(&quot;YourIdentifier&quot;,&quot;This is a debug message&quot;);
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.localization.description"
+ id="android_localization"
+ label="%category.localization">
+ <item
+ description="%snippet.localization.string.description"
+ id="com.motorola.studio.android.codesnippets.item1"
+ label="%snippet.localization.string">
+ <content>
+ String text = getResources().getString(R.string.yourStringID);
+ </content>
+ </item>
+ <item
+ description="%snippet.localization.drawable.description"
+ id="com.motorola.studio.android.codesnippets.item2"
+ label="%snippet.localization.drawable">
+ <content>
+ Drawable drawable = getResources().getDrawable(R.drawable.yourDrawableID);
+ </content>
+ </item>
+ <item
+ description="%snippet.localization.curLocale.description"
+ id="com.motorola.studio.android.codesnippets.item4"
+ label="%snippet.localization.curLocale">
+ <content>
+ Locale curLocale = java.util.Locale.getDefault();
+ </content>
+ </item>
+ <item
+ description="%snippet.localization.resLocale.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%snippet.localization.resLocale">
+ <content>
+ Locale resLocale = getResources().getConfiguration().locale;
+ </content>
+ </item>
+ <item
+ description="%snippet.localization.dynamicMsg.description"
+ id="com.motorola.studio.android.codesnippets.item3"
+ label="%snippet.localization.dynamicMsg">
+ <content>
+ // yourMsgID =&quot;The language is {0}&quot;
+String msg = getResources().getString(R.string.yourMsgID);
+Object[] arguments = {
+ java.util.Locale.getDefault().getDisplayLanguage()
+};
+String fullMsg = java.text.MessageFormat.format(msg, arguments);
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.bluetooth.description"
+ id="android_bluetooth"
+ label="%category.bluetooth">
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.bluetooth.check.description"
+ id="com.motorola.studio.android.codesnippets.bt1"
+ label="%snippet.bluetooth.check">
+ <content>
+ // To use this BluetoothAdapter method, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;
+// Trying to get the adapter
+BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
+
+if (btAdapter == null) {
+ // Bluetooth is not supported, do something here to warn the user
+ return;
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.bluetooth.connect.description"
+ id="com.motorola.studio.android.codesnippets.bt7"
+ label="%snippet.bluetooth.connect">
+ <content>
+ // To use these BluetoothAdapter methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;
+/*
+ * This code is loose here but you will
+ * likely use it inside a thread
+ *
+ * Make sure you have the &apos;device&apos; variable (BluetoothDevice)
+ * at the point you insert this code
+ */
+
+// UUID for your application
+UUID MY_UUID = UUID.fromString(&quot;yourdata&quot;);
+
+// Get the adapter
+BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
+
+// The socket
+BluetoothSocket socket = null;
+try {
+ // Your app UUID string (is also used by the server)
+ socket = device.createRfcommSocketToServiceRecord(MY_UUID);
+} catch (IOException e) { }
+
+// For performance reasons
+btAdapter.cancelDiscovery();
+
+try {
+ // Be aware that this is a blocking operation. You probably want to use this in a thread
+ socket.connect();
+
+} catch (IOException connectException) {
+ // Unable to connect; close the socket and get out
+ try {
+ socket.close();
+ } catch (IOException closeException) {
+ // Deal with it
+ }
+ return;
+}
+
+// Now manage your connection (in a separate thread)
+myConnectionManager(socket);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.bluetooth.enable.description"
+ id="com.motorola.studio.android.codesnippets.bt2"
+ label="%snippet.bluetooth.enable">
+ <content>
+ // To use these BluetoothAdapter methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;
+/* This number is used to identify this request (&quot;Enable Bluetooth&quot;)
+ * when the callback method onActivityResult() is called. Your
+ * interaction with the Bluetooth stack will probably start there.
+ *
+ * You probably want to insert this as a global variable
+ */
+int ENABLE_BLUETOOTH = 1;
+
+// Get the adapter
+BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
+
+if (btAdapter == null) {
+ return;
+}
+
+// If Bluetooth is not yet enabled, enable it
+if (!btAdapter.isEnabled()) {
+ Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
+ startActivityForResult(enableBluetooth, ENABLE_BLUETOOTH);
+ // Now implement the onActivityResult() and wait for it to be invoked with ENABLE_BLUETOOTH
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.bluetooth.getpaired.description"
+ id="com.motorola.studio.android.codesnippets.bt4"
+ label="%snippet.bluetooth.getpaired">
+ <content>
+ // To use these BluetoothAdapter methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;
+// Get the adapter
+BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
+
+// Get the paired devices
+Set&lt;BluetoothDevice&gt; devices = btAdapter.getBondedDevices();
+
+// If there are paired devices, do whatever you&apos;re supposed to do
+if (devices.size() &gt; 0) {
+ for (BluetoothDevice pairedDevice : devices) {
+ // do something useful with the device
+ }
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.bluetooth.discoverable.description"
+ id="com.motorola.studio.android.codesnippets.bt3"
+ label="%snippet.bluetooth.discoverable">
+ <content>
+ // To use these BluetoothAdapter methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;
+//Get the adapter
+BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
+
+if (btAdapter == null) {
+ return;
+}
+
+// If Bluetooth is not discoverable, make it discoverable
+if (btAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
+ Intent makeDiscoverable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
+ makeDiscoverable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
+ // In a real situation you would probably use startActivityForResult to get the user&apos;s choice.
+ startActivity(makeDiscoverable);
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.bluetooth.incoming.description"
+ id="com.motorola.studio.android.codesnippets.bt6"
+ label="%snippet.bluetooth.incoming">
+ <content>
+ // To use these BluetoothAdapter methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;
+// UUID for your application
+UUID MY_UUID = UUID.fromString(&quot;yourdata&quot;);
+
+// SDP record name used when creating the server socket
+String NAME = &quot;BluetoothExample&quot;;
+
+// The server socket
+BluetoothServerSocket btServerSocket = null;
+
+// The adapter
+BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
+
+// The socket
+BluetoothSocket socket = null;
+
+try {
+ btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
+
+ // This operation is blocking: you will wait until it returns or an error occurs
+ socket = btServerSocket.accept();
+} catch (IOException e) {
+ // Deal with it
+}
+
+if (socket != null) {
+ /* The connection was accepted. Do what you want to do.
+ * For example, get the streams
+ */
+ InputStream inputStream = null;
+ OutputStream outputStream = null;
+ try {
+ inputStream = socket.getInputStream();
+ outputStream = socket.getOutputStream();
+ } catch (IOException e) {
+ // Deal with it
+ }
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.bluetooth.discover.description"
+ id="com.motorola.studio.android.codesnippets.bt5"
+ label="%snippet.bluetooth.discover">
+ <content>
+ // To use these BluetoothDevice methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot;/&gt;
+
+// BroadcastReceiver that is notified as each device is found and when the discovery process completes
+// Should be an internal class or in a separate .java file
+final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ String action = intent.getAction();
+
+ // Device was discovered
+ if (BluetoothDevice.ACTION_FOUND.equals(action)) {
+ BluetoothDevice device =
+intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
+ if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
+ // device is not already paired. Do something useful here.
+ }
+ // Discovery is finished
+ } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
+ // do something useful here
+ }
+ }
+};
+
+// Register for notification upon discovery of a Bluetooth device
+IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
+this.registerReceiver(bluetoothReceiver, intentFilter);
+
+// Register for notification upon completion of the device discovery process
+intentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
+this.registerReceiver(bluetoothReceiver, intentFilter);
+
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.sql.description"
+ id="android_sql"
+ label="%category.sql">
+ <item
+ description="%snippet.sql.create.description"
+ id="com.motorola.studio.android.codesnippets.sql1"
+ label="%snippet.sql.create">
+ <content>
+ CREATE TABLE songs(
+ id INTEGER,
+ name TEXT,
+ genre TEXT,
+ rate REAL,
+ some_raw_data BLOB
+);
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.createfromtable.description"
+ id="com.motorola.studio.android.codesnippets.sql2"
+ label="%snippet.sql.createfromtable">
+ <content>
+ SELECT * INTO rockssongs
+FROM songs WHERE genre =&apos;rock&apos;;
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.count.description"
+ id="com.motorola.studio.android.codesnippets.sql3"
+ label="%snippet.sql.count">
+ <content>
+ SELECT COUNT(DISTINCT student_city) AS total
+FROM students;
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.delete.description"
+ id="com.motorola.studio.android.codesnippets.sql4"
+ label="%snippet.sql.delete">
+ <content>
+DELETE FROM songs
+WHERE rating&lt; 5;
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.drop.description"
+ id="com.motorola.studio.android.codesnippets.sql5"
+ label="%snippet.sql.drop">
+ <content>
+ DROP TABLE&quot;bad_songs&quot;;
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.left.description"
+ id="com.motorola.studio.android.codesnippets.sql6"
+ label="%snippet.sql.left">
+ <content>
+ SELECT students.name
+FROM students LEFT JOIN math_class
+ ON students.id = math_class.student_id
+WHERE math_class.grade &gt; 5;
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.inner.description"
+ id="com.motorola.studio.android.codesnippets.sql7"
+ label="%snippet.sql.inner">
+ <content>
+ SELECT DISTINCT students.id, students.name
+FROM students INNER JOIN math_class ON students.id = math_class.student_id;
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.insert.description"
+ id="com.motorola.studio.android.codesnippets.sql8"
+ label="%snippet.sql.insert">
+ <content>
+ INSERT INTO albums(ambum_id, artist_name, album_name)
+VALUES(&apos;12345&apos;, &apos;David Bowie&apos;,&apos;Ziggy Stardust&apos;);
+ </content>
+ </item>
+ <item
+ description="%snippet.sql.update.description"
+ id="com.motorola.studio.android.codesnippets.sql9"
+ label="%snippet.sql.update">
+ <content>
+ UPDATE songs SET already_listened =&quot;yes&quot;
+WHERE genre = &quot;rock&quot;;
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.web.description"
+ id="android_web"
+ label="%category.web">
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.web.get.description"
+ id="com.motorola.studio.android.codesnippets.web1"
+ label="%snippet.web.get">
+ <content>
+ // To use these Internet methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
+URI myURI = null;
+try {
+ myURI = new URI(&quot;www.webserver.org&quot;);
+} catch (URISyntaxException e) {
+ // Deal with it
+}
+HttpClient httpClient = new DefaultHttpClient();
+HttpGet getMethod = new HttpGet(myURI);
+HttpResponse webServerResponse = null;
+try {
+ webServerResponse = httpClient.execute(getMethod);
+} catch (ClientProtocolException e) {
+ // Deal with it
+} catch (IOException e) {
+ // Deal with it
+}
+
+HttpEntity httpEntity = webServerResponse.getEntity();
+
+if (httpEntity != null) {
+ // You have your response; handle it. For instance, with an input
+ // stream
+ // InputStream input = entity.getContent();
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.web.post.description"
+ id="com.motorola.studio.android.codesnippets.web2"
+ label="%snippet.web.post">
+ <content>
+ // To use these Internet methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
+// Create the Apache HTTP client and post
+ HttpClient httpclient = new DefaultHttpClient();
+ HttpPost httppost = new HttpPost(&quot;http://www.website.org/service.php&quot;);
+
+ try {
+ // Add data to your post
+ List&lt;NameValuePair&gt; pairs = new ArrayList&lt;NameValuePair&gt;(2);
+ pairs.add(new BasicNameValuePair(&quot;ID&quot;, &quot;VALUE&quot;));
+ pairs.add(new BasicNameValuePair(&quot;string&quot;, &quot;Yeah!&quot;));
+ httppost.setEntity(new UrlEncodedFormEntity(pairs));
+
+ //Finally, execute the request
+ HttpResponse webServerAnswer = httpclient.execute(httppost);
+
+ } catch (ClientProtocolException e) {
+ //Deal with it
+ } catch (IOException e) {
+ //Deal with it
+ }
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.web.json.description"
+ id="com.motorola.studio.android.codesnippets.web3"
+ label="%snippet.web.json">
+ <content>
+ // To use these Internet methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
+// The JSON objects
+JSONObject myJSON = null;
+JSONArray names = null;
+JSONArray values = null;
+
+String restWebServerResponse = &quot;TheResponse&quot;;
+try{
+ myJSON = new JSONObject(restWebServerResponse);
+ names = myJSON.names();
+ values = myJSON.toJSONArray(names);
+}
+catch (JSONException e) {
+ // Deal with it
+}
+
+for (int i = 0; i &lt; values.length(); i++) {
+ // Do something with values.getString(i)
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.web.rest.description"
+ id="com.motorola.studio.android.codesnippets.web4"
+ label="%snippet.web.rest">
+ <content>
+ // To use these Internet methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
+// This assumes that you have a URL from which to get the answer
+URI myURL = new URI(&quot;www.website.org&quot;);
+
+// The HTTP objects
+HttpClient httpClient = new DefaultHttpClient();
+HttpGet getMethod = new HttpGet(myURL);
+HttpResponse httpResponse;
+
+// The query result
+String result = null;
+
+try {
+ httpResponse = httpClient.execute(getMethod);
+ // You might want to check response.getStatusLine().toString()
+
+ HttpEntity entity = httpResponse.getEntity();
+
+ if (entity != null) {
+ InputStream instream = entity.getContent();
+ BufferedReader reader = new BufferedReader( new InputStreamReader(instream));
+ StringBuilder sb = new StringBuilder();
+ String line = null;
+ try {
+ while ((line = reader.readLine()) != null) {
+ sb.append(line + &quot;\n&quot;);
+ }
+ } catch (IOException e) {
+ // Deal with it
+ } finally {
+ try {
+ instream.close();
+ } catch (IOException e) {
+ // Deal with it
+ }
+ }
+
+ // Handle the result (for instance, get a JSON object
+ // using the &quot;Retrieve JSON from a server response&quot; snippet)
+ handleResult(result);
+ }
+} catch (ClientProtocolException e) {
+ // Deal with it
+} catch (IOException e) {
+ // Deal with it
+}
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.web.email.description"
+ id="com.motorola.studio.android.codesnippets.web5"
+ label="%snippet.web.email">
+ <content>
+ // To use these Internet methods, AndroidManifest.xml must have the following permission:
+// &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
+Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
+emailIntent.setType(&quot;plain/text&quot;);
+emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{&quot;to@email.com&quot;});
+emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, &quot;Hello!&quot;);
+emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, &quot;Hello!&quot;);
+
+startActivity(Intent.createChooser(emailIntent, &quot;Send mail...&quot;));
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.web.urlconnection.description"
+ id="com.motorola.studio.android.codesnippets.web6"
+ label="%snippet.web.urlconnection">
+ <content>
+ // To use these Internet methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
+// The data that is retrieved
+String result = null;
+
+try {
+ // This assumes that you have a URL from which the response will come
+ URL url = new URL(&quot;www.webaddress.org&quot;);
+
+ // Open a connection to the URL and obtain a buffered input stream
+ URLConnection connection = url.openConnection();
+ InputStream inputStream = connection.getInputStream();
+ BufferedInputStream bufferedInput = new BufferedInputStream(inputStream);
+
+ // Read the response into a byte array
+ ByteArrayBuffer byteArray = new ByteArrayBuffer(50);
+ int current = 0;
+ while((current = bufferedInput.read()) != -1){
+ byteArray.append((byte)current);
+ }
+
+ // Construct a String object from the byte array containing the response
+ result = new String(byteArray.toByteArray());
+} catch (Exception e) {
+
+}
+
+// Handle the result
+handleResult(result);
+ </content>
+ </item>
+ <item
+ class="com.motorola.studio.android.codesnippets.AndroidPermissionInsertSnippet"
+ description="%snippet.web.soap.description"
+ id="com.motorola.studio.android.codesnippets.web7"
+ label="%snippet.web.soap">
+ <content>
+ // To use these Internet methods, AndroidManifest.xml must have the following permission:
+//&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
+/* This example is intended to be used with the kSOAP
+ * project (http://ksoap2.sourceforge.net/), which
+ * provides some objects to deal with SOAP within
+ * mobile development.
+ *
+ * You must download the kSOAP objects and
+ * have something like this in your import list:
+ * import org.ksoap2.SoapEnvelope; // (and other necessary classes)
+ */
+String SOAP_ACTION = &quot;yourMethod&quot;;
+String METHOD_NAME = &quot;yourMethod&quot;;
+String NAMESPACE = &quot;http://namespace.com/&quot;;
+String URL = &quot;http://server.org&quot;;
+
+SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
+request.addProperty(&quot;property1&quot;, &quot;property&quot;);
+
+SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
+envelope.setOutputSoapObject(request);
+HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
+androidHttpTransport.call(SOAP_ACTION, envelope);
+
+Object results = envelope.getResponse();
+
+// Handle the results
+handleResults(results);
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.sensors.description"
+ id="android_sensor"
+ label="%category.sensors">
+ <item
+ description="%snnipet.sensor.detect.description"
+ id="com.motorola.studio.android.codesnippets.sensor1"
+ label="%snnipet.sensor.detect">
+ <content>
+ // This code requires API level 3 (Android 1.5) or higher
+SensorManager manager = (SensorManager) getSystemService(SENSOR_SERVICE);
+boolean isAccelerometerSupported = true;
+if(manager.getSensorList(Sensor.TYPE_ACCELEROMETER).isEmpty()){
+ isAccelerometerSupported = false;
+}
+ </content>
+ </item>
+ <item
+ description="%snnipet.sensor.getorientation.description"
+ id="com.motorola.studio.android.codesnippets.sensor2"
+ label="%snnipet.sensor.getorientation">
+ <content>
+ // This code requires API level 3 (Android 1.5) or higher
+SensorManager manager;
+manager = (SensorManager) getSystemService(SENSOR_SERVICE);
+manager.registerListener(new SensorEventListener(){
+ public void onAccuracyChanged(Sensor sensor, int accuracy){
+ }
+
+ public void onSensorChanged(SensorEvent event){
+ if(event.sensor.getType() == Sensor.TYPE_ORIENTATION){
+ // The contents of the values[] array depends upon the sensor type.
+ // See the description of the values[] array in the SensorEvent object documentation.
+ float azimuth = Math.round(event.values[0]);
+ float pitch = Math.round(event.values[1]);
+ float roll = Math.round(event.values[2]);
+
+ // Do something with the device orientation values
+ }
+ }},
+ manager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
+ SensorManager.SENSOR_DELAY_NORMAL);
+ </content>
+ </item>
+ </category>
+
+ <category
+ description="%category.ui.description"
+ id="ui"
+ label="%category.ui">
+ <item
+ description="%snippet.ui.gestures.description"
+ id="com.motorola.studio.android.codesnippets.ui1"
+ label="%snippet.ui.gestures.string">
+ <content>
+private static final float DISTANCE_DIP = 16.0f;
+private static final float PATH_DIP = 40.0f;
+// convert dip measurements to pixels
+final float scale = getResources().getDisplayMetrics().density;
+int scaledDistance = (int) (DISTANCE_DIP * scale + 0.5f);
+int scaledPath = (int) (PATH_DIP * scale + 0.5f);
+// For more information about touch gestures and screens support, see:
+// http://developer.android.com/resources/articles/gestures.html
+// http://developer.android.com/reference/android/gesture/package-summary.html
+// http://developer.android.com/guide/practices/screens_support.html
+ </content>
+ </item>
+ <item
+ description="%snippet.ui.background.description"
+ id="com.motorola.studio.android.codesnippets.ui3"
+ label="%snippet.ui.background.string">
+ <content>
+ originalImage = Bitmap.createScaledBitmap(
+originalImage, // bitmap to resize
+view.getWidth(), // new width
+view.getHeight(), // new height
+true); // bilinear filtering
+
+ </content>
+ </item>
+ <item
+ description="%snippet.ui.sizes.description"
+ id="com.motorola.studio.android.codesnippets.ui2"
+ label="%snippet.ui.sizes.string">
+ <content>
+ public void onSizeChanged(int w, int h, int oldW,
+int oldH) {
+// Calculate relative sizes at runtime
+// mButton and mButtonBackGround are of type Drawable
+int selfW = mButton.getIntrinsicWidth();
+int selfH = mButton.getIntrinsicHeight();
+int marginX = (w - selfW) / 2;
+int marginY = (h - selfH) / 2;
+mButtonBackground.setBounds(marginX, marginY,
+marginX + selfW, marginY + selfH);
+mButton.setBounds(marginX, marginY,
+marginX + selfW, marginY + selfH);
+// Implement the measureText method to resize text data, if applicable
+measureText();
+}
+ </content>
+ </item>
+ <item
+ description="%snippet.ui.widget.description"
+ id="com.motorola.studio.android.codesnippets.ui4"
+ label="%snippet.ui.widget.string">
+ <content>
+ // Add import android.view.View.OnClickListener; statement
+// Add import android.widget.Button; statement
+// Add import android.view.View; statement
+
+Button b1 = (Button) findViewById(R.id.your_button_id); // Use this method carefully, it consumes lots of system resources
+b1.setOnClickListener(new OnClickListener() {
+ public void onClick(View v) {
+ // Handle the button click here as you wish
+ }
+});
+ </content>
+ </item>
+ <item
+ description="%snippet.ui.moveout.description"
+ id="com.motorola.studio.android.codesnippets.ui5"
+ label="%snippet.ui.moveout.string">
+ <content>
+// You must provide types for the three generic parameters before the code will compile.
+// For more details, see http://developer.android.com/reference/android/os/AsyncTask.html
+ private class MoveOutOfUIthread extends AsyncTask&lt;
+ Params, // one or more values of this type are passed to doInBackground()
+ Progress, // the type of the progress units published during background crunching.
+ Result // the type of the result returned by doInBackground()
+ &gt;
+ {
+
+ protected Integer doInBackground(Params... p1, p2, p3) {
+ // your background task here
+ Result result = new Result();
+ return result;
+ }
+
+ protected void onPostExecute(Result r) {
+ // this gets the object returned by doInBackground, and executes on the UI thread
+ }
+ }
+ new MoveOutOfUIthread().execute(p1, p2, p3);
+ </content>
+ </item>
+ <item
+ description="%snippet.ui.backgroundtaskwithnotification.description"
+ id="com.motorola.studio.android.codesnippets.ui6"
+ label="%snippet.ui.backgroundtaskwithnotification.string">
+ <content>
+ // This code is supposed to be used as an inner class and will start a
+ // background task while it notifies the user via the status bar. The outer class
+ // must implement Context (sub)classes like Activity and Service. Use
+ // new BackgroundTaskWithStatusBarNotification(id, title, text,
+ // context).execute() to start the background task.
+ private class BackgroundTaskWithStatusBarNotification extends
+ AsyncTask&lt;Void, Integer, Void&gt; {
+
+ // A unique identifier for the notification.
+ private int mId;
+
+ // The text that will be displayed when the status bar is expanded.
+ private String mShortDesc;
+
+ // The text that flows by in the status bar when the notification first
+ // activates.
+ private String mContent;
+
+ // The application context where the task was launched.
+ private Context mContext;
+
+ // The notification itself.
+ private Notification mNotification;
+
+ // The notification manager retrieved from the system.
+ private NotificationManager mNotificationManager;
+
+ // An intent that will be launched when user clicks the
+ // notification
+ PendingIntent mPendingIntent;
+
+ public BackgroundTaskWithStatusBarNotification(int id,
+ String shortDesc, String content, Context context) {
+ mId = id;
+ mShortDesc = shortDesc;
+ mContent = content;
+ mContext = context;
+ }
+
+ protected void onPreExecute() {
+ mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
+
+ mNotification = new Notification(
+ android.R.drawable.stat_sys_download, mContent,
+ System.currentTimeMillis());
+
+ // TODO: enter the initial text for your task here, such as:
+ // &quot;0% complete&quot;.
+ String progressText = &quot;your_text_here&quot;;
+
+ // this intent will be launched when user clicks the notification in the
+ // status bar and will start activity YourActivity
+ Intent intent = new Intent(mContext, YourActivity.class);
+ mPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
+
+ // updates the notification
+ mNotification.setLatestEventInfo(mContext, mShortDesc,
+ progressText, mPendingIntent);
+ mNotification.flags = Notification.FLAG_ONGOING_EVENT;
+ mNotificationManager.notify(mId, mNotification);
+ }
+
+ @Override
+ protected Void doInBackground(Void... argList) {
+
+ // TODO: add the content of your background task here. Call
+ // AsyncTask.publishProgress() method to update the
+ // tasks progress (method onProgressUpdate() will handle this
+ // progress update).
+
+ return null;
+ }
+
+ protected void onProgressUpdate(Integer... progress) {
+
+ // TODO: supply the text that must be displayed while the task is in
+ // progress. For instance, &quot;progress[0] + &quot;% complete&quot;.
+ String contentText = &quot;your_text_here&quot;;
+
+ // updates the notification
+ mNotification.setLatestEventInfo(mContext, mShortDesc, contentText,
+ mPendingIntent);
+ mNotificationManager.notify(mId, mNotification);
+ }
+
+ protected void onPostExecute(Void result) {
+ // TODO: supply the final text that must be displayed when the task
+ // is done. For instance, &quot;Done&quot;.
+ String contentText = &quot;your_text_here&quot;;
+
+ // updates the notification
+ mNotification.icon = android.R.drawable.stat_sys_download_done;
+ mNotification.setLatestEventInfo(mContext, mShortDesc, contentText,
+ mPendingIntent);
+ mNotificationManager.notify(mId, mNotification);
+ }
+}
+ </content>
+ </item>
+ <item
+ description="%snippet.ui.hide.statusbar.description"
+ id="com.motorola.studio.android.codesnippets.item6"
+ label="%snippet.ui.hide.statusbar.label">
+ <content>
+ //Hides status bar (if it was showing)
+View v = findViewById(R.id.view_id); //for example, the ID representing the root of a linear layout
+v.setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
+ </content>
+ </item>
+ <item
+ description="%snippet.ui.visible.statusbar.description"
+ id="com.motorola.studio.android.codesnippets.item7"
+ label="%snippet.ui.visible.statusbar.label">
+ <content>
+ //Shows status bar (if it was hidden)
+View v = findViewById(R.id.view_id); //for example, the ID representing the root of a linear layout
+v.setSystemUiVisibility(View.STATUS_BAR_VISIBLE);
+ </content>
+ </item>
+ </category>
+ <category
+ description="%intents.ui.description"
+ id="android_intents"
+ label="%intents.ui">
+ <item
+ description="%intents.start.activity.explicitly.description"
+ id="com.motorola.studio.android.codesnippets.intents1"
+ label="%intents.start.activity.explicitly.label">
+ <content>
+ //Calls another activity, by name, without passing data
+
+Intent iExp = new Intent(this, ActivityToCall.class); //TODO Replace 'ActivityToCall' with the class name of the activity being called
+
+startActivity(iExp);
+ </content>
+ </item>
+ <item
+ description="%intents.start.activity.implicitly.description"
+ id="com.motorola.studio.android.codesnippets.item2"
+ label="%intents.start.activity.implicitly.label">
+ <content>
+ //Calls another activity, by action and category, without passing data
+//refer to AndroidManifest.xml&lt;intent-filter&gt; when determining the action and category of the activity to call
+Intent iImp = new Intent(&quot;actionName&quot;); //TODO Replace 'actionName' as appropriate for your action (for example, Intent.ACTION_EDIT)
+iImp.addCategory(&quot;categoryName&quot;); //TODO Replace 'categoryName' as appropriate for your category (for example, Intent.CATEGORY_DEFAULT)
+startActivity(iImp);
+ </content>
+ </item>
+ <item
+ description="%intents.start.activity.for.result.description"
+ id="com.motorola.studio.android.codesnippets.item3"
+ label="%intents.start.activity.for.result.label">
+ <content>
+ //Calls another activity, identified by action and category, passing data URL and a MIME type
+//The class calling the snippet code must implement the following method:
+//protected void onActivityResult (int requestCode, int resultCode, Intent data) {}
+Intent iImp = new Intent();
+iImp.setAction(&quot;actionName&quot;); //TODO Replace 'actionName' as appropriate for your action (for example, Intent.ACTION_EDIT)
+iImp.addCategory(&quot;categoryName&quot;); //TODO Replace 'categoryName' as appropriate for your category (for example, Intent.CATEGORY_DEFAULT)
+//optional - set data and MIME type for the intent
+iImp.setDataAndType(Uri.parse(&quot;http://com.example.project/folder&quot;), &quot;text/plain&quot;); //TODO Change URL and MIME type as appropriate
+startActivityForResult(iImp, 0); //TODO The second parameter (here, zero) is the request code to be used in onActivityResult(); change this parameter to an appropriate value for your activity
+ </content>
+ </item>
+ <item
+ description="%intents.send.broadcast.description"
+ id="com.motorola.studio.android.codesnippets.item4"
+ label="%intents.send.broadcast.label">
+ <content>
+ //Broadcasts an event notification
+//before sending broadcast, make sure that your application has permission to broadcast the action. Otherwise, a SecurityException: Permission denial will be thrown
+Intent iBroad = new Intent();
+iBroad.setAction(&quot;actionName&quot;); //TODO Replace 'actionName' as appropriate for your action (for example, Intent.ACTION_EDIT)
+iBroad.addCategory(&quot;categoryName&quot;); //TODO Replace 'categoryName' as appropriate for your category (for example, Intent.CATEGORY_DEFAULT)
+this.sendBroadcast(iBroad);
+
+ </content>
+ </item>
+ <item
+ description="%intents.start.service.description"
+ id="com.motorola.studio.android.codesnippets.item5"
+ label="%intents.start.service.label">
+ <content>
+ //Starts a service (task to be accomplished in the background, without UI)
+//The class employing the snippet code must implement ServiceConnection
+Intent iServ = new Intent();
+iServ.setClass(getBaseContext(), ServiceName.class); //TODO Replace 'ServiceName' with the class name for your Service
+bindService(iServ, this, BIND_AUTO_CREATE);
+startService(iServ);
+ </content>
+ </item>
+ </category>
+ <category
+ description="%fragments.ui.description"
+ id="android_fragments"
+ label="%fragments.ui">
+ <item
+ description="%fragments.replace.transaction.description"
+ id="com.motorola.studio.android.codesnippets.item10"
+ label="%fragments.replace.transaction.label">
+ <content>
+ //Replaces a container's fragment(s)
+FragmentTransaction ft = getFragmentManager().beginTransaction();
+MyFragment newFrag =new MyFragment(); //TODO Change to your fragment constructor
+ft.addToBackStack(null); //Allows this transaction to be undone when the back button is pressed
+ft.replace(R.id.containerId, newFrag, &quot;newFragTag&quot;); //TODO Replace 'R.id.containerId' (with the ID of a View) and 'newFragTag'
+ft.commit();
+ </content>
+ </item>
+ <item
+ description="%fragments.add.transaction.description"
+ id="com.motorola.studio.android.codesnippets.item11"
+ label="%fragments.add.transaction.label">
+ <content>
+ //Adds a fragment to a specified layout
+FragmentTransaction ft = getFragmentManager().beginTransaction();
+MyFragment newFrag =new MyFragment(); //TODO Change to your fragment constructor
+ft.addToBackStack(null); //Allows this transaction to be undone when the back button is pressed
+ft.add(R.id.layoutId, newFrag); //TODO Replace 'R.id.layoutId' (with the ID of a layout)
+ft.commit();
+ </content>
+ </item>
+ </category>
+ <category
+ description="%category.facerecog.description"
+ id="face_recognition"
+ label="%category.facerecog">
+ <item
+ description="%snippet.facerecog.description"
+ id="com.motorola.studio.android.codesnippets.facerecog1"
+ label="%snippet.facerecog.string">
+ <content>
+ //Make sure the bitmap file was generated using the RGB_565
+ //configuration, or else it cannot be used for detection
+ //For more information, see http://developer.android.com/reference/android/media/FaceDetector.html#findFaces(android.graphics.Bitmap, android.media.FaceDetector.Face[])
+ BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
+ bmpOptions.inPreferredConfig = Bitmap.Config.RGB_565;
+
+ //Decode the file from Resources and get some of its parameters.
+ //You can also use any of the decode methods from BitmapFactory
+ Bitmap bmp = BitmapFactory.decodeResource(getResources(), /*TODO: Insert your drawable resource ID here*/, bmpOptions);
+ int MaxNumberOfDetectedFaces = 2;
+
+ //Instantiate a vector with the number of faces you want
+ Face[] faces = new FaceDetector.Face[MaxNumberOfDetectedFaces];
+ //Instantiate a FaceDetector object for the bitmap
+ FaceDetector fd = new FaceDetector(bmp.getWidth(), bmp.getHeight(), MaxNumberOfDetectedFaces);
+
+ //Use the findfaces() method to actually process the bitmap
+ if (fd.findFaces(bmp, faces) &gt; 0) {
+ //Do something here. You can see how accurate the detection was
+ //by calling confidence() on any of the found faces.
+ //In this example, it looks only for the first face (faces[0]).
+ Toast.makeText(this, &quot;Confidence: &quot; + faces[0].confidence(), Toast.LENGTH_SHORT).show();
+ }
+ else {
+ //No faces were found in the bitmap
+ Toast.makeText(this, &quot;No face found!&quot;, Toast.LENGTH_SHORT).show();
+ }
+ </content>
+ </item>
+ </category>
+ </extension>
+ <extension
+ point="org.eclipse.ui.perspectiveExtensions">
+ <perspectiveExtension
+ targetID="org.eclipse.jdt.ui.JavaPerspective">
+ <viewShortcut
+ id="org.eclipse.wst.common.snippets.internal.ui.SnippetsView">
+ </viewShortcut>
+ <view
+ id="org.eclipse.wst.common.snippets.internal.ui.SnippetsView"
+ minimized="false"
+ relationship="stack"
+ relative="org.eclipse.ui.views.ContentOutline"
+ visible="true">
+ </view>
+ </perspectiveExtension>
+ </extension>
+ </plugin>
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidPermissionInsertSnippet.java b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidPermissionInsertSnippet.java
new file mode 100644
index 0000000..5743e16
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidPermissionInsertSnippet.java
@@ -0,0 +1,274 @@
+/*
+* Copyright (C) 2012 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.motorola.studio.android.codesnippets;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.eclipse.core.resources.IFile;
+import org.eclipse.core.resources.IProject;
+import org.eclipse.jface.text.BadLocationException;
+import org.eclipse.jface.text.IDocument;
+import org.eclipse.jface.text.ITextSelection;
+import org.eclipse.osgi.util.NLS;
+import org.eclipse.swt.dnd.DragSourceEvent;
+import org.eclipse.ui.IEditorInput;
+import org.eclipse.ui.IEditorPart;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.ui.part.FileEditorInput;
+import org.eclipse.ui.texteditor.ITextEditor;
+import org.eclipse.wst.common.snippets.core.ISnippetItem;
+import org.eclipse.wst.common.snippets.core.ISnippetsEntry;
+import org.eclipse.wst.common.snippets.internal.ui.SnippetsView;
+import org.eclipse.wst.common.snippets.ui.DefaultSnippetInsertion;
+
+import com.motorola.studio.android.codesnippets.i18n.AndroidSnippetsNLS;
+import com.motorola.studio.android.common.log.StudioLogger;
+import com.motorola.studio.android.common.log.UsageDataConstants;
+import com.motorola.studio.android.common.utilities.EclipseUtils;
+import com.motorola.studio.android.manifest.AndroidProjectManifestFile;
+import com.motorola.studio.android.model.manifest.AndroidManifestFile;
+import com.motorola.studio.android.model.manifest.dom.ManifestNode;
+import com.motorola.studio.android.model.manifest.dom.UsesPermissionNode;
+
+public class AndroidPermissionInsertSnippet extends DefaultSnippetInsertion
+{
+
+ @Override
+ protected void doInsert(IEditorPart editorPart, ITextEditor textEditor, IDocument document,
+ ITextSelection textSelection) throws BadLocationException
+ {
+ String replacement = getInsertString(editorPart.getEditorSite().getShell());
+ boolean permissionsAdded = addPermissionToManifest(editorPart, replacement);
+
+ // get the Snippets View
+ SnippetsView snippetsView =
+ (SnippetsView) EclipseUtils.getActiveView(AndroidSnippetsStartup.SNIPPETS_VIEW_ID);
+ // get the selected snippet
+ ISnippetsEntry snippetEntry = snippetsView.getSelectedEntry();
+ if (snippetEntry != null)
+ {
+ String snippetLabel = snippetEntry.getLabel();
+
+ if (CodeSnippetsPlugin.getDefault() != null)
+ {
+ StudioLogger
+ .collectUsageData(
+ UsageDataConstants.WHAT_CODESNIPPET,
+ UsageDataConstants.KIND_CODESNIPPET,
+ "Codesnippet '" + snippetLabel + "' used. Permission added: " + permissionsAdded, //$NON-NLS-1$
+ AndroidSnippetsStartup.SNIPPETS_VIEW_ID, CodeSnippetsPlugin
+ .getDefault().getBundle().getVersion().toString());
+ }
+ }
+
+ super.doInsert(editorPart, textEditor, document, textSelection);
+ }
+
+ /**
+ * If the snippetText contains comment to insert uses-permission, then
+ * it adds uses-permission to androidmanifest file
+ * @param editorPart editor
+ * @param snippetText text to drop
+ */
+ private boolean addPermissionToManifest(IEditorPart editorPart, String snippetText)
+ {
+ boolean needToAddPermission =
+ snippetText.contains("AndroidManifest.xml must have the following permission:"); //$NON-NLS-1$
+ boolean shouldAddToManifest = false;
+ if (needToAddPermission)
+ {
+
+ List<String> neededPermissions = getNeededPermissions(snippetText);
+ List<String> permissionsToBeAdded = new ArrayList<String>(neededPermissions.size());
+
+ IEditorInput input = editorPart.getEditorInput();
+ FileEditorInput fileEditorInput = null;
+ ManifestNode manifestNode = null;
+ if (input instanceof FileEditorInput)
+ {
+ fileEditorInput = (FileEditorInput) input;
+ IProject project;
+ IFile file = fileEditorInput.getFile();
+ project = file.getProject();
+ try
+ {
+ AndroidManifestFile androidManifestFile =
+ AndroidProjectManifestFile.getFromProject(project);
+ manifestNode = androidManifestFile.getManifestNode();
+ }
+ catch (Exception e)
+ {
+ // Do nothing, just ask for the permissions.
+ }
+ }
+
+ if (manifestNode != null)
+ {
+ for (String neededPermission : neededPermissions)
+ {
+ if (!permAlreadyExists(manifestNode, neededPermission))
+ {
+ permissionsToBeAdded.add(neededPermission);
+ }
+ }
+ }
+
+ if (!permissionsToBeAdded.isEmpty())
+ {
+
+ StringBuilder permMsgBuilder = new StringBuilder();
+ for (String neededPermission : permissionsToBeAdded)
+ {
+ permMsgBuilder
+ .append(AndroidSnippetsNLS.AndroidPermissionInsertSnippet_PermissionPrefix);
+ permMsgBuilder.append(neededPermission);
+ permMsgBuilder
+ .append(AndroidSnippetsNLS.AndroidPermissionInsertSnippet_PermissionSuffix);
+ }
+
+ //Ask user permission
+ shouldAddToManifest =
+ EclipseUtils
+ .showQuestionDialog(
+ AndroidSnippetsNLS.AndroidPermissionInsertSnippet_Msg_AddToManifest_Title,
+ NLS.bind(
+ AndroidSnippetsNLS.AndroidPermissionInsertSnippet_Msg_AddToManifest_Msg,
+ permMsgBuilder.toString()));
+
+ if (shouldAddToManifest)
+ {
+ AndroidManifestFile androidManifestFile = null;
+ manifestNode = null;
+ if (fileEditorInput != null)
+ {
+ addPermissionToManifest(permissionsToBeAdded, fileEditorInput,
+ androidManifestFile, manifestNode);
+ }
+
+ }
+ }
+ }
+ return shouldAddToManifest;
+ }
+
+ private List<String> getNeededPermissions(String snippetText)
+ {
+ //search each <uses-permission tag
+ StringTokenizer lineToken = new StringTokenizer(snippetText, "\n\r"); //$NON-NLS-1$
+ List<String> neededPermissions = new ArrayList<String>(lineToken.countTokens());
+ while (lineToken.hasMoreTokens())
+ {
+ String line = lineToken.nextToken();
+ if (line.contains("<uses-permission")) //$NON-NLS-1$
+ {
+ String permNameToAdd = null;
+ String androidNameStr = "android:name=\""; //$NON-NLS-1$
+ int beginIndex = line.indexOf(androidNameStr);
+ int endIndex = line.indexOf("\"/>"); //$NON-NLS-1$
+ if ((beginIndex > 0) && (endIndex > 0))
+ {
+ permNameToAdd = line.substring(beginIndex + androidNameStr.length(), endIndex);
+ neededPermissions.add(permNameToAdd);
+ }
+ else
+ {
+ //log malformed permission statement
+ StudioLogger
+ .error(AndroidPermissionInsertSnippet.class,
+ "Permission code snippet was not in the right format to enable insert of uses-permission on androidmanifest.xml" //$NON-NLS-1$
+ + snippetText);
+ }
+ }
+ }
+
+ return neededPermissions;
+ }
+
+ /**
+ * If the snippetText contains comment to insert uses-permission, then
+ * it asks user to add uses-permission to androidmanifest file
+ * @param snippetText text to drop
+ * @param input editor
+ * @param androidManifestFile file to update
+ * @param manifestNode node to update
+ */
+ private void addPermissionToManifest(List<String> neededPermissions, IEditorInput input,
+ AndroidManifestFile androidManifestFile, ManifestNode manifestNode)
+ {
+ IProject project;
+ IFile file = ((FileEditorInput) input).getFile();
+ project = file.getProject();
+ try
+ {
+ androidManifestFile = AndroidProjectManifestFile.getFromProject(project);
+ manifestNode = androidManifestFile.getManifestNode();
+
+ for (String neededPermission : neededPermissions)
+ {
+ if (!permAlreadyExists(manifestNode, neededPermission))
+ {
+ //append permission node
+ UsesPermissionNode usesPermissionNode =
+ new UsesPermissionNode(neededPermission);
+ manifestNode.addChild(usesPermissionNode);
+ }
+ }
+
+ AndroidProjectManifestFile.saveToProject(project, androidManifestFile, true);
+ }
+ catch (Exception e)
+ {
+ StudioLogger.error(AndroidPermissionInsertSnippet.class,
+ "Error adding snippet permissions to androidmanifest.xml.", e); //$NON-NLS-1$
+ }
+ }
+
+ private boolean permAlreadyExists(ManifestNode manifestNode, String neededPermission)
+ {
+ //Check if permissions does not exist yet
+ boolean permAlreadyExists = false;
+ List<UsesPermissionNode> permissionsNode = manifestNode.getUsesPermissionNodes();
+
+ if (permissionsNode != null)
+ {
+ for (UsesPermissionNode existentPermissionNode : permissionsNode)
+ {
+ String permName =
+ existentPermissionNode.getNodeProperties()
+ .get(UsesPermissionNode.PROP_NAME);
+ if ((permName != null) && permName.equals(neededPermission))
+ {
+ permAlreadyExists = true;
+ break;
+ }
+ }
+ }
+ return permAlreadyExists;
+ }
+
+ @Override
+ public void dragSetData(DragSourceEvent event, ISnippetItem item)
+ {
+ IEditorPart part =
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
+ .getActiveEditor();
+ addPermissionToManifest(part, item.getContentString());
+ super.dragSetData(event, item);
+ }
+}
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsStartup.java b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsStartup.java
new file mode 100644
index 0000000..e555654
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsStartup.java
@@ -0,0 +1,338 @@
+/*
+* Copyright (C) 2012 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.motorola.studio.android.codesnippets;
+
+import org.eclipse.gef.ui.palette.PaletteViewer;
+import org.eclipse.jface.action.ToolBarManager;
+import org.eclipse.swt.events.DragDetectEvent;
+import org.eclipse.swt.events.DragDetectListener;
+import org.eclipse.swt.events.MouseEvent;
+import org.eclipse.swt.events.MouseListener;
+import org.eclipse.swt.graphics.Point;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.ui.IPerspectiveDescriptor;
+import org.eclipse.ui.IPerspectiveListener;
+import org.eclipse.ui.IStartup;
+import org.eclipse.ui.IViewReference;
+import org.eclipse.ui.IWorkbenchPage;
+import org.eclipse.ui.IWorkbenchPartReference;
+import org.eclipse.ui.IWorkbenchWindow;
+import org.eclipse.ui.PerspectiveAdapter;
+import org.eclipse.ui.PlatformUI;
+import org.eclipse.wst.common.snippets.core.ISnippetItem;
+import org.eclipse.wst.common.snippets.core.ISnippetsEntry;
+import org.eclipse.wst.common.snippets.internal.ui.SnippetsView;
+
+import com.motorola.studio.android.common.utilities.EclipseUtils;
+
+/**
+ * This class register listeners in the Snippets View to monitor changes on its
+ * selection. This way, MOTODEV Studio for Android displays the snippet preview
+ * when appropriate
+ *
+ */
+@SuppressWarnings("restriction")
+public class AndroidSnippetsStartup implements IStartup
+{
+
+ public final static String SNIPPETS_VIEW_ID =
+ "org.eclipse.wst.common.snippets.internal.ui.SnippetsView";
+
+ private static SnippetsViewContributionItem searchContributionItem;
+
+ private static TooltipDisplayConfigContriutionItem tooltipDisplayConfigcontributionItem;
+
+ /*
+ * The tool tip being displayed
+ */
+ private AndroidSnippetsTooltip tooltip = null;
+
+ private static void addSearchBar(final SnippetsView view)
+ {
+ if (searchContributionItem == null)
+ {
+ ToolBarManager tbManager =
+ (ToolBarManager) view.getViewSite().getActionBars().getToolBarManager();
+
+ // the item which searches for words within snippets titles, descriptions and codes
+ searchContributionItem = new SnippetsViewContributionItem(view);
+
+ tbManager.add(searchContributionItem);
+ tbManager.update(true);
+ view.getViewSite().getActionBars().updateActionBars();
+ }
+
+ if (tooltipDisplayConfigcontributionItem == null)
+ {
+ ToolBarManager tbManager =
+ (ToolBarManager) view.getViewSite().getActionBars().getToolBarManager();
+
+ // the item which configures the display of the tool tip
+ tooltipDisplayConfigcontributionItem = new TooltipDisplayConfigContriutionItem();
+
+ tbManager.add(tooltipDisplayConfigcontributionItem);
+ tbManager.update(true);
+ view.getViewSite().getActionBars().updateActionBars();
+ }
+ }
+
+ /**
+ * Add a mouse listener to Snippets View
+ * Open the snippet preview tooltip when the user clicks on a
+ * snippet item.
+ * Close it when he clicks again in the same item
+ *
+ * @see org.eclipse.ui.IStartup#earlyStartup()
+ */
+ public void earlyStartup()
+ {
+
+ /*
+ * This is the listener responsible for monitoring mouse clicks
+ * on snippet items. When the user clicks on an item, it triggers
+ * the action to display the snippet preview
+ */
+ final MouseListener snippetsMouseListener = new MouseListener()
+ {
+ /**
+ * Do nothing
+ *
+ * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
+ */
+ public void mouseUp(MouseEvent e)
+ {
+ // nothing
+ }
+
+ /**
+ * Open/Toogle tooltip
+ *
+ * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
+ */
+ public void mouseDown(MouseEvent e)
+ {
+
+ // get the Snippets View
+ SnippetsView snippetsView =
+ (SnippetsView) EclipseUtils.getActiveView(SNIPPETS_VIEW_ID);
+
+ // get the selected snippet
+ ISnippetsEntry snippetEntry = snippetsView.getSelectedEntry();
+
+ // check the tooltip is already being displayed
+ // open it if it's not and its config allows so, close it otherwise
+ if ((snippetEntry instanceof ISnippetItem)
+ && ((tooltip == null) || (!tooltip.getItem().equals(snippetEntry)))
+ && tooltipDisplayConfigcontributionItem.isTooltipDisplayed())
+ {
+ Control snippetsControl = snippetsView.getViewer().getControl();
+ tooltip =
+ new AndroidSnippetsTooltip((ISnippetItem) snippetEntry, snippetsControl);
+ tooltip.setPopupDelay(250);
+ tooltip.show(new Point(snippetsControl.getBounds().width, 0));
+
+ }
+ else
+ {
+ if (tooltip != null)
+ {
+ tooltip.hide();
+ }
+ tooltip = null;
+ }
+ }
+
+ /**
+ * Hide tooltip
+ *
+ * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
+ */
+ public void mouseDoubleClick(MouseEvent e)
+ {
+ if (tooltip != null)
+ {
+ tooltip.hide();
+ }
+ tooltip = null;
+ }
+ };
+
+ /**
+ * this listener is called when the mouse is dragged. It simply
+ * hides the tool tip when this action occurs.
+ */
+ final DragDetectListener snippetsMouseDragListener = new DragDetectListener()
+ {
+
+ /**
+ * Hide the tool tip.
+ */
+ public void dragDetected(DragDetectEvent e)
+ {
+ // simply hide the tool tip
+ if (tooltip != null)
+ {
+ tooltip.hide();
+ }
+ }
+ };
+
+ /*
+ * This is the listener that is attached to the workspace and monitor
+ * perspectives activation, as well as changes in the views being displayed
+ * (for example: view opened/closed). It intends to attach the snippetsMouseListener
+ * listener declared above in the Snippets View being used by Eclipse
+ */
+ final IPerspectiveListener perspectiveListener = new PerspectiveAdapter()
+ {
+ // Set if it has already been executed
+ // If so, it doesn't need to be executed again
+ boolean executed = false;
+
+ /**
+ * This action is called when the user goes to another perspective (it's not called for the first perspective
+ * displayed when he opens Eclipse)
+ *
+ * @see org.eclipse.ui.PerspectiveAdapter#perspectiveActivated(org.eclipse.ui.IWorkbenchPage, org.eclipse.ui.IPerspectiveDescriptor)
+ */
+ @Override
+ public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective)
+ {
+ IViewReference[] viewReferences = page.getViewReferences();
+ for (IViewReference viewReference : viewReferences)
+ {
+ if (SNIPPETS_VIEW_ID.equals(viewReference.getId()))
+ {
+ SnippetsView snippetsView = (SnippetsView) viewReference.getView(true);
+ if (snippetsView != null)
+ {
+ addSearchBar(snippetsView);
+ PaletteViewer palleteViewer = snippetsView.getViewer();
+ if (palleteViewer != null)
+ {
+ Control control = palleteViewer.getControl();
+ if (control != null)
+ {
+ control.removeMouseListener(snippetsMouseListener); // remove mouse listener just to ensure we never have two listeners registered
+ control.removeDragDetectListener(snippetsMouseDragListener); // remove mouse draggable listener just to ensure we never have two listeners registered
+ control.addMouseListener(snippetsMouseListener);
+ control.addDragDetectListener(snippetsMouseDragListener);
+ executed = true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * This is called when something in the perspective have changed.
+ * For example: when a view is opened or closed
+ *
+ * @see org.eclipse.ui.PerspectiveAdapter#perspectiveChanged(org.eclipse.ui.IWorkbenchPage, org.eclipse.ui.IPerspectiveDescriptor, org.eclipse.ui.IWorkbenchPartReference, java.lang.String)
+ */
+ @Override
+ public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective,
+ IWorkbenchPartReference partRef, String changeId)
+ {
+ // check if it's the Snippet View
+ if (SNIPPETS_VIEW_ID.equals(partRef.getId()))
+ {
+ // if it's the Snippet View and it's being OPENED
+ if (IWorkbenchPage.CHANGE_VIEW_SHOW.equals(changeId))
+ {
+ if (!executed)
+ {
+ SnippetsView snippetsView = (SnippetsView) partRef.getPart(false);
+ addSearchBar(snippetsView);
+ snippetsView.getViewer().getControl()
+ .removeMouseListener(snippetsMouseListener); // remove mouse listener just to ensure we never have two listeners registered
+ snippetsView.getViewer().getControl()
+ .removeDragDetectListener(snippetsMouseDragListener); // remove mouse draggable listener just to ensure we never have two liseteners registered
+ snippetsView.getViewer().getControl()
+ .addMouseListener(snippetsMouseListener);
+ snippetsView.getViewer().getControl()
+ .addDragDetectListener(snippetsMouseDragListener);
+ // it doesn't need to add the mouse listener to the Snippets View in further opportunities
+ executed = true;
+ }
+ }
+ // if it's the Snippet View and it's being CLOSED
+ else if (IWorkbenchPage.CHANGE_VIEW_HIDE.equals(changeId))
+ {
+ // it must add the mouse listener to the Snippets View again next time the view is opened
+ if (searchContributionItem != null)
+ {
+ searchContributionItem.clean();
+ searchContributionItem.getParent().remove(searchContributionItem);
+ }
+
+ if (tooltipDisplayConfigcontributionItem != null) {
+ tooltipDisplayConfigcontributionItem.getParent().remove(tooltipDisplayConfigcontributionItem);
+ }
+
+ searchContributionItem = null;
+ tooltipDisplayConfigcontributionItem = null;
+
+ executed = false;
+ }
+ }
+
+ }
+
+ };
+
+ /*
+ * Attach the perspectiveListener declared above into the active window
+ * Also try to add the snippetsMouseListener listener to the Snippet View,
+ * if it's already being displayed
+ */
+ PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable()
+ {
+
+ public void run()
+ {
+ /*
+ * Add mouse listener to Snippet View
+ */
+ final IWorkbenchWindow activeWindow =
+ PlatformUI.getWorkbench().getActiveWorkbenchWindow();
+
+ activeWindow.addPerspectiveListener(perspectiveListener);
+
+ IViewReference viewReference =
+ activeWindow.getActivePage().findViewReference(SNIPPETS_VIEW_ID);
+
+ if (viewReference != null)
+ {
+ final SnippetsView snippetsView = (SnippetsView) viewReference.getView(true);
+ if (snippetsView != null)
+ {
+ addSearchBar(snippetsView);
+ snippetsView.getViewer().getControl()
+ .addMouseListener(snippetsMouseListener);
+ snippetsView.getViewer().getControl()
+ .addDragDetectListener(snippetsMouseDragListener);
+ }
+
+ }
+
+ }
+
+ });
+
+ }
+} \ No newline at end of file
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsTooltip.java b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsTooltip.java
new file mode 100644
index 0000000..a954ba8
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/AndroidSnippetsTooltip.java
@@ -0,0 +1,147 @@
+/*
+* Copyright (C) 2012 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.motorola.studio.android.codesnippets;
+
+import org.eclipse.jdt.internal.ui.JavaPlugin;
+import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
+import org.eclipse.jdt.ui.PreferenceConstants;
+import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
+import org.eclipse.jdt.ui.text.JavaTextTools;
+import org.eclipse.jface.preference.IPreferenceStore;
+import org.eclipse.jface.resource.JFaceResources;
+import org.eclipse.jface.text.Document;
+import org.eclipse.jface.text.source.SourceViewer;
+import org.eclipse.jface.window.ToolTip;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.custom.ScrolledComposite;
+import org.eclipse.swt.events.ControlAdapter;
+import org.eclipse.swt.events.ControlEvent;
+import org.eclipse.swt.graphics.Rectangle;
+import org.eclipse.swt.layout.FillLayout;
+import org.eclipse.swt.layout.GridData;
+import org.eclipse.swt.layout.GridLayout;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Label;
+import org.eclipse.wst.common.snippets.core.ISnippetItem;
+
+import com.motorola.studio.android.codesnippets.i18n.AndroidSnippetsNLS;
+
+/**
+ * Customized tooltip for snippets in Snippet View.
+ * It's intended to display the snippet preview
+ *
+ */
+@SuppressWarnings("restriction")
+public class AndroidSnippetsTooltip extends ToolTip
+{
+
+ /*
+ * The snippet item to be displayed in the tooltip
+ */
+ private final ISnippetItem item;
+
+ /**
+ * Constructor
+ *
+ * @param item the snippet item to be displayed
+ * @param control
+ */
+ public AndroidSnippetsTooltip(ISnippetItem item, Control control)
+ {
+ super(control, NO_RECREATE, true);
+ this.item = item;
+ }
+
+ /**
+ * Display the snippet preview by using a JAVA Source Viewer, which is
+ * used to highlight the code
+ *
+ * @see org.eclipse.jface.window.ToolTip#createToolTipContentArea(org.eclipse.swt.widgets.Event, org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ protected Composite createToolTipContentArea(Event event, Composite parent)
+ {
+ // the main composite
+ Composite mainComposite = new Composite(parent, SWT.NULL);
+ mainComposite.setLayout(new GridLayout(1, true));
+
+ /*
+ * snippet preview label
+ */
+ Label textElem = new Label(mainComposite, SWT.LEFT);
+ textElem.setText(AndroidSnippetsNLS.UI_Snippet_Preview);
+ textElem.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
+
+ /*
+ * JAVA source viewer
+ */
+ final ScrolledComposite scroll =
+ new ScrolledComposite(mainComposite, SWT.H_SCROLL | SWT.V_SCROLL);
+ scroll.setLayout(new FillLayout());
+ // create scroll layout which receives values to limit its area of display
+ GridData scrollLayoutData = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
+ Rectangle visibleArea = parent.getDisplay().getActiveShell().getMonitor().getClientArea();
+ scrollLayoutData.heightHint = visibleArea.height / 3;
+ scrollLayoutData.widthHint = visibleArea.width / 3;
+ scroll.setLayoutData(scrollLayoutData);
+
+ final Composite javaSourceViewerComposite = new Composite(scroll, SWT.NULL);
+ javaSourceViewerComposite.setLayout(new FillLayout());
+
+ int styles = SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION;
+ Document document = new Document(item.getContentString());
+ IPreferenceStore store = JavaPlugin.getDefault().getCombinedPreferenceStore();
+ JavaTextTools javaTextTools = JavaPlugin.getDefault().getJavaTextTools();
+
+ SourceViewer javaSourceViewer =
+ new JavaSourceViewer(javaSourceViewerComposite, null, null, false, styles, store);
+ javaSourceViewer.configure(new JavaSourceViewerConfiguration(javaTextTools
+ .getColorManager(), store, null, null));
+ javaSourceViewer.getControl().setFont(
+ JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT));
+ javaTextTools.setupJavaDocumentPartitioner(document);
+ javaSourceViewer.setDocument(document);
+ javaSourceViewer.setEditable(false);
+
+ // set up scroll
+ scroll.setContent(javaSourceViewerComposite);
+ scroll.setExpandHorizontal(true);
+ scroll.setExpandVertical(true);
+ scroll.addControlListener(new ControlAdapter()
+ {
+ @Override
+ public void controlResized(ControlEvent e)
+ {
+ scroll.setMinSize(javaSourceViewerComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
+ }
+ });
+
+ return mainComposite;
+ }
+
+ /**
+ * Get the snippet item being displayed
+ *
+ * @return the snippet item being displayed
+ */
+ public ISnippetItem getItem()
+ {
+ return item;
+ }
+
+}
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/CodeSnippetsPlugin.java b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/CodeSnippetsPlugin.java
new file mode 100644
index 0000000..b3a0ab8
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/CodeSnippetsPlugin.java
@@ -0,0 +1,69 @@
+/*
+* Copyright (C) 2012 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.motorola.studio.android.codesnippets;
+
+import org.eclipse.ui.plugin.AbstractUIPlugin;
+import org.osgi.framework.BundleContext;
+
+import com.motorola.studio.android.common.log.StudioLogger;
+
+public class CodeSnippetsPlugin extends AbstractUIPlugin
+{
+
+ // The plug-in ID
+ public static final String PLUGIN_ID = "com.motorola.studio.android.codesnippets"; //$NON-NLS-1$
+
+ // The shared instance
+ private static CodeSnippetsPlugin plugin;
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void start(BundleContext context) throws Exception
+ {
+ StudioLogger.debug(CodeSnippetsPlugin.class,
+ "Starting MOTODEV Android Code Snippets Plugin...");
+
+ super.start(context);
+ plugin = this;
+
+ StudioLogger.debug(CodeSnippetsPlugin.class,
+ "MOTODEV Android Code Snippets Plugin started.");
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
+ */
+ @Override
+ public void stop(BundleContext context) throws Exception
+ {
+ plugin = null;
+ super.stop(context);
+ }
+
+ /**
+ * Returns the shared instance
+ *
+ * @return the shared instance
+ */
+ public static CodeSnippetsPlugin getDefault()
+ {
+ return plugin;
+ }
+}
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/SnippetsViewContributionItem.java b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/SnippetsViewContributionItem.java
new file mode 100644
index 0000000..d869601
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/SnippetsViewContributionItem.java
@@ -0,0 +1,227 @@
+/*
+* Copyright (C) 2012 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.motorola.studio.android.codesnippets;
+
+import java.util.Iterator;
+import java.util.List;
+
+import org.eclipse.jface.action.ControlContribution;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.eclipse.swt.widgets.Event;
+import org.eclipse.swt.widgets.Listener;
+import org.eclipse.swt.widgets.Text;
+import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteDrawer;
+import org.eclipse.wst.common.snippets.internal.palette.SnippetPaletteItem;
+import org.eclipse.wst.common.snippets.internal.ui.SnippetsView;
+
+import com.motorola.studio.android.codesnippets.i18n.AndroidSnippetsNLS;
+
+@SuppressWarnings("restriction")
+public class SnippetsViewContributionItem extends ControlContribution
+{
+ private final SnippetsView view;
+
+ public SnippetsViewContributionItem(SnippetsView view)
+ {
+ super("com.motorola.studio.android.codesnippets.search");
+ this.view = view;
+ }
+
+ private Text text;
+
+ final String INITIAL_TEXT = AndroidSnippetsNLS.UI_Snippet_SearchLabel;
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.action.ControlContribution#computeWidth(org.eclipse.swt.widgets.Control)
+ */
+ @Override
+ protected int computeWidth(Control control)
+ {
+ return text.computeSize(100, SWT.DEFAULT).x;
+ }
+
+ @Override
+ protected Control createControl(Composite parent)
+ {
+
+ text = new Text(parent, SWT.BORDER | SWT.SEARCH | SWT.ICON_SEARCH);
+
+ text.setToolTipText(INITIAL_TEXT);
+ text.setEnabled(true);
+ text.setEditable(true);
+ text.setMessage(INITIAL_TEXT);
+
+ resetView();
+
+ text.addListener(SWT.Modify, new Listener()
+ {
+ public void handleEvent(Event event)
+ {
+ String typed = text.getText().toLowerCase();
+
+ // variables for the first inner loop
+ Object rootChildObject = null;
+ SnippetPaletteDrawer snippetPaletteDrawer = null;
+ SnippetPaletteItem snippetPalletItem = null;
+
+ // variables for the second inner loop
+ List<?> snippetPalleteDrawerChildren = null;
+ Iterator<?> snippetPalleteDrawerIterator = null;
+ Integer foundItemsCount = null;
+ Integer lastIndex = null;
+ Object snippetPalletObject = null;
+
+ // get text and items to be sought in
+ List<?> rootChildren = view.getRoot().getChildren();
+ Iterator<?> rootChildremIterator = rootChildren.iterator();
+
+ /* Here the idea is to iterate through the snippets labels, text and codes,
+ * and find a match. In case there are results, a number of found items by category
+ * is displayed.
+ */
+ while (rootChildremIterator.hasNext())
+ {
+ rootChildObject = rootChildremIterator.next();
+ if (rootChildObject instanceof SnippetPaletteDrawer)
+ {
+ snippetPaletteDrawer = (SnippetPaletteDrawer) rootChildObject;
+ snippetPalleteDrawerChildren = snippetPaletteDrawer.getChildren();
+ snippetPalleteDrawerIterator = snippetPalleteDrawerChildren.iterator();
+ foundItemsCount = 0;
+ while (snippetPalleteDrawerIterator.hasNext())
+ {
+ snippetPalletObject = snippetPalleteDrawerIterator.next();
+ if (snippetPalletObject instanceof SnippetPaletteItem)
+ {
+ snippetPalletItem = (SnippetPaletteItem) snippetPalletObject;
+
+ // there must be a match for either the label, description or code of the snippet
+ if (snippetPalletItem.getLabel().toLowerCase().contains(typed)
+ || snippetPalletItem.getDescription().toLowerCase()
+ .contains(typed)
+ || snippetPalletItem.getContentString().toLowerCase()
+ .contains(typed))
+ {
+ snippetPalletItem.setVisible(true);
+ foundItemsCount++;
+ }
+ else
+ {
+ // since no match was found for the snippets, try to find for its category label
+ if (snippetPaletteDrawer.getLabel().toLowerCase()
+ .contains(typed))
+ {
+ snippetPalletItem.setVisible(true);
+ foundItemsCount++;
+ }
+ else
+ {
+ snippetPalletItem.setVisible(false);
+ }
+ }
+ }
+ }
+
+ // display the number of found items between parenthesis
+ lastIndex = snippetPaletteDrawer.getLabel().lastIndexOf(")");
+ if (lastIndex == -1)
+ {
+ snippetPaletteDrawer.setLabel(snippetPaletteDrawer.getLabel() + " ("
+ + foundItemsCount + ")");
+ }
+ else
+ {
+ snippetPaletteDrawer.setLabel(snippetPaletteDrawer.getLabel()
+ .replaceFirst("\\(\\d+\\)",
+ "(" + foundItemsCount.toString() + ")"));
+ }
+
+ /*
+ * In case no match is found, hide the pallete and all
+ * its children, otherwise display the number of items
+ * found between parenthesis.
+ */
+ if (foundItemsCount == 0)
+ {
+ snippetPaletteDrawer.setVisible(false);
+ snippetPaletteDrawer.setFilters(new String[]
+ {
+ "!"
+ });
+ }
+ else
+ {
+ // show the item
+ snippetPaletteDrawer.setVisible(true);
+ snippetPaletteDrawer.setFilters(new String[]
+ {
+ "*"
+ });
+ }
+ }
+ }
+ }
+
+ });
+
+ return text;
+ }
+
+ /**
+ * Set all items to be visible.
+ */
+ private void resetView()
+ {
+ // get text and items to be sought in
+ List<?> rootChildren = view.getRoot().getChildren();
+ Iterator<?> rootChildremIterator = rootChildren.iterator();
+
+ /*
+ * Here the idea is to iterate through the snippets labels, text and codes,
+ * and set everything to visible, since the view is saving the state.
+ */
+ while (rootChildremIterator.hasNext())
+ {
+ Object rootChildObject = rootChildremIterator.next();
+ if (rootChildObject instanceof SnippetPaletteDrawer)
+ {
+ SnippetPaletteDrawer snippetPaletteDrawer = (SnippetPaletteDrawer) rootChildObject;
+ List<?> snippetPalleteDrawerChildren = snippetPaletteDrawer.getChildren();
+ Iterator<?> snippetPalleteDrawerIterator = snippetPalleteDrawerChildren.iterator();
+ snippetPaletteDrawer.setVisible(true);
+ while (snippetPalleteDrawerIterator.hasNext())
+ {
+ Object snippetPalletObject = snippetPalleteDrawerIterator.next();
+ if (snippetPalletObject instanceof SnippetPaletteItem)
+ {
+ SnippetPaletteItem snippetPalletItem =
+ (SnippetPaletteItem) snippetPalletObject;
+ snippetPalletItem.setVisible(true);
+ }
+ }
+ }
+
+ }
+ }
+
+ public void clean()
+ {
+ text.setText("");
+ }
+}
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/TooltipDisplayConfigContriutionItem.java b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/TooltipDisplayConfigContriutionItem.java
new file mode 100644
index 0000000..2a814c2
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/TooltipDisplayConfigContriutionItem.java
@@ -0,0 +1,164 @@
+/*
+* Copyright (C) 2012 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.motorola.studio.android.codesnippets;
+
+import org.eclipse.core.runtime.preferences.ConfigurationScope;
+import org.eclipse.core.runtime.preferences.IEclipsePreferences;
+import org.eclipse.jface.action.ControlContribution;
+import org.eclipse.jface.dialogs.IDialogSettings;
+import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.SelectionEvent;
+import org.eclipse.swt.events.SelectionListener;
+import org.eclipse.swt.layout.RowLayout;
+import org.eclipse.swt.widgets.Button;
+import org.eclipse.swt.widgets.Composite;
+import org.eclipse.swt.widgets.Control;
+import org.osgi.service.prefs.BackingStoreException;
+
+import com.motorola.studio.android.codesnippets.i18n.AndroidSnippetsNLS;
+import com.motorola.studio.android.common.log.StudioLogger;
+
+/**
+ * This {@link ControlContribution} adds the check box button which
+ * shows or hides the tooltip of the snippet.
+ *
+ * @see ControlContribution
+ * @see {@link AndroidSnippetsStartup}
+ *
+ */
+public class TooltipDisplayConfigContriutionItem extends ControlContribution
+{
+ /**
+ * Listener which updates the status of whether or not to display
+ * the tool tip.
+ *
+ * @see SelectionListener
+ *
+ */
+ private final class TooltipSelectionListener implements SelectionListener
+ {
+ /**
+ * Here the state of the tooltip display button is persisted in
+ * the {@link IDialogSettings}.
+ *
+ * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ public void widgetSelected(SelectionEvent e)
+ {
+ // action for when the check box is pressed.
+ performButtonSelection();
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
+ */
+ public void widgetDefaultSelected(SelectionEvent e)
+ {
+ // do nothing
+ }
+ }
+
+ /**
+ * Check box {@link Button} which shows or hides the tooltip.
+ */
+ private Button showToolTipButton = null;
+
+ /**
+ * {@link IDialogSettings} field for whether or not the tooltip
+ * is to be displayed.
+ */
+ private static final String DIALOG_SETTINGS__IS_TOOLTIP_DISPLAYED = "IsTooltipDisplayed";
+
+ /**
+ * Constructor which initiates this {@link ControlContribution}.
+ */
+ public TooltipDisplayConfigContriutionItem()
+ {
+ super("com.motorola.studio.android.codesnippets.tooltipDisplayConfig"); //$NON-NLS-1$
+ }
+
+ /* (non-Javadoc)
+ * @see org.eclipse.jface.action.ControlContribution#createControl(org.eclipse.swt.widgets.Composite)
+ */
+ @Override
+ protected Control createControl(Composite parent)
+ {
+ // adjust layout in order to produce space to the left
+ Composite mainComposite = new Composite(parent, SWT.NONE);
+ RowLayout layout = new RowLayout(SWT.FILL);
+ layout.center = true;
+ layout.marginLeft = 10;
+ mainComposite.setLayout(layout);
+
+ // create the check box button
+ showToolTipButton = new Button(mainComposite, SWT.CHECK);
+ showToolTipButton
+ .setText(AndroidSnippetsNLS.TooltipDisplayConfigContriutionItem_ShowPreview);
+ showToolTipButton.addSelectionListener(new TooltipSelectionListener());
+
+ // set the selection persisted
+ IEclipsePreferences preferences = getEclipsePreferences();
+ boolean isTooltipDisplayed =
+ preferences.getBoolean(DIALOG_SETTINGS__IS_TOOLTIP_DISPLAYED, true);
+ showToolTipButton.setSelection(isTooltipDisplayed);
+ performButtonSelection();
+
+ return mainComposite;
+ }
+
+ /**
+ * Returns <code>true</code> in case the tool tip is to
+ * be displayed, or <code>false</code> should it be hidden.
+ *
+ * @return <code>true</code> in case the tool tip
+ * is to be displayed, <code>false</code> otherwise.
+ */
+ public boolean isTooltipDisplayed()
+ {
+ return showToolTipButton.getSelection();
+ }
+
+ /**
+ * Method called when the check box {@link Button} is called. It
+ * persists the check box selection state in the {@link IDialogSettings}.
+ */
+ private void performButtonSelection()
+ {
+ // persist whether or not to show the tooltip
+ IEclipsePreferences preferences = getEclipsePreferences();
+ preferences.putBoolean(DIALOG_SETTINGS__IS_TOOLTIP_DISPLAYED,
+ showToolTipButton.getSelection());
+ try
+ {
+ preferences.flush();
+ }
+ catch (BackingStoreException bse)
+ {
+ StudioLogger.error(TooltipDisplayConfigContriutionItem.class.toString(),
+ "Preferences for snippets could not be saved.", bse); //$NON-NLS-1$
+ }
+ }
+
+ /**
+ * Get Eclipse´s preferences.
+ *
+ * @return Return Eclipse´s preferences.
+ */
+ private IEclipsePreferences getEclipsePreferences()
+ {
+ return ConfigurationScope.INSTANCE.getNode(AndroidSnippetsStartup.SNIPPETS_VIEW_ID);
+ }
+}
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/AndroidSnippetsNLS.java b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/AndroidSnippetsNLS.java
new file mode 100644
index 0000000..07c77d8
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/AndroidSnippetsNLS.java
@@ -0,0 +1,55 @@
+/*
+* Copyright (C) 2012 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.motorola.studio.android.codesnippets.i18n;
+
+import org.eclipse.osgi.util.NLS;
+
+/**
+ * This class is the NLS component for Code Snippets plug-in
+ *
+ */
+public class AndroidSnippetsNLS extends NLS
+{
+ /**
+ * The bundle location.
+ * It refers to messages.properties file inside this package
+ */
+ private static final String BUNDLE_NAME =
+ "com.motorola.studio.android.codesnippets.i18n.androidSnippetsNLS";
+
+ static
+ {
+ NLS.initializeMessages(BUNDLE_NAME, AndroidSnippetsNLS.class);
+ }
+
+ public static String AndroidPermissionInsertSnippet_Msg_AddToManifest_Msg;
+
+ public static String AndroidPermissionInsertSnippet_Msg_AddToManifest_Title;
+
+ public static String AndroidPermissionInsertSnippet_PermissionPrefix;
+
+ public static String AndroidPermissionInsertSnippet_PermissionSuffix;
+
+ public static String TooltipDisplayConfigContriutionItem_ShowPreview;
+
+ /*
+ * UI strings area
+ */
+ public static String UI_Snippet_Preview;
+
+ public static String UI_Snippet_SearchLabel;
+
+}
diff --git a/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/androidSnippetsNLS.properties b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/androidSnippetsNLS.properties
new file mode 100644
index 0000000..b66bfd4
--- /dev/null
+++ b/src/plugins/snippets/src/com/motorola/studio/android/codesnippets/i18n/androidSnippetsNLS.properties
@@ -0,0 +1,7 @@
+AndroidPermissionInsertSnippet_Msg_AddToManifest_Msg=This snippet requires specific permissions in order to work correctly.\nShould the following permissions be added to AndroidManifest.xml?\n{0}
+AndroidPermissionInsertSnippet_Msg_AddToManifest_Title=Snippet Required Permissions
+AndroidPermissionInsertSnippet_PermissionPrefix=-
+AndroidPermissionInsertSnippet_PermissionSuffix=\n
+TooltipDisplayConfigContriutionItem_ShowPreview=Show Preview
+UI_Snippet_Preview=Snippet Preview:
+UI_Snippet_SearchLabel=Search... \ No newline at end of file