Slide 1

Slide 1 text

Trevor Johns Android Developer Relations +Trevor Johns | @tjohns Android’s Social APIs

Slide 2

Slide 2 text

"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 “ ”

Slide 3

Slide 3 text

so•cial |ˈsōSHəl| adjetive Software that creates and strengthens human bonds through personal interaction, discovery, and participation.

Slide 4

Slide 4 text

personal interaction, discovery, and participation.

Slide 5

Slide 5 text

Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream API NFC Android’s Social APIs

Slide 6

Slide 6 text

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.

Slide 7

Slide 7 text

ACTION_SEND

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

ArrayList imageUris = new ArrayList(); 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

Slide 11

Slide 11 text

Share Action Provider Available on API 14 (Android 4.0/ICS) and above. (Or using support library.)

Slide 12

Slide 12 text

... ACTION_SEND Example: ShareActionProvider (menu.xml)

Slide 13

Slide 13 text

@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

Slide 14

Slide 14 text

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.

Slide 15

Slide 15 text

Social Stream

Slide 16

Slide 16 text

Social Stream Remember: Many devices store the last 5 social stream events for each content, but this is configurable by device manufacturers.

Slide 17

Slide 17 text

Background: Contacts Schema Social Stream

Slide 18

Slide 18 text

Background: Contacts Schema Social Stream

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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.

Slide 21

Slide 21 text

QuickContactBadge badgeSmall = (QuickContactBadge) findViewById(R.id.badge_small); badgeSmall.assignContactFromEmail("[email protected]", true); badgeSmall.setMode(ContactsContract.QuickContact.MODE_SMALL); Quick Action Button Example: Displaying Quick Action Button

Slide 22

Slide 22 text

Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream API NFC Android’s Social APIs

Slide 23

Slide 23 text

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.

Slide 24

Slide 24 text

NSD Each service is issued a unique name: (Internet Printing Protocol) _._ Example: _ipp._tcp Protocol names should be registered with the IANA at http://www.iana.org/form/ports-services.

Slide 25

Slide 25 text

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.

Slide 26

Slide 26 text

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.

Slide 27

Slide 27 text

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.

Slide 28

Slide 28 text

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.

Slide 29

Slide 29 text

Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream API NFC Android’s Social APIs

Slide 30

Slide 30 text

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.

Slide 31

Slide 31 text

WiFi Direct WiFi Direct Checklist: 1. Request permissions...

Slide 32

Slide 32 text

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.

Slide 33

Slide 33 text

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.

Slide 34

Slide 34 text

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 } }

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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!

Slide 37

Slide 37 text

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.

Slide 38

Slide 38 text

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!

Slide 39

Slide 39 text

NFC NFC Payload NDEF (NFC Data Exchange Format)

Slide 40

Slide 40 text

NFC NDEF Record Type Name Field (TNF) 3 Bits Type 256 Bytes ID 256 Bytes Payload Variable

Slide 41

Slide 41 text

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.

Slide 42

Slide 42 text

•NFC Push •Send NDEF messages between devices –setNdefPushMessage() –ACTION_NDEF_DISCOVERED •Share app by default •Transparent Bluetooth handoff for larger data Android Beam NFC

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

NFC Implementing Beam Required Intent Filter

Slide 47

Slide 47 text

Personal Interaction Discovery Participation ACTION_SEND NSD WiFi Direct Social Stream API NFC Android’s Social APIs

Slide 48

Slide 48 text

+Trevor Johns | @tjohns Questions?

Slide 49

Slide 49 text

YADDA YADDA Android, Google are registered trademarks of Google Inc. All other trademarks and copyrights are the property of their respective owners.