Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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).

Trevor Johns

October 20, 2012
Tweet

Other Decks in Programming

Transcript

  1. "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 “ ”
  2. so•cial |ˈsōSHəl| adjetive Software that creates and strengthens human bonds

    through personal interaction, discovery, and participation.
  3. 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.
  4. 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
  5. 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
  6. 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
  7. @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
  8. 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.
  9. Social Stream Remember: Many devices store the last 5 social

    stream events for each content, but this is configurable by device manufacturers.
  10. 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
  11. 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.
  12. 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.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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.
  19. 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...
  20. 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.
  21. 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.
  22. 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 } }
  23. 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.)
  24. 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!
  25. 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.
  26. 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!
  27. NFC NDEF Record Type Name Field (TNF) 3 Bits Type

    256 Bytes ID 256 Bytes Payload Variable
  28. 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.
  29. •NFC Push •Send NDEF messages between devices –setNdefPushMessage() –ACTION_NDEF_DISCOVERED •Share

    app by default •Transparent Bluetooth handoff for larger data Android Beam NFC
  30. 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
  31. 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
  32. 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
  33. YADDA YADDA Android, Google are registered trademarks of Google Inc.

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