Android's Social APIs

Android's Social APIs

Learn about the APIs that help make Android more social. We'll explore ways that application developers can display status updates, share content, enable real-time communication, detect nearby devices, and interact with the physical world. No social network required.

Topics: Share Intent, Social Stream, Network Service Discovery (NSD), WiFi Direct, Near-Field Communication (NFC)

Presented at GDG DevFest West (http://devfestwest.com).

352d3f1508da812cfac456dd8cf4e721?s=128

Trevor Johns

October 20, 2012
Tweet

Transcript

  1. Trevor Johns Android Developer Relations +Trevor Johns | @tjohns Android’s

    Social APIs
  2. "With Android Ice Cream Sandwich, we set out to build

    software that supports emotional connections between humans and the devices they carry. We wanted to build the most personal device that the user has ever owned." — Daniel Lehmann, TL Android Apps Team “ ”
  3. so•cial |ˈsōSHəl| adjetive Software that creates and strengthens human bonds

    through personal interaction, discovery, and participation.
  4. personal interaction, discovery, and participation.

  5. Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream

    API NFC Android’s Social APIs
  6. ACTION_SEND An intent action signaling an attachment which is meant

    to be delivered to somebody else (aka “share”). Remember: Intents describe a action to be performed. When executed, the system will locate Activities which can perform that action.
  7. ACTION_SEND

  8. Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my

    text to send."); sendIntent.setType("text/plain"); startActivity( Intent.createChooser(sendIntent, “Share snippet”)); To share content: •Create a new Intent. •Attach content as an Extra. •Set content’s MIME type. •Use Intent.createChooser(). •Call startActivity(). ACTION_SEND Example: Sharing Text
  9. Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage); shareIntent.setType("image/jpeg"); startActivity(

    Intent.createChooser(shareIntent, “Share picture”)); To share content: •Create a new Intent. •Attach content as an Extra. •Set content’s MIME type. •Use Intent.createChooser(). •Call startActivity(). ACTION_SEND Example: Sharing Images
  10. ArrayList<Uri> imageUris = new ArrayList<Uri>(); imageUris.add(imageUri1); // Add your image

    URIs here imageUris.add(imageUri2); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND_MULTIPLE); shareIntent.putParcelableArrayListExtra( Intent.EXTRA_STREAM, imageUris); shareIntent.setType("image/*"); startActivity(Intent.createChooser( shareIntent, "Share images to..")); To share multiple pieces of content use ACTION_SEND_MULTIPLE. ACTION_SEND Example: Sharing Images
  11. Share Action Provider Available on API 14 (Android 4.0/ICS) and

    above. (Or using support library.)
  12. <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_item_share" android:showAsAction="ifRoom" android:title="Share" android:actionProviderClass="android.widget.ShareActionProvider" /> ... </menu>

    ACTION_SEND Example: ShareActionProvider (menu.xml)
  13. @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate menu resource

    file. getMenuInflater().inflate(R.menu.share_menu, menu); // Locate MenuItem with ShareActionProvider MenuItem item = menu.findItem(R.id.menu_item_share); // Fetch and store ShareActionProvider mShareActionProvider = (ShareActionProvider) item.getActionProvider(); // Return true to display menu return true; } // Call to update the share intent (when content changes) private void setShareIntent(Intent shareIntent) { if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(shareIntent); } } ACTION_SEND Example: Updating ShareActionProvider Intent
  14. Social Stream API Allows storing (and retrieving) status updates for

    existing contacts on a device. Available on API 14 (Android 4.0/ICS) and above.
  15. Social Stream

  16. Social Stream Remember: Many devices store the last 5 social

    stream events for each content, but this is configurable by device manufacturers.
  17. Background: Contacts Schema Social Stream

  18. Background: Contacts Schema Social Stream

  19. private static void addContactStreamItem(Context context, long rawContactId, String text, String

    comments, long timestamp, String accountName, String accountType){ ContentValues values = new ContentValues(); values.put(StreamItems.RAW_CONTACT_ID, rawContactId); values.put(StreamItems.TEXT, "Taking my robot for a walk"); values.put(StreamItems.TIMESTAMP, timestamp); values.put(StreamItems.COMMENTS, comments); values.put(StreamItems.ACCOUNT_NAME, accountName); values.put(StreamItems.ACCOUNT_TYPE, accountType); context.getContentResolver().insert( StreamItems.CONTENT_URI, values); } To insert new Social Stream items: Social Stream Example: Adding To Social Stream
  20. QuickContactBadge Provides one-touch access to contact details, via popup window.

    (Easier than reading SocialStream items directly, shares system UI.) Available on API 6 (Android 1.6/Donut) and above.
  21. QuickContactBadge badgeSmall = (QuickContactBadge) findViewById(R.id.badge_small); badgeSmall.assignContactFromEmail("any@gmail.com", true); badgeSmall.setMode(ContactsContract.QuickContact.MODE_SMALL); Quick Action

    Button Example: Displaying Quick Action Button
  22. Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream

    API NFC Android’s Social APIs
  23. NSD Network Service Discovery allows detecting other devices on the

    local network that support the services your app requests. Available on devices running API 16 (Android 4.1/ Jelly Bean) and above. Built using open protocols: Multicast DNS (mDNS) and the DNS-SD protocol.
  24. NSD Each service is issued a unique name: (Internet Printing

    Protocol) _<protocol>._<transportlayer> Example: _ipp._tcp Protocol names should be registered with the IANA at http://www.iana.org/form/ports-services.
  25. NSD public void initializeServerSocket() { // Initialize a server socket

    on the next available port. mServerSocket = new ServerSocket(0); // Store the chosen port. mLocalPort = mServerSocket.getLocalPort(); ... } Example: Requesting any available port No need to assign a dedicated port for your application. Pick any available port, then advertise.
  26. NSD public void registerService(int port) { NsdServiceInfo serviceInfo = new

    NsdServiceInfo(); serviceInfo.setServiceName("Rick Deckard"); serviceInfo.setServiceType("_myapp._tcp."); serviceInfo.setPort(port); mNsdManager = Context.getSystemService( Context.NSD_SERVICE); mNsdManager.registerService( serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener); } Example: Registering a service To advertise, use NsdManager.registerService(). Results are posted async via callback to a NsdManager.RegistrationListener.
  27. NSD mNsdManager.discoverServices( "_myapp._tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener); Example: Discovering peers To find

    peers, use NsdManager.discoverServices(). Results are posted async via callback to a NsdManager.DiscoveryListener.
  28. NSD mNsdManager.resolveService(anNsdServiceInfo, new NsdManager.ResolveListener() { @Override public void onResolveFailed( NsdServiceInfo

    serviceInfo, int errorCode) {...} @Override public void onServiceResolved(NsdServiceInfo serviceInfo) { int port = serviceInfo.getPort(); InetAddress host = serviceInfo.getHost(); } }; ); Example: Discovering peers To connect to a peer, use NsdManager.resolveService(). Provide NsdServiceInfo from discovery step. Results are posted async via callback to a NsdManager. ResolveListener.
  29. Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream

    API NFC Android’s Social APIs
  30. WiFi Direct Peer-to-peer WiFi connection, with no need for Internet

    connection or traditional AP. Faster & longer range than Bluetooth. Discover peers, form groups, exchange data. Available on devices running API 14 (Android 4.0/ Honeycomb) and above.
  31. WiFi Direct <uses-sdk android:minSdkVersion="14" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"

    /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> WiFi Direct Checklist: 1. Request permissions...
  32. WiFi Direct protected void onCreate(Bundle savedInstanceState){ ... mManager = (WifiP2pManager)

    getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); mReceiver = new WiFiDirectBroadcastReceiver(manager, channel, this); ... mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); } WiFi Direct Checklist: 2. Create WiFiP2pManager, Channel object, and a new Broadcast Receiver. Add relevant Intent filters to your process.
  33. WiFi Direct /* register the broadcast receiver with the intent

    values to be matched */ @Override protected void onResume() { super.onResume(); registerReceiver(mReceiver, mIntentFilter); } /* unregister the broadcast receiver */ @Override protected void onPause() { super.onPause(); unregisterReceiver(mReceiver); } WiFi Direct Checklist: 3. Register your Broadcast Receiver.
  34. WiFi Direct WiFi Direct Checklist: 4. Check to make sure

    WiFi Direct is on and supported (inside Broadcast Receiver’s onReceive()). String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { int state = intent.getIntExtra( WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { // Wifi Direct is enabled } else { // Wi-Fi Direct is not enabled } }
  35. WiFi Direct Interacting With Peers Start Scan: Use discoverPeers(), listen

    for WIFI_P2P_PEERS_CHANGED_ACTION broadcast. Retrieve Scan Results: Use manager.requestPeers(). List for PeerListListener. onPeersAvailable() callback, which will contain an iterable WifiP2pDeviceList. Connecting: Use connect(), passing in the device address obtained in WifiP2pDeviceList. WifiP2pDevice device; WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; manager.connect(channel, config, new ActionListener() {...}); ... Then open a socket! (Tip: Use NSD to negotiate host/port for the connection.)
  36. NFC Near Field Communication provides ultra-short range (~1cm) communication via

    RF. Available on API 9 (Android 2.3/Gingerbread) and above, but notable changes in API 14 (Android 4.0/ ICS). Not just for payment cards!
  37. NFC Operating Modes (Simplified) Tag Emulation: Simulates a standalone NFC

    tag. Tag Reader: Listen for NFC tags. (Default mode.) Tag Writer: Reprogram NFC tags. P2P: Bidirectional communication between two NFC devices.
  38. NFC A note on tags... Android devices are required to

    support NFC Forum Type 1-4 tags. They may also support other (proprietary) tag formats, depending on the NFC chipset. For compatibility, make sure your tags are NFC Forum compatible!
  39. NFC NFC Payload NDEF (NFC Data Exchange Format)

  40. NFC NDEF Record Type Name Field (TNF) 3 Bits Type

    256 Bytes ID 256 Bytes Payload Variable
  41. NFC But don’t worry about any of that. Instead... createUri():

    Web resources. createMime(): Mixed-media content. (Images, Text, etc.) createExternal(): Opaque data owned by the application. createApplicationRecord(): Android Application Record (AAR) used to store app’s package name.
  42. •NFC Push •Send NDEF messages between devices –setNdefPushMessage() –ACTION_NDEF_DISCOVERED •Share

    app by default •Transparent Bluetooth handoff for larger data Android Beam NFC
  43. NFC Implementing Beam public class Beam extends Activity implements CreateNdefMessageCallback

    { NfcAdapter mNfcAdapter; @Override public void onCreate(Bundle savedInstanceState) { ... // Check for available NFC Adapter mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter == null) { Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show(); finish(); return; } // Register callback mNfcAdapter.setNdefPushMessageCallback(this, this); } ... } Can also use setNdefPushMessage() for synchronous API (matches ShareActionProvider model). Example: Setup Code
  44. NFC Implementing Beam @Override public NdefMessage createNdefMessage(NfcEvent event) { String

    text = ("Hello Android!"); NdefMessage msg = new NdefMessage( NdefRecord.createMime( "application/com.example.android.beam", text.getBytes()) // AAR is optional, specifying it overrides tag dispatch , NdefRecord.createApplicationRecord("com.example.android.beam") }); return msg; } Example: Sending Data
  45. NFC Implementing Beam @Override public void onResume() { super.onResume(); //

    Check to see that the Activity started due to an Android Beam if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) { processIntent(getIntent()); } } void processIntent(Intent intent) { Parcelable[] rawMsgs = intent.getParcelableArrayExtra( NfcAdapter.EXTRA_NDEF_MESSAGES); // only one message sent during the beam NdefMessage msg = (NdefMessage) rawMsgs[0]; // record 0 contains the MIME type, record 1 is the AAR String data = msg.getRecords()[0].getPayload(); } Example: Receiving Data
  46. NFC Implementing Beam <intent-filter> <action android:name="android.nfc.action.NDEF_DISCOVERED"/> <category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="application/com.example.android.beam"/>

    </intent-filter> Required Intent Filter
  47. Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream

    API NFC Android’s Social APIs
  48. +Trevor Johns | @tjohns Questions?

  49. YADDA YADDA Android, Google are registered trademarks of Google Inc.

    All other trademarks and copyrights are the property of their respective owners.