Sync prebuilts for lmp-docs to commit c206cb304e2e334211838389c81d7766a0784068
Includes manual override for wearable samples, ported from klp-modular-docs
as of commit 67660d44402e398f19b6e4c975039cdea65aa7ea.
Change-Id: Icff648b5e7c443de07794b67fa3c4aad2dea6688
diff --git a/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/DetailActivity.java b/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/DetailActivity.java
index 741cd26..9589008 100644
--- a/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/DetailActivity.java
+++ b/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/DetailActivity.java
@@ -65,8 +65,8 @@
* This could be done in the layout XML, but exposing it via static variables allows easy
* querying from other Activities
*/
- mHeaderImageView.setViewName(VIEW_NAME_HEADER_IMAGE);
- mHeaderTitle.setViewName(VIEW_NAME_HEADER_TITLE);
+ mHeaderImageView.setTransitionName(VIEW_NAME_HEADER_IMAGE);
+ mHeaderTitle.setTransitionName(VIEW_NAME_HEADER_TITLE);
// END_INCLUDE(detail_set_view_name)
loadItem(item);
diff --git a/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/MainActivity.java b/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/MainActivity.java
index 3630990..9c51789 100644
--- a/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/MainActivity.java
+++ b/prebuilts/gradle/ActivitySceneTransitionBasic/Application/src/main/java/com/example/android/activityscenetransitionbasic/MainActivity.java
@@ -135,8 +135,8 @@
* As we're in an adapter we need to set each view's name dynamically, using the
* item's ID so that the names are unique.
*/
- image.setViewName("grid:image:" + item.getId());
- name.setViewName("grid:name:" + item.getId());
+ image.setTransitionName("grid:image:" + item.getId());
+ name.setTransitionName("grid:name:" + item.getId());
// END_INCLUDE(grid_set_view_name)
return view;
diff --git a/prebuilts/gradle/AdvancedImmersiveMode/Application/build.gradle b/prebuilts/gradle/AdvancedImmersiveMode/Application/build.gradle
index 78ae552..bd1120c 100644
--- a/prebuilts/gradle/AdvancedImmersiveMode/Application/build.gradle
+++ b/prebuilts/gradle/AdvancedImmersiveMode/Application/build.gradle
@@ -26,12 +26,12 @@
'template'] // boilerplate code that is generated by the sample template process
android {
- compileSdkVersion 19
+ compileSdkVersion 21
buildToolsVersion "21.0.0"
defaultConfig {
minSdkVersion 4
- targetSdkVersion 19
+ targetSdkVersion 21
}
sourceSets {
diff --git a/prebuilts/gradle/AgendaData/Application/build.gradle b/prebuilts/gradle/AgendaData/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/AgendaData/Application/build.gradle
+++ b/prebuilts/gradle/AgendaData/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/AgendaData/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/AgendaData/Application/src/main/AndroidManifest.xml
index b5bebc3..284e0e6 100644
--- a/prebuilts/gradle/AgendaData/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/AgendaData/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.agendadata">
+ package="com.example.android.wearable.agendadata">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
@@ -34,7 +34,7 @@
android:value="@integer/google_play_services_version" />
<activity
- android:name="com.example.android.agendadata.MainActivity"
+ android:name="com.example.android.wearable.agendadata.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
@@ -43,6 +43,6 @@
</intent-filter>
</activity>
- <service android:name="com.example.android.agendadata.CalendarQueryService"/>
+ <service android:name="com.example.android.wearable.agendadata.CalendarQueryService"/>
</application>
</manifest>
diff --git a/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/CalendarQueryService.java b/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/CalendarQueryService.java
new file mode 100644
index 0000000..c39a5ed
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/CalendarQueryService.java
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.agendadata;
+
+
+import static com.example.android.wearable.agendadata.Constants.TAG;
+import static com.example.android.wearable.agendadata.Constants.CONNECTION_TIME_OUT_MS;
+import static com.example.android.wearable.agendadata.Constants.CAL_DATA_ITEM_PATH_PREFIX;
+import static com.example.android.wearable.agendadata.Constants.ALL_DAY;
+import static com.example.android.wearable.agendadata.Constants.BEGIN;
+import static com.example.android.wearable.agendadata.Constants.DATA_ITEM_URI;
+import static com.example.android.wearable.agendadata.Constants.DESCRIPTION;
+import static com.example.android.wearable.agendadata.Constants.END;
+import static com.example.android.wearable.agendadata.Constants.EVENT_ID;
+import static com.example.android.wearable.agendadata.Constants.ID;
+import static com.example.android.wearable.agendadata.Constants.PROFILE_PIC;
+import static com.example.android.wearable.agendadata.Constants.TITLE;
+
+import android.app.IntentService;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.database.Cursor;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.os.Bundle;
+import android.provider.CalendarContract;
+import android.provider.ContactsContract.CommonDataKinds.Email;
+import android.provider.ContactsContract.Contacts;
+import android.provider.ContactsContract.Data;
+import android.text.format.Time;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
+import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
+import com.google.android.gms.wearable.Asset;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import java.io.ByteArrayOutputStream;
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Queries calendar events using Android Calendar Provider API and creates a data item for each
+ * event.
+ */
+public class CalendarQueryService extends IntentService
+ implements ConnectionCallbacks, OnConnectionFailedListener {
+
+ private static final String[] INSTANCE_PROJECTION = {
+ CalendarContract.Instances._ID,
+ CalendarContract.Instances.EVENT_ID,
+ CalendarContract.Instances.TITLE,
+ CalendarContract.Instances.BEGIN,
+ CalendarContract.Instances.END,
+ CalendarContract.Instances.ALL_DAY,
+ CalendarContract.Instances.DESCRIPTION,
+ CalendarContract.Instances.ORGANIZER
+ };
+
+ private static final String[] CONTACT_PROJECTION = new String[] { Data._ID, Data.CONTACT_ID };
+ private static final String CONTACT_SELECTION = Email.ADDRESS + " = ?";
+
+ private GoogleApiClient mGoogleApiClient;
+
+ public CalendarQueryService() {
+ super(CalendarQueryService.class.getSimpleName());
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
+ // Query calendar events in the next 24 hours.
+ Time time = new Time();
+ time.setToNow();
+ long beginTime = time.toMillis(true);
+ time.monthDay++;
+ time.normalize(true);
+ long endTime = time.normalize(true);
+
+ List<Event> events = queryEvents(this, beginTime, endTime);
+ for (Event event : events) {
+ final PutDataMapRequest putDataMapRequest = event.toPutDataMapRequest();
+ if (mGoogleApiClient.isConnected()) {
+ Wearable.DataApi.putDataItem(
+ mGoogleApiClient, putDataMapRequest.asPutDataRequest()).await();
+ } else {
+ Log.e(TAG, "Failed to send data item: " + putDataMapRequest
+ + " - Client disconnected from Google Play Services");
+ }
+ }
+ mGoogleApiClient.disconnect();
+ }
+
+ private static String makeDataItemPath(long eventId, long beginTime) {
+ return CAL_DATA_ITEM_PATH_PREFIX + eventId + "/" + beginTime;
+ }
+
+ private static List<Event> queryEvents(Context context, long beginTime, long endTime) {
+ ContentResolver contentResolver = context.getContentResolver();
+ Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
+ ContentUris.appendId(builder, beginTime);
+ ContentUris.appendId(builder, endTime);
+
+ Cursor cursor = contentResolver.query(builder.build(), INSTANCE_PROJECTION,
+ null /* selection */, null /* selectionArgs */, null /* sortOrder */);
+ try {
+ int idIdx = cursor.getColumnIndex(CalendarContract.Instances._ID);
+ int eventIdIdx = cursor.getColumnIndex(CalendarContract.Instances.EVENT_ID);
+ int titleIdx = cursor.getColumnIndex(CalendarContract.Instances.TITLE);
+ int beginIdx = cursor.getColumnIndex(CalendarContract.Instances.BEGIN);
+ int endIdx = cursor.getColumnIndex(CalendarContract.Instances.END);
+ int allDayIdx = cursor.getColumnIndex(CalendarContract.Instances.ALL_DAY);
+ int descIdx = cursor.getColumnIndex(CalendarContract.Instances.DESCRIPTION);
+ int ownerEmailIdx = cursor.getColumnIndex(CalendarContract.Instances.ORGANIZER);
+
+ List<Event> events = new ArrayList<Event>(cursor.getCount());
+ while (cursor.moveToNext()) {
+ Event event = new Event();
+ event.id = cursor.getLong(idIdx);
+ event.eventId = cursor.getLong(eventIdIdx);
+ event.title = cursor.getString(titleIdx);
+ event.begin = cursor.getLong(beginIdx);
+ event.end = cursor.getLong(endIdx);
+ event.allDay = cursor.getInt(allDayIdx) != 0;
+ event.description = cursor.getString(descIdx);
+ String ownerEmail = cursor.getString(ownerEmailIdx);
+ Cursor contactCursor = contentResolver.query(Data.CONTENT_URI,
+ CONTACT_PROJECTION, CONTACT_SELECTION, new String[] {ownerEmail}, null);
+ int ownerIdIdx = contactCursor.getColumnIndex(Data.CONTACT_ID);
+ long ownerId = -1;
+ if (contactCursor.moveToFirst()) {
+ ownerId = contactCursor.getLong(ownerIdIdx);
+ }
+ contactCursor.close();
+ // Use event organizer's profile picture as the notification background.
+ event.ownerProfilePic = getProfilePicture(contentResolver, context, ownerId);
+ events.add(event);
+ }
+ return events;
+ } finally {
+ cursor.close();
+ }
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ }
+
+ private static Asset getDefaultProfile(Resources res) {
+ Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.nobody);
+ return Asset.createFromBytes(toByteArray(bitmap));
+ }
+
+ private static Asset getProfilePicture(ContentResolver contentResolver, Context context,
+ long contactId) {
+ if (contactId != -1) {
+ // Try to retrieve the profile picture for the given contact.
+ Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
+ InputStream inputStream = Contacts.openContactPhotoInputStream(contentResolver,
+ contactUri, true /*preferHighres*/);
+
+ if (null != inputStream) {
+ try {
+ Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
+ if (bitmap != null) {
+ return Asset.createFromBytes(toByteArray(bitmap));
+ } else {
+ Log.e(TAG, "Cannot decode profile picture for contact " + contactId);
+ }
+ } finally {
+ closeQuietly(inputStream);
+ }
+ }
+ }
+ // Use a default background image if the user has no profile picture or there was an error.
+ return getDefaultProfile(context.getResources());
+ }
+
+ private static byte[] toByteArray(Bitmap bitmap) {
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
+ byte[] byteArray = stream.toByteArray();
+ closeQuietly(stream);
+ return byteArray;
+ }
+
+ private static void closeQuietly(Closeable closeable) {
+ try {
+ closeable.close();
+ } catch (IOException e) {
+ Log.e(TAG, "IOException while closing closeable.", e);
+ }
+ }
+
+ private static class Event {
+
+ public long id;
+ public long eventId;
+ public String title;
+ public long begin;
+ public long end;
+ public boolean allDay;
+ public String description;
+ public Asset ownerProfilePic;
+
+ public PutDataMapRequest toPutDataMapRequest(){
+ final PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(
+ makeDataItemPath(eventId, begin));
+ DataMap data = putDataMapRequest.getDataMap();
+ data.putString(DATA_ITEM_URI, putDataMapRequest.getUri().toString());
+ data.putLong(ID, id);
+ data.putLong(EVENT_ID, eventId);
+ data.putString(TITLE, title);
+ data.putLong(BEGIN, begin);
+ data.putLong(END, end);
+ data.putBoolean(ALL_DAY, allDay);
+ data.putString(DESCRIPTION, description);
+ data.putAsset(PROFILE_PIC, ownerProfilePic);
+
+ return putDataMapRequest;
+ }
+ }
+}
diff --git a/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/Constants.java b/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/Constants.java
new file mode 100644
index 0000000..6dc6952
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/Constants.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.agendadata;
+
+/** Constants used in companion app. */
+public final class Constants {
+ private Constants() {
+ }
+
+ public static final String TAG = "AgendaDataSample";
+
+ public static final String CAL_DATA_ITEM_PATH_PREFIX = "/event";
+ // Timeout for making a connection to GoogleApiClient (in milliseconds).
+ public static final long CONNECTION_TIME_OUT_MS = 100;
+
+ public static final String EVENT_ID = "event_id";
+ public static final String ID = "id";
+ public static final String TITLE = "title";
+ public static final String DESCRIPTION = "description";
+ public static final String BEGIN = "begin";
+ public static final String END = "end";
+ public static final String DATA_ITEM_URI = "data_item_uri";
+ public static final String ALL_DAY = "all_day";
+ public static final String PROFILE_PIC = "profile_pic";
+}
diff --git a/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/MainActivity.java b/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/MainActivity.java
new file mode 100644
index 0000000..8e4063d
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/Application/src/main/java/com/example/android/wearable/agendadata/MainActivity.java
@@ -0,0 +1,202 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.agendadata;
+
+import static com.example.android.wearable.agendadata.Constants.TAG;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.content.IntentSender;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
+import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.common.data.FreezableUtils;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataItem;
+import com.google.android.gms.wearable.DataItemBuffer;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.NodeApi;
+import com.google.android.gms.wearable.Wearable;
+
+import java.util.List;
+
+public class MainActivity extends Activity implements NodeApi.NodeListener, ConnectionCallbacks,
+ OnConnectionFailedListener {
+
+ /** Request code for launching the Intent to resolve Google Play services errors. */
+ private static final int REQUEST_RESOLVE_ERROR = 1000;
+
+ private GoogleApiClient mGoogleApiClient;
+ private boolean mResolvingError = false;
+
+ private TextView mLogTextView;
+ ScrollView mScroller;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.main);
+ mLogTextView = (TextView) findViewById(R.id.log);
+ mScroller = (ScrollView) findViewById(R.id.scroller);
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ if (!mResolvingError) {
+ mGoogleApiClient.connect();
+ }
+ }
+
+ @Override
+ protected void onStop() {
+ if (mGoogleApiClient.isConnected()) {
+ Wearable.NodeApi.removeListener(mGoogleApiClient, this);
+ }
+ mGoogleApiClient.disconnect();
+ super.onStop();
+ }
+
+ public void onGetEventsClicked(View v) {
+ startService(new Intent(this, CalendarQueryService.class));
+ }
+
+ public void onDeleteEventsClicked(View v) {
+ if (mGoogleApiClient.isConnected()) {
+ Wearable.DataApi.getDataItems(mGoogleApiClient)
+ .setResultCallback(new ResultCallback<DataItemBuffer>() {
+ @Override
+ public void onResult(DataItemBuffer result) {
+ if (result.getStatus().isSuccess()) {
+ deleteDataItems(result);
+ } else {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onDeleteEventsClicked(): failed to get Data Items");
+ }
+ }
+ result.close();
+ }
+ });
+ } else {
+ Log.e(TAG, "Failed to delete data items"
+ + " - Client disconnected from Google Play Services");
+ }
+ }
+
+ private void deleteDataItems(DataItemBuffer dataItems) {
+ if (mGoogleApiClient.isConnected()) {
+ // Store the DataItem URIs in a List and close the buffer. Then use these URIs
+ // to delete the DataItems.
+ final List<DataItem> dataItemList = FreezableUtils.freezeIterable(dataItems);
+ dataItems.close();
+ for (final DataItem dataItem : dataItemList) {
+ final Uri dataItemUri = dataItem.getUri();
+ // In a real calendar application, this might delete the corresponding calendar
+ // event from the calendar data provider. In this sample, we simply delete the
+ // DataItem, but leave the phone's calendar data intact.
+ Wearable.DataApi.deleteDataItems(mGoogleApiClient, dataItemUri)
+ .setResultCallback(new ResultCallback<DataApi.DeleteDataItemsResult>() {
+ @Override
+ public void onResult(DataApi.DeleteDataItemsResult deleteResult) {
+ if (deleteResult.getStatus().isSuccess()) {
+ appendLog("Successfully deleted data item: " + dataItemUri);
+ } else {
+ appendLog("Failed to delete data item:" + dataItemUri);
+ }
+ }
+ });
+ }
+ } else {
+ Log.e(TAG, "Failed to delete data items"
+ + " - Client disconnected from Google Play Services");
+ }
+ }
+
+ private void appendLog(final String s) {
+ mLogTextView.post(new Runnable() {
+ @Override
+ public void run() {
+ mLogTextView.append(s);
+ mLogTextView.append("\n");
+ mScroller.fullScroll(View.FOCUS_DOWN);
+ }
+ });
+ }
+
+ @Override
+ public void onPeerConnected(Node peer) {
+ appendLog("Device connected");
+ }
+
+ @Override
+ public void onPeerDisconnected(Node peer) {
+ appendLog("Device disconnected");
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Connected to Google Api Service");
+ }
+ mResolvingError = false;
+ Wearable.NodeApi.addListener(mGoogleApiClient, this);
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ // Ignore
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Disconnected from Google Api Service");
+ }
+ if (null != Wearable.NodeApi) {
+ Wearable.NodeApi.removeListener(mGoogleApiClient, this);
+ }
+ if (mResolvingError) {
+ // Already attempting to resolve an error.
+ return;
+ } else if (result.hasResolution()) {
+ try {
+ mResolvingError = true;
+ result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
+ } catch (IntentSender.SendIntentException e) {
+ // There was an error with the resolution intent. Try again.
+ mGoogleApiClient.connect();
+ }
+ } else {
+ mResolvingError = false;
+ }
+ }
+}
diff --git a/prebuilts/gradle/AgendaData/Wearable/build.gradle b/prebuilts/gradle/AgendaData/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/AgendaData/Wearable/build.gradle
+++ b/prebuilts/gradle/AgendaData/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/AgendaData/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/AgendaData/Wearable/src/main/AndroidManifest.xml
index c91f09c..f2576af 100644
--- a/prebuilts/gradle/AgendaData/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/AgendaData/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.agendadata" >
+ package="com.example.android.wearable.agendadata" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -32,13 +32,13 @@
android:value="@integer/google_play_services_version" />
<service
- android:name="com.example.android.agendadata.HomeListenerService" >
+ android:name="com.example.android.wearable.agendadata.HomeListenerService" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
- <service android:name="com.example.android.agendadata.DeleteService"/>
+ <service android:name="com.example.android.wearable.agendadata.DeleteService"/>
<activity android:name="android.support.wearable.activity.ConfirmationActivity"/>
diff --git a/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/Constants.java b/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/Constants.java
new file mode 100644
index 0000000..176a21e
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/Constants.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.agendadata;
+
+/** Constants used in wearable app. */
+public final class Constants {
+
+ private Constants() {
+ }
+
+ public static final String TAG = "AgendaDataSample";
+
+ public static final String TITLE = "title";
+ public static final String DESCRIPTION = "description";
+ public static final String BEGIN = "begin";
+ public static final String END = "end";
+ public static final String ALL_DAY = "all_day";
+ public static final String PROFILE_PIC = "profile_pic";
+
+ public static final String EXTRA_SILENT = "silent";
+}
diff --git a/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/DeleteService.java b/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/DeleteService.java
new file mode 100644
index 0000000..86aafe0
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/DeleteService.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.agendadata;
+
+import static com.example.android.wearable.agendadata.Constants.TAG;
+import static com.example.android.wearable.agendadata.Constants.EXTRA_SILENT;
+
+import android.app.IntentService;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.wearable.activity.ConfirmationActivity;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.Wearable;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Handles "Delete" button on calendar event card.
+ */
+public class DeleteService extends IntentService implements GoogleApiClient.ConnectionCallbacks,
+ GoogleApiClient.OnConnectionFailedListener {
+
+ /* Timeout for making a connection to GoogleApiClient (in milliseconds) */
+ private static final long TIME_OUT = 100;
+
+ private GoogleApiClient mGoogleApiClient;
+
+ public DeleteService() {
+ super(DeleteService.class.getSimpleName());
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ mGoogleApiClient.blockingConnect(TIME_OUT, TimeUnit.MILLISECONDS);
+ Uri dataItemUri = intent.getData();
+ if (Log.isLoggable(TAG, Log.VERBOSE)) {
+ Log.v(TAG, "DeleteService.onHandleIntent=" + dataItemUri);
+ }
+ if (mGoogleApiClient.isConnected()) {
+ DataApi.DeleteDataItemsResult result = Wearable.DataApi
+ .deleteDataItems(mGoogleApiClient, dataItemUri).await();
+ if (result.getStatus().isSuccess() && !intent.getBooleanExtra(EXTRA_SILENT, false)) {
+ // Show the success animation on the watch unless Silent extra is true.
+ startConfirmationActivity(ConfirmationActivity.SUCCESS_ANIMATION,
+ getString(R.string.delete_successful));
+ } else {
+ if (Log.isLoggable(TAG, Log.VERBOSE)) {
+ Log.v(TAG, "DeleteService.onHandleIntent: Failed to delete dataItem:"
+ + dataItemUri);
+ }
+ // Show the failure animation on the watch unless Silent extra is true.
+ if (!intent.getBooleanExtra(EXTRA_SILENT, false)) {
+ startConfirmationActivity(ConfirmationActivity.FAILURE_ANIMATION,
+ getString(R.string.delete_unsuccessful));
+ }
+ }
+ } else {
+ Log.e(TAG, "Failed to delete data item: " + dataItemUri
+ + " - Client disconnected from Google Play Services");
+ // Show the failure animation on the watch unless Silent extra is true.
+ if (!intent.getBooleanExtra(EXTRA_SILENT, false)) {
+ startConfirmationActivity(ConfirmationActivity.FAILURE_ANIMATION,
+ getString(R.string.delete_unsuccessful));
+ }
+ }
+ mGoogleApiClient.disconnect();
+ }
+
+ private void startConfirmationActivity(int animationType, String message) {
+ Intent confirmationActivity = new Intent(this, ConfirmationActivity.class)
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION)
+ .putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, animationType)
+ .putExtra(ConfirmationActivity.EXTRA_MESSAGE, message);
+ startActivity(confirmationActivity);
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ }
+
+}
diff --git a/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/HomeListenerService.java b/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/HomeListenerService.java
new file mode 100644
index 0000000..ef47977
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/Wearable/src/main/java/com/example/android/wearable/agendadata/HomeListenerService.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.agendadata;
+
+import static com.example.android.wearable.agendadata.Constants.TAG;
+import static com.example.android.wearable.agendadata.Constants.EXTRA_SILENT;
+
+import static com.example.android.wearable.agendadata.Constants.ALL_DAY;
+import static com.example.android.wearable.agendadata.Constants.BEGIN;
+import static com.example.android.wearable.agendadata.Constants.DESCRIPTION;
+import static com.example.android.wearable.agendadata.Constants.END;
+import static com.example.android.wearable.agendadata.Constants.PROFILE_PIC;
+import static com.example.android.wearable.agendadata.Constants.TITLE;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.text.TextUtils;
+import android.text.format.DateFormat;
+import android.util.Log;
+
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.Asset;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.DataItem;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.DataMapItem;
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.Wearable;
+import com.google.android.gms.wearable.WearableListenerService;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Listens to DataItem events on the home device.
+ */
+public class HomeListenerService extends WearableListenerService {
+
+ private static final Map<Uri, Integer> sNotificationIdByDataItemUri =
+ new HashMap<Uri, Integer>();
+ private static int sNotificationId = 1;
+ private GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onDataChanged: " + dataEvents + " for " + getPackageName());
+ }
+ for (DataEvent event : dataEvents) {
+ if (event.getType() == DataEvent.TYPE_DELETED) {
+ deleteDataItem(event.getDataItem());
+ } else if (event.getType() == DataEvent.TYPE_CHANGED) {
+ UpdateNotificationForDataItem(event.getDataItem());
+ }
+ }
+ dataEvents.close();
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this.getApplicationContext())
+ .addApi(Wearable.API)
+ .build();
+ mGoogleApiClient.connect();
+ }
+
+ /**
+ * Posts a local notification to show calendar card.
+ */
+ private void UpdateNotificationForDataItem(DataItem dataItem) {
+ DataMapItem mapDataItem = DataMapItem.fromDataItem(dataItem);
+ DataMap data = mapDataItem.getDataMap();
+
+ String description = data.getString(DESCRIPTION);
+ if (TextUtils.isEmpty(description)) {
+ description = "";
+ } else {
+ // Add a space between the description and the time of the event.
+ description += " ";
+ }
+ String contentText;
+ if (data.getBoolean(ALL_DAY)) {
+ contentText = getString(R.string.desc_all_day, description);
+ } else {
+ String startTime = DateFormat.getTimeFormat(this).format(new Date(data.getLong(BEGIN)));
+ String endTime = DateFormat.getTimeFormat(this).format(new Date(data.getLong(END)));
+ contentText = getString(R.string.desc_time_period, description, startTime, endTime);
+ }
+
+ Intent deleteOperation = new Intent(this, DeleteService.class);
+ // Use a unique identifier for the delete action.
+ String deleteAction = "action_delete" + dataItem.getUri().toString() + sNotificationId;
+ deleteOperation.setAction(deleteAction);
+ deleteOperation.setData(dataItem.getUri());
+ PendingIntent deleteIntent = PendingIntent.getService(this, 0, deleteOperation,
+ PendingIntent.FLAG_ONE_SHOT);
+ PendingIntent silentDeleteIntent = PendingIntent.getService(this, 1,
+ deleteOperation.putExtra(EXTRA_SILENT, true), PendingIntent.FLAG_ONE_SHOT);
+
+ Notification.Builder notificationBuilder = new Notification.Builder(this)
+ .setContentTitle(data.getString(TITLE))
+ .setContentText(contentText)
+ .setSmallIcon(R.drawable.ic_launcher)
+ .addAction(R.drawable.ic_menu_delete, getText(R.string.delete), deleteIntent)
+ .setDeleteIntent(silentDeleteIntent) // Delete DataItem if notification dismissed.
+ .setLocalOnly(true)
+ .setPriority(Notification.PRIORITY_MIN);
+
+ // Set the event owner's profile picture as the notification background.
+ Asset asset = data.getAsset(PROFILE_PIC);
+ if (null != asset) {
+ if (mGoogleApiClient.isConnected()) {
+ DataApi.GetFdForAssetResult assetFdResult =
+ Wearable.DataApi.getFdForAsset(mGoogleApiClient, asset).await();
+ if (assetFdResult.getStatus().isSuccess()) {
+ Bitmap profilePic = BitmapFactory.decodeStream(assetFdResult.getInputStream());
+ notificationBuilder.extend(new Notification.WearableExtender()
+ .setBackground(profilePic));
+ } else if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "asset fetch failed with statusCode: "
+ + assetFdResult.getStatus().getStatusCode());
+ }
+ } else {
+ Log.e(TAG, "Failed to set notification background"
+ + " - Client disconnected from Google Play Services");
+ }
+ }
+ Notification card = notificationBuilder.build();
+
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(sNotificationId, card);
+
+ sNotificationIdByDataItemUri.put(dataItem.getUri(), sNotificationId++);
+ }
+
+ /**
+ * Deletes the calendar card associated with the data item.
+ */
+ private void deleteDataItem(DataItem dataItem) {
+ if (Log.isLoggable(TAG, Log.VERBOSE)) {
+ Log.v(TAG, "onDataItemDeleted:DataItem=" + dataItem.getUri());
+ }
+ Integer notificationId = sNotificationIdByDataItemUri.remove(dataItem.getUri());
+ if (notificationId != null) {
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(notificationId);
+ }
+ }
+
+ @Override
+ public void onMessageReceived(MessageEvent messageEvent) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onMessageReceived: " + messageEvent.getPath()
+ + " " + messageEvent.getData() + " for " + getPackageName());
+ }
+ }
+
+}
diff --git a/prebuilts/gradle/AgendaData/screenshots/companion_agenda_data.png b/prebuilts/gradle/AgendaData/screenshots/companion_agenda_data.png
new file mode 100644
index 0000000..c39503b
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/screenshots/companion_agenda_data.png
Binary files differ
diff --git a/prebuilts/gradle/AgendaData/screenshots/dummy_calendar_event.png b/prebuilts/gradle/AgendaData/screenshots/dummy_calendar_event.png
new file mode 100644
index 0000000..074c56b
--- /dev/null
+++ b/prebuilts/gradle/AgendaData/screenshots/dummy_calendar_event.png
Binary files differ
diff --git a/prebuilts/gradle/AgendaData/settings.gradle b/prebuilts/gradle/AgendaData/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/AgendaData/settings.gradle
+++ b/prebuilts/gradle/AgendaData/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/BasicImmersiveMode/Application/build.gradle b/prebuilts/gradle/BasicImmersiveMode/Application/build.gradle
index 008a16f..1617224 100644
--- a/prebuilts/gradle/BasicImmersiveMode/Application/build.gradle
+++ b/prebuilts/gradle/BasicImmersiveMode/Application/build.gradle
@@ -28,12 +28,12 @@
'template'] // boilerplate code that is generated by the sample template process
android {
- compileSdkVersion 19
+ compileSdkVersion 21
buildToolsVersion "21.0.0"
defaultConfig {
minSdkVersion 19
- targetSdkVersion 19
+ targetSdkVersion 21
}
sourceSets {
diff --git a/prebuilts/gradle/BasicTransition/Application/build.gradle b/prebuilts/gradle/BasicTransition/Application/build.gradle
index 008a16f..1617224 100644
--- a/prebuilts/gradle/BasicTransition/Application/build.gradle
+++ b/prebuilts/gradle/BasicTransition/Application/build.gradle
@@ -28,12 +28,12 @@
'template'] // boilerplate code that is generated by the sample template process
android {
- compileSdkVersion 19
+ compileSdkVersion 21
buildToolsVersion "21.0.0"
defaultConfig {
minSdkVersion 19
- targetSdkVersion 19
+ targetSdkVersion 21
}
sourceSets {
diff --git a/prebuilts/gradle/CustomChoiceList/Application/build.gradle b/prebuilts/gradle/CustomChoiceList/Application/build.gradle
index 7c0fe06..bd1120c 100644
--- a/prebuilts/gradle/CustomChoiceList/Application/build.gradle
+++ b/prebuilts/gradle/CustomChoiceList/Application/build.gradle
@@ -30,7 +30,7 @@
buildToolsVersion "21.0.0"
defaultConfig {
- minSdkVersion 3
+ minSdkVersion 4
targetSdkVersion 21
}
diff --git a/prebuilts/gradle/DataLayer/Application/build.gradle b/prebuilts/gradle/DataLayer/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/DataLayer/Application/build.gradle
+++ b/prebuilts/gradle/DataLayer/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/DataLayer/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/DataLayer/Application/src/main/AndroidManifest.xml
index f382b25..821bc11 100644
--- a/prebuilts/gradle/DataLayer/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/DataLayer/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.datalayer" >
+ package="com.example.android.wearable.datalayer" >
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
diff --git a/prebuilts/gradle/DataLayer/Application/src/main/java/com/example/android/wearable/datalayer/MainActivity.java b/prebuilts/gradle/DataLayer/Application/src/main/java/com/example/android/wearable/datalayer/MainActivity.java
new file mode 100644
index 0000000..23bc696
--- /dev/null
+++ b/prebuilts/gradle/DataLayer/Application/src/main/java/com/example/android/wearable/datalayer/MainActivity.java
@@ -0,0 +1,484 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.datalayer;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentSender;
+import android.content.pm.PackageManager;
+import android.graphics.Bitmap;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Handler;
+import android.provider.MediaStore;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.Button;
+import android.widget.ImageView;
+import android.widget.ListView;
+import android.widget.TextView;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
+import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
+import com.google.android.gms.common.data.FreezableUtils;
+import com.google.android.gms.wearable.Asset;
+import com.google.android.gms.wearable.DataApi.DataItemResult;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.MessageApi.SendMessageResult;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.MessageApi;
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.NodeApi;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.PutDataRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Receives its own events using a listener API designed for foreground activities. Updates a data
+ * item every second while it is open. Also allows user to take a photo and send that as an asset to
+ * the paired wearable.
+ */
+public class MainActivity extends Activity implements DataApi.DataListener,
+ MessageApi.MessageListener, NodeApi.NodeListener, ConnectionCallbacks,
+ OnConnectionFailedListener {
+
+ private static final String TAG = "MainActivity";
+
+ /** Request code for launching the Intent to resolve Google Play services errors. */
+ private static final int REQUEST_RESOLVE_ERROR = 1000;
+
+ private static final String START_ACTIVITY_PATH = "/start-activity";
+ private static final String COUNT_PATH = "/count";
+ private static final String IMAGE_PATH = "/image";
+ private static final String IMAGE_KEY = "photo";
+ private static final String COUNT_KEY = "count";
+
+ private GoogleApiClient mGoogleApiClient;
+ private boolean mResolvingError = false;
+ private boolean mCameraSupported = false;
+
+ private ListView mDataItemList;
+ private Button mTakePhotoBtn;
+ private Button mSendPhotoBtn;
+ private ImageView mThumbView;
+ private Bitmap mImageBitmap;
+ private View mStartActivityBtn;
+
+ private DataItemAdapter mDataItemListAdapter;
+ private Handler mHandler;
+
+ // Send DataItems.
+ private ScheduledExecutorService mGeneratorExecutor;
+ private ScheduledFuture<?> mDataItemGeneratorFuture;
+
+ static final int REQUEST_IMAGE_CAPTURE = 1;
+
+ @Override
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ mHandler = new Handler();
+ LOGD(TAG, "onCreate");
+ mCameraSupported = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
+ setContentView(R.layout.main_activity);
+ setupViews();
+
+ // Stores DataItems received by the local broadcaster or from the paired watch.
+ mDataItemListAdapter = new DataItemAdapter(this, android.R.layout.simple_list_item_1);
+ mDataItemList.setAdapter(mDataItemListAdapter);
+
+ mGeneratorExecutor = new ScheduledThreadPoolExecutor(1);
+
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
+ Bundle extras = data.getExtras();
+ mImageBitmap = (Bitmap) extras.get("data");
+ mThumbView.setImageBitmap(mImageBitmap);
+ }
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ if (!mResolvingError) {
+ mGoogleApiClient.connect();
+ }
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ mDataItemGeneratorFuture = mGeneratorExecutor.scheduleWithFixedDelay(
+ new DataItemGenerator(), 1, 5, TimeUnit.SECONDS);
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ mDataItemGeneratorFuture.cancel(true /* mayInterruptIfRunning */);
+ }
+
+ @Override
+ protected void onStop() {
+ if (!mResolvingError) {
+ Wearable.DataApi.removeListener(mGoogleApiClient, this);
+ Wearable.MessageApi.removeListener(mGoogleApiClient, this);
+ Wearable.NodeApi.removeListener(mGoogleApiClient, this);
+ mGoogleApiClient.disconnect();
+ }
+ super.onStop();
+ }
+
+ @Override //ConnectionCallbacks
+ public void onConnected(Bundle connectionHint) {
+ LOGD(TAG, "Google API Client was connected");
+ mResolvingError = false;
+ mStartActivityBtn.setEnabled(true);
+ mSendPhotoBtn.setEnabled(mCameraSupported);
+ Wearable.DataApi.addListener(mGoogleApiClient, this);
+ Wearable.MessageApi.addListener(mGoogleApiClient, this);
+ Wearable.NodeApi.addListener(mGoogleApiClient, this);
+ }
+
+ @Override //ConnectionCallbacks
+ public void onConnectionSuspended(int cause) {
+ LOGD(TAG, "Connection to Google API client was suspended");
+ mStartActivityBtn.setEnabled(false);
+ mSendPhotoBtn.setEnabled(false);
+ }
+
+ @Override //OnConnectionFailedListener
+ public void onConnectionFailed(ConnectionResult result) {
+ if (mResolvingError) {
+ // Already attempting to resolve an error.
+ return;
+ } else if (result.hasResolution()) {
+ try {
+ mResolvingError = true;
+ result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
+ } catch (IntentSender.SendIntentException e) {
+ // There was an error with the resolution intent. Try again.
+ mGoogleApiClient.connect();
+ }
+ } else {
+ Log.e(TAG, "Connection to Google API client has failed");
+ mResolvingError = false;
+ mStartActivityBtn.setEnabled(false);
+ mSendPhotoBtn.setEnabled(false);
+ Wearable.DataApi.removeListener(mGoogleApiClient, this);
+ Wearable.MessageApi.removeListener(mGoogleApiClient, this);
+ Wearable.NodeApi.removeListener(mGoogleApiClient, this);
+ }
+ }
+
+ @Override //DataListener
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ LOGD(TAG, "onDataChanged: " + dataEvents);
+ final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
+ dataEvents.close();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ for (DataEvent event : events) {
+ if (event.getType() == DataEvent.TYPE_CHANGED) {
+ mDataItemListAdapter.add(
+ new Event("DataItem Changed", event.getDataItem().toString()));
+ } else if (event.getType() == DataEvent.TYPE_DELETED) {
+ mDataItemListAdapter.add(
+ new Event("DataItem Deleted", event.getDataItem().toString()));
+ }
+ }
+ }
+ });
+ }
+
+ @Override //MessageListener
+ public void onMessageReceived(final MessageEvent messageEvent) {
+ LOGD(TAG, "onMessageReceived() A message from watch was received:" + messageEvent
+ .getRequestId() + " " + messageEvent.getPath());
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mDataItemListAdapter.add(new Event("Message from watch", messageEvent.toString()));
+ }
+ });
+
+ }
+
+ @Override //NodeListener
+ public void onPeerConnected(final Node peer) {
+ LOGD(TAG, "onPeerConnected: " + peer);
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mDataItemListAdapter.add(new Event("Connected", peer.toString()));
+ }
+ });
+
+ }
+
+ @Override //NodeListener
+ public void onPeerDisconnected(final Node peer) {
+ LOGD(TAG, "onPeerDisconnected: " + peer);
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mDataItemListAdapter.add(new Event("Disconnected", peer.toString()));
+ }
+ });
+ }
+
+ /**
+ * A View Adapter for presenting the Event objects in a list
+ */
+ private static class DataItemAdapter extends ArrayAdapter<Event> {
+
+ private final Context mContext;
+
+ public DataItemAdapter(Context context, int unusedResource) {
+ super(context, unusedResource);
+ mContext = context;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ ViewHolder holder;
+ if (convertView == null) {
+ holder = new ViewHolder();
+ LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
+ Context.LAYOUT_INFLATER_SERVICE);
+ convertView = inflater.inflate(android.R.layout.two_line_list_item, null);
+ convertView.setTag(holder);
+ holder.text1 = (TextView) convertView.findViewById(android.R.id.text1);
+ holder.text2 = (TextView) convertView.findViewById(android.R.id.text2);
+ } else {
+ holder = (ViewHolder) convertView.getTag();
+ }
+ Event event = getItem(position);
+ holder.text1.setText(event.title);
+ holder.text2.setText(event.text);
+ return convertView;
+ }
+
+ private class ViewHolder {
+
+ TextView text1;
+ TextView text2;
+ }
+ }
+
+ private class Event {
+
+ String title;
+ String text;
+
+ public Event(String title, String text) {
+ this.title = title;
+ this.text = text;
+ }
+ }
+
+ private Collection<String> getNodes() {
+ HashSet<String> results = new HashSet<String>();
+ NodeApi.GetConnectedNodesResult nodes =
+ Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).await();
+
+ for (Node node : nodes.getNodes()) {
+ results.add(node.getId());
+ }
+
+ return results;
+ }
+
+ private void sendStartActivityMessage(String node) {
+ Wearable.MessageApi.sendMessage(
+ mGoogleApiClient, node, START_ACTIVITY_PATH, new byte[0]).setResultCallback(
+ new ResultCallback<SendMessageResult>() {
+ @Override
+ public void onResult(SendMessageResult sendMessageResult) {
+ if (!sendMessageResult.getStatus().isSuccess()) {
+ Log.e(TAG, "Failed to send message with status code: "
+ + sendMessageResult.getStatus().getStatusCode());
+ }
+ }
+ }
+ );
+ }
+
+ private class StartWearableActivityTask extends AsyncTask<Void, Void, Void> {
+
+ @Override
+ protected Void doInBackground(Void... args) {
+ Collection<String> nodes = getNodes();
+ for (String node : nodes) {
+ sendStartActivityMessage(node);
+ }
+ return null;
+ }
+ }
+
+ /** Sends an RPC to start a fullscreen Activity on the wearable. */
+ public void onStartWearableActivityClick(View view) {
+ LOGD(TAG, "Generating RPC");
+
+ // Trigger an AsyncTask that will query for a list of connected nodes and send a
+ // "start-activity" message to each connected node.
+ new StartWearableActivityTask().execute();
+ }
+
+ /** Generates a DataItem based on an incrementing count. */
+ private class DataItemGenerator implements Runnable {
+
+ private int count = 0;
+
+ @Override
+ public void run() {
+ PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(COUNT_PATH);
+ putDataMapRequest.getDataMap().putInt(COUNT_KEY, count++);
+ PutDataRequest request = putDataMapRequest.asPutDataRequest();
+
+ LOGD(TAG, "Generating DataItem: " + request);
+ if (!mGoogleApiClient.isConnected()) {
+ return;
+ }
+ Wearable.DataApi.putDataItem(mGoogleApiClient, request)
+ .setResultCallback(new ResultCallback<DataItemResult>() {
+ @Override
+ public void onResult(DataItemResult dataItemResult) {
+ if (!dataItemResult.getStatus().isSuccess()) {
+ Log.e(TAG, "ERROR: failed to putDataItem, status code: "
+ + dataItemResult.getStatus().getStatusCode());
+ }
+ }
+ });
+ }
+ }
+
+ /**
+ * Dispatches an {@link android.content.Intent} to take a photo. Result will be returned back
+ * in onActivityResult().
+ */
+ private void dispatchTakePictureIntent() {
+ Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+ if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
+ startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
+ }
+ }
+
+ /**
+ * Builds an {@link com.google.android.gms.wearable.Asset} from a bitmap. The image that we get
+ * back from the camera in "data" is a thumbnail size. Typically, your image should not exceed
+ * 320x320 and if you want to have zoom and parallax effect in your app, limit the size of your
+ * image to 640x400. Resize your image before transferring to your wearable device.
+ */
+ private static Asset toAsset(Bitmap bitmap) {
+ ByteArrayOutputStream byteStream = null;
+ try {
+ byteStream = new ByteArrayOutputStream();
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteStream);
+ return Asset.createFromBytes(byteStream.toByteArray());
+ } finally {
+ if (null != byteStream) {
+ try {
+ byteStream.close();
+ } catch (IOException e) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ /**
+ * Sends the asset that was created form the photo we took by adding it to the Data Item store.
+ */
+ private void sendPhoto(Asset asset) {
+ PutDataMapRequest dataMap = PutDataMapRequest.create(IMAGE_PATH);
+ dataMap.getDataMap().putAsset(IMAGE_KEY, asset);
+ dataMap.getDataMap().putLong("time", new Date().getTime());
+ PutDataRequest request = dataMap.asPutDataRequest();
+ Wearable.DataApi.putDataItem(mGoogleApiClient, request)
+ .setResultCallback(new ResultCallback<DataItemResult>() {
+ @Override
+ public void onResult(DataItemResult dataItemResult) {
+ LOGD(TAG, "Sending image was successful: " + dataItemResult.getStatus()
+ .isSuccess());
+ }
+ });
+
+ }
+
+ public void onTakePhotoClick(View view) {
+ dispatchTakePictureIntent();
+ }
+
+ public void onSendPhotoClick(View view) {
+ if (null != mImageBitmap && mGoogleApiClient.isConnected()) {
+ sendPhoto(toAsset(mImageBitmap));
+ }
+ }
+
+ /**
+ * Sets up UI components and their callback handlers.
+ */
+ private void setupViews() {
+ mTakePhotoBtn = (Button) findViewById(R.id.takePhoto);
+ mSendPhotoBtn = (Button) findViewById(R.id.sendPhoto);
+
+ // Shows the image received from the handset
+ mThumbView = (ImageView) findViewById(R.id.imageView);
+ mDataItemList = (ListView) findViewById(R.id.data_item_list);
+
+ mStartActivityBtn = findViewById(R.id.start_wearable_activity);
+ }
+
+ /**
+ * As simple wrapper around Log.d
+ */
+ private static void LOGD(final String tag, String message) {
+ if (Log.isLoggable(tag, Log.DEBUG)) {
+ Log.d(tag, message);
+ }
+ }
+
+}
diff --git a/prebuilts/gradle/DataLayer/Wearable/build.gradle b/prebuilts/gradle/DataLayer/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/DataLayer/Wearable/build.gradle
+++ b/prebuilts/gradle/DataLayer/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/DataLayer/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/DataLayer/Wearable/src/main/AndroidManifest.xml
index 7bde39a..38c0798 100644
--- a/prebuilts/gradle/DataLayer/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/DataLayer/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.datalayer" >
+ package="com.example.android.wearable.datalayer" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -47,7 +47,7 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
- <action android:name="com.example.android.datalayer.EXAMPLE"/>
+ <action android:name="com.example.android.wearable.datalayer.EXAMPLE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
diff --git a/prebuilts/gradle/DataLayer/Wearable/src/main/java/com/example/android/wearable/datalayer/DataLayerListenerService.java b/prebuilts/gradle/DataLayer/Wearable/src/main/java/com/example/android/wearable/datalayer/DataLayerListenerService.java
new file mode 100644
index 0000000..64abaf5
--- /dev/null
+++ b/prebuilts/gradle/DataLayer/Wearable/src/main/java/com/example/android/wearable/datalayer/DataLayerListenerService.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.datalayer;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.data.FreezableUtils;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.Wearable;
+import com.google.android.gms.wearable.WearableListenerService;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Listens to DataItems and Messages from the local node.
+ */
+public class DataLayerListenerService extends WearableListenerService {
+
+ private static final String TAG = "DataLayerListenerServic";
+
+ private static final String START_ACTIVITY_PATH = "/start-activity";
+ private static final String DATA_ITEM_RECEIVED_PATH = "/data-item-received";
+ public static final String COUNT_PATH = "/count";
+ public static final String IMAGE_PATH = "/image";
+ public static final String IMAGE_KEY = "photo";
+ private static final String COUNT_KEY = "count";
+ private static final int MAX_LOG_TAG_LENGTH = 23;
+ GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .build();
+ mGoogleApiClient.connect();
+ }
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ LOGD(TAG, "onDataChanged: " + dataEvents);
+ final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
+ dataEvents.close();
+ if(!mGoogleApiClient.isConnected()) {
+ ConnectionResult connectionResult = mGoogleApiClient
+ .blockingConnect(30, TimeUnit.SECONDS);
+ if (!connectionResult.isSuccess()) {
+ Log.e(TAG, "DataLayerListenerService failed to connect to GoogleApiClient.");
+ return;
+ }
+ }
+
+ // Loop through the events and send a message back to the node that created the data item.
+ for (DataEvent event : events) {
+ Uri uri = event.getDataItem().getUri();
+ String path = uri.getPath();
+ if (COUNT_PATH.equals(path)) {
+ // Get the node id of the node that created the data item from the host portion of
+ // the uri.
+ String nodeId = uri.getHost();
+ // Set the data of the message to be the bytes of the Uri.
+ byte[] payload = uri.toString().getBytes();
+
+ // Send the rpc
+ Wearable.MessageApi.sendMessage(mGoogleApiClient, nodeId, DATA_ITEM_RECEIVED_PATH,
+ payload);
+ }
+ }
+ }
+
+ @Override
+ public void onMessageReceived(MessageEvent messageEvent) {
+ LOGD(TAG, "onMessageReceived: " + messageEvent);
+
+ // Check to see if the message is to start an activity
+ if (messageEvent.getPath().equals(START_ACTIVITY_PATH)) {
+ Intent startIntent = new Intent(this, MainActivity.class);
+ startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ startActivity(startIntent);
+ }
+ }
+
+ @Override
+ public void onPeerConnected(Node peer) {
+ LOGD(TAG, "onPeerConnected: " + peer);
+ }
+
+ @Override
+ public void onPeerDisconnected(Node peer) {
+ LOGD(TAG, "onPeerDisconnected: " + peer);
+ }
+
+ public static void LOGD(final String tag, String message) {
+ if (Log.isLoggable(tag, Log.DEBUG)) {
+ Log.d(tag, message);
+ }
+ }
+}
diff --git a/prebuilts/gradle/DataLayer/Wearable/src/main/java/com/example/android/wearable/datalayer/MainActivity.java b/prebuilts/gradle/DataLayer/Wearable/src/main/java/com/example/android/wearable/datalayer/MainActivity.java
new file mode 100644
index 0000000..b312135
--- /dev/null
+++ b/prebuilts/gradle/DataLayer/Wearable/src/main/java/com/example/android/wearable/datalayer/MainActivity.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.datalayer;
+
+import static com.example.android.wearable.datalayer.DataLayerListenerService.LOGD;
+
+import android.app.Activity;
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.drawable.BitmapDrawable;
+import android.os.Bundle;
+import android.os.Handler;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.WindowManager;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import android.widget.TextView;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
+import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
+import com.google.android.gms.common.data.FreezableUtils;
+import com.google.android.gms.wearable.Asset;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.DataMapItem;
+import com.google.android.gms.wearable.MessageApi;
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.NodeApi;
+import com.google.android.gms.wearable.Wearable;
+
+import java.io.InputStream;
+import java.util.List;
+
+/**
+ * Shows events and photo from the Wearable APIs.
+ */
+public class MainActivity extends Activity implements ConnectionCallbacks,
+ OnConnectionFailedListener, DataApi.DataListener, MessageApi.MessageListener,
+ NodeApi.NodeListener {
+
+ private static final String TAG = "MainActivity";
+
+ private GoogleApiClient mGoogleApiClient;
+ private ListView mDataItemList;
+ private TextView mIntroText;
+ private DataItemAdapter mDataItemListAdapter;
+ private View mLayout;
+ private Handler mHandler;
+
+ @Override
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ mHandler = new Handler();
+ LOGD(TAG, "onCreate");
+ setContentView(R.layout.main_activity);
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ mDataItemList = (ListView) findViewById(R.id.dataItem_list);
+ mIntroText = (TextView) findViewById(R.id.intro);
+ mLayout = findViewById(R.id.layout);
+
+ // Stores data events received by the local broadcaster.
+ mDataItemListAdapter = new DataItemAdapter(this, android.R.layout.simple_list_item_1);
+ mDataItemList.setAdapter(mDataItemListAdapter);
+
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ mGoogleApiClient.connect();
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ Wearable.DataApi.removeListener(mGoogleApiClient, this);
+ Wearable.MessageApi.removeListener(mGoogleApiClient, this);
+ Wearable.NodeApi.removeListener(mGoogleApiClient, this);
+ mGoogleApiClient.disconnect();
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ LOGD(TAG, "onConnected(): Successfully connected to Google API client");
+ Wearable.DataApi.addListener(mGoogleApiClient, this);
+ Wearable.MessageApi.addListener(mGoogleApiClient, this);
+ Wearable.NodeApi.addListener(mGoogleApiClient, this);
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ LOGD(TAG, "onConnectionSuspended(): Connection to Google API client was suspended");
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ Log.e(TAG, "onConnectionFailed(): Failed to connect, with result: " + result);
+ }
+
+ private void generateEvent(final String title, final String text) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ mIntroText.setVisibility(View.INVISIBLE);
+ mDataItemListAdapter.add(new Event(title, text));
+ }
+ });
+ }
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ LOGD(TAG, "onDataChanged(): " + dataEvents);
+
+ final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
+ dataEvents.close();
+ for (DataEvent event : events) {
+ if (event.getType() == DataEvent.TYPE_CHANGED) {
+ String path = event.getDataItem().getUri().getPath();
+ if (DataLayerListenerService.IMAGE_PATH.equals(path)) {
+ DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
+ Asset photo = dataMapItem.getDataMap()
+ .getAsset(DataLayerListenerService.IMAGE_KEY);
+ final Bitmap bitmap = loadBitmapFromAsset(mGoogleApiClient, photo);
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ Log.d(TAG, "Setting background image..");
+ mLayout.setBackground(new BitmapDrawable(getResources(), bitmap));
+ }
+ });
+
+ } else if (DataLayerListenerService.COUNT_PATH.equals(path)) {
+ LOGD(TAG, "Data Changed for COUNT_PATH");
+ generateEvent("DataItem Changed", event.getDataItem().toString());
+ } else {
+ LOGD(TAG, "Unrecognized path: " + path);
+ }
+
+ } else if (event.getType() == DataEvent.TYPE_DELETED) {
+ generateEvent("DataItem Deleted", event.getDataItem().toString());
+ } else {
+ generateEvent("Unknown data event type", "Type = " + event.getType());
+ }
+ }
+ }
+
+ /**
+ * Extracts {@link android.graphics.Bitmap} data from the
+ * {@link com.google.android.gms.wearable.Asset}
+ */
+ private Bitmap loadBitmapFromAsset(GoogleApiClient apiClient, Asset asset) {
+ if (asset == null) {
+ throw new IllegalArgumentException("Asset must be non-null");
+ }
+
+ InputStream assetInputStream = Wearable.DataApi.getFdForAsset(
+ apiClient, asset).await().getInputStream();
+
+ if (assetInputStream == null) {
+ Log.w(TAG, "Requested an unknown Asset.");
+ return null;
+ }
+ return BitmapFactory.decodeStream(assetInputStream);
+ }
+
+ @Override
+ public void onMessageReceived(MessageEvent event) {
+ LOGD(TAG, "onMessageReceived: " + event);
+ generateEvent("Message", event.toString());
+ }
+
+ @Override
+ public void onPeerConnected(Node node) {
+ generateEvent("Node Connected", node.getId());
+ }
+
+ @Override
+ public void onPeerDisconnected(Node node) {
+ generateEvent("Node Disconnected", node.getId());
+ }
+
+ private static class DataItemAdapter extends ArrayAdapter<Event> {
+
+ private final Context mContext;
+
+ public DataItemAdapter(Context context, int unusedResource) {
+ super(context, unusedResource);
+ mContext = context;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ ViewHolder holder;
+ if (convertView == null) {
+ holder = new ViewHolder();
+ LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(
+ Context.LAYOUT_INFLATER_SERVICE);
+ convertView = inflater.inflate(android.R.layout.two_line_list_item, null);
+ convertView.setTag(holder);
+ holder.text1 = (TextView) convertView.findViewById(android.R.id.text1);
+ holder.text2 = (TextView) convertView.findViewById(android.R.id.text2);
+ } else {
+ holder = (ViewHolder) convertView.getTag();
+ }
+ Event event = getItem(position);
+ holder.text1.setText(event.title);
+ holder.text2.setText(event.text);
+ return convertView;
+ }
+
+ private class ViewHolder {
+
+ TextView text1;
+ TextView text2;
+ }
+ }
+
+ private class Event {
+
+ String title;
+ String text;
+
+ public Event(String title, String text) {
+ this.title = title;
+ this.text = text;
+ }
+ }
+}
diff --git a/prebuilts/gradle/DataLayer/screenshots/phone_image.png b/prebuilts/gradle/DataLayer/screenshots/phone_image.png
new file mode 100644
index 0000000..e045b65
--- /dev/null
+++ b/prebuilts/gradle/DataLayer/screenshots/phone_image.png
Binary files differ
diff --git a/prebuilts/gradle/DataLayer/screenshots/wearable_background_image.png b/prebuilts/gradle/DataLayer/screenshots/wearable_background_image.png
new file mode 100644
index 0000000..7826180
--- /dev/null
+++ b/prebuilts/gradle/DataLayer/screenshots/wearable_background_image.png
Binary files differ
diff --git a/prebuilts/gradle/DataLayer/settings.gradle b/prebuilts/gradle/DataLayer/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/DataLayer/settings.gradle
+++ b/prebuilts/gradle/DataLayer/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/DelayedConfirmation/Application/build.gradle b/prebuilts/gradle/DelayedConfirmation/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/DelayedConfirmation/Application/build.gradle
+++ b/prebuilts/gradle/DelayedConfirmation/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/DelayedConfirmation/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/DelayedConfirmation/Application/src/main/AndroidManifest.xml
index 115ebec..20b7aab 100644
--- a/prebuilts/gradle/DelayedConfirmation/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/DelayedConfirmation/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.delayedconfirmation" >
+ package="com.example.android.wearable.delayedconfirmation" >
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application
android:allowBackup="true"
diff --git a/prebuilts/gradle/DelayedConfirmation/Application/src/main/java/com/example/android/wearable/delayedconfirmation/MainActivity.java b/prebuilts/gradle/DelayedConfirmation/Application/src/main/java/com/example/android/wearable/delayedconfirmation/MainActivity.java
new file mode 100644
index 0000000..3ffda53
--- /dev/null
+++ b/prebuilts/gradle/DelayedConfirmation/Application/src/main/java/com/example/android/wearable/delayedconfirmation/MainActivity.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.delayedconfirmation;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.Toast;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.wearable.MessageApi;
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.NodeApi;
+import com.google.android.gms.wearable.Wearable;
+
+/**
+ * Has a single button, used to start the Wearable MainActivity.
+ */
+public class MainActivity extends Activity implements MessageApi.MessageListener,
+ GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String TAG = "DelayedConfirmation";
+ private static final String START_ACTIVITY_PATH = "/start-activity";
+ private static final String TIMER_SELECTED_PATH = "/timer_selected";
+ private static final String TIMER_FINISHED_PATH = "/timer_finished";
+ private GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ setContentView(R.layout.main_activity);
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (!mGoogleApiClient.isConnected()) {
+ mGoogleApiClient.connect();
+ }
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (mGoogleApiClient.isConnected()) {
+ mGoogleApiClient.disconnect();
+ }
+ super.onDestroy();
+ }
+
+ @Override
+ public void onConnected(Bundle bundle) {
+ Wearable.MessageApi.addListener(mGoogleApiClient, this);
+ }
+
+ @Override
+ public void onConnectionSuspended(int i) {
+ Wearable.MessageApi.removeListener(mGoogleApiClient, this);
+ }
+
+ @Override
+ public void onMessageReceived(final MessageEvent messageEvent) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ if (messageEvent.getPath().equals(TIMER_SELECTED_PATH)) {
+ Toast.makeText(getApplicationContext(), R.string.toast_timer_selected,
+ Toast.LENGTH_SHORT).show();
+ } else if (messageEvent.getPath().equals(TIMER_FINISHED_PATH)) {
+ Toast.makeText(getApplicationContext(), R.string.toast_timer_finished,
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+ });
+
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult connectionResult) {
+ Log.e(TAG, "Failed to connect to Google Api Client with error code "
+ + connectionResult.getErrorCode());
+ }
+
+ /**
+ * Sends a message to Wearable MainActivity when button is pressed.
+ */
+ public void onStartWearableActivityClick(View view) {
+ Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(
+ new ResultCallback<NodeApi.GetConnectedNodesResult>() {
+ @Override
+ public void onResult(NodeApi.GetConnectedNodesResult getConnectedNodesResult) {
+ for (final Node node : getConnectedNodesResult.getNodes()) {
+ Wearable.MessageApi.sendMessage(
+ mGoogleApiClient, node.getId(), START_ACTIVITY_PATH, new byte[0])
+ .setResultCallback(getSendMessageResultCallback());
+ }
+ }
+ });
+ }
+
+ private ResultCallback<MessageApi.SendMessageResult> getSendMessageResultCallback() {
+ return new ResultCallback<MessageApi.SendMessageResult>() {
+ @Override
+ public void onResult(MessageApi.SendMessageResult sendMessageResult) {
+ if (!sendMessageResult.getStatus().isSuccess()) {
+ Log.e(TAG, "Failed to connect to Google Api Client with status "
+ + sendMessageResult.getStatus());
+ }
+ }
+ };
+ }
+}
diff --git a/prebuilts/gradle/DelayedConfirmation/Wearable/build.gradle b/prebuilts/gradle/DelayedConfirmation/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/DelayedConfirmation/Wearable/build.gradle
+++ b/prebuilts/gradle/DelayedConfirmation/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/AndroidManifest.xml
index a220008..b73af62 100644
--- a/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.delayedconfirmation" >
+ package="com.example.android.wearable.delayedconfirmation" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
diff --git a/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/java/com/example/android/wearable/delayedconfirmation/MainActivity.java b/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/java/com/example/android/wearable/delayedconfirmation/MainActivity.java
new file mode 100644
index 0000000..f9b126d
--- /dev/null
+++ b/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/java/com/example/android/wearable/delayedconfirmation/MainActivity.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.delayedconfirmation;
+
+import android.app.Activity;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.os.Bundle;
+import android.support.wearable.view.DelayedConfirmationView;
+import android.util.Log;
+import android.view.View;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.wearable.MessageApi;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.NodeApi;
+import com.google.android.gms.wearable.Wearable;
+
+
+public class MainActivity extends Activity implements
+ DelayedConfirmationView.DelayedConfirmationListener,
+ GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String TAG = "DelayedConfirmation";
+ private static final int NUM_SECONDS = 5;
+
+ private static final String TIMER_SELECTED_PATH = "/timer_selected";
+ private static final String TIMER_FINISHED_PATH = "/timer_finished";
+
+ private DelayedConfirmationView delayedConfirmationView;
+ private GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ setContentView(R.layout.main_activity);
+ delayedConfirmationView = (DelayedConfirmationView) findViewById(R.id.delayed_confirmation);
+ delayedConfirmationView.setTotalTimeMs(NUM_SECONDS * 1000);
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (!mGoogleApiClient.isConnected()) {
+ mGoogleApiClient.connect();
+ }
+ }
+
+ @Override
+ protected void onDestroy() {
+ if (mGoogleApiClient.isConnected()) {
+ mGoogleApiClient.disconnect();
+ }
+ super.onDestroy();
+ }
+
+ /**
+ * Starts the DelayedConfirmationView when user presses "Start Timer" button.
+ */
+ public void onStartTimer(View view) {
+ delayedConfirmationView.start();
+ delayedConfirmationView.setListener(this);
+ }
+
+ @Override
+ public void onTimerSelected(View v) {
+ v.setPressed(true);
+ Notification notification = new Notification.Builder(this)
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setContentTitle(getString(R.string.notification_title))
+ .setContentText(getString(R.string.notification_timer_selected))
+ .build();
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(0, notification);
+ sendMessageToCompanion(TIMER_SELECTED_PATH);
+ // Prevent onTimerFinished from being heard.
+ ((DelayedConfirmationView) v).setListener(null);
+ finish();
+ }
+
+ @Override
+ public void onTimerFinished(View v) {
+ Notification notification = new Notification.Builder(this)
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setContentTitle(getString(R.string.notification_title))
+ .setContentText(getString(R.string.notification_timer_finished))
+ .build();
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(0, notification);
+ sendMessageToCompanion(TIMER_FINISHED_PATH);
+ finish();
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult connectionResult) {
+ Log.e(TAG, "Failed to connect to Google Api Client");
+ }
+
+ private void sendMessageToCompanion(final String path) {
+ Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(
+ new ResultCallback<NodeApi.GetConnectedNodesResult>() {
+ @Override
+ public void onResult(NodeApi.GetConnectedNodesResult getConnectedNodesResult) {
+ for (final Node node : getConnectedNodesResult.getNodes()) {
+ Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path,
+ new byte[0]).setResultCallback(getSendMessageResultCallback());
+ }
+ }
+ }
+ );
+
+ }
+
+ private ResultCallback<MessageApi.SendMessageResult> getSendMessageResultCallback() {
+ return new ResultCallback<MessageApi.SendMessageResult>() {
+ @Override
+ public void onResult(MessageApi.SendMessageResult sendMessageResult) {
+ if (!sendMessageResult.getStatus().isSuccess()) {
+ Log.e(TAG, "Failed to connect to Google Api Client with status "
+ + sendMessageResult.getStatus());
+ }
+ }
+ };
+ }
+}
diff --git a/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/java/com/example/android/wearable/delayedconfirmation/WearableMessageListenerService.java b/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/java/com/example/android/wearable/delayedconfirmation/WearableMessageListenerService.java
new file mode 100644
index 0000000..bb2ec91
--- /dev/null
+++ b/prebuilts/gradle/DelayedConfirmation/Wearable/src/main/java/com/example/android/wearable/delayedconfirmation/WearableMessageListenerService.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.delayedconfirmation;
+
+import android.content.Intent;
+
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.WearableListenerService;
+
+/**
+ * Listens for a message telling it to start the Wearable MainActivity.
+ */
+public class WearableMessageListenerService extends WearableListenerService {
+ private static final String START_ACTIVITY_PATH = "/start-activity";
+
+ @Override
+ public void onMessageReceived(MessageEvent event) {
+ if (event.getPath().equals(START_ACTIVITY_PATH)) {
+ Intent startIntent = new Intent(this, MainActivity.class);
+ startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ startActivity(startIntent);
+ }
+ }
+}
diff --git a/prebuilts/gradle/DelayedConfirmation/screenshots/companion_delayed_confirmation.png b/prebuilts/gradle/DelayedConfirmation/screenshots/companion_delayed_confirmation.png
new file mode 100644
index 0000000..b1b61a4
--- /dev/null
+++ b/prebuilts/gradle/DelayedConfirmation/screenshots/companion_delayed_confirmation.png
Binary files differ
diff --git a/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_box_inset_all.png b/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_box_inset_all.png
new file mode 100644
index 0000000..9119dd3
--- /dev/null
+++ b/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_box_inset_all.png
Binary files differ
diff --git a/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_box_inset_top.png b/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_box_inset_top.png
new file mode 100644
index 0000000..6d2da70
--- /dev/null
+++ b/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_box_inset_top.png
Binary files differ
diff --git a/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_notification.png b/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_notification.png
new file mode 100644
index 0000000..936bcaf
--- /dev/null
+++ b/prebuilts/gradle/DelayedConfirmation/screenshots/delayed_confirmation_notification.png
Binary files differ
diff --git a/prebuilts/gradle/DelayedConfirmation/settings.gradle b/prebuilts/gradle/DelayedConfirmation/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/DelayedConfirmation/settings.gradle
+++ b/prebuilts/gradle/DelayedConfirmation/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/DoneBar/Application/src/main/res/values/template-attrs.xml b/prebuilts/gradle/DoneBar/Application/src/main/res/values/template-attrs.xml
new file mode 100644
index 0000000..442ed77
--- /dev/null
+++ b/prebuilts/gradle/DoneBar/Application/src/main/res/values/template-attrs.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.
+-->
+
+<resources>
+</resources>
\ No newline at end of file
diff --git a/prebuilts/gradle/ElizaChat/Application/build.gradle b/prebuilts/gradle/ElizaChat/Application/build.gradle
index c50e592..75a4852 100644
--- a/prebuilts/gradle/ElizaChat/Application/build.gradle
+++ b/prebuilts/gradle/ElizaChat/Application/build.gradle
@@ -13,7 +13,7 @@
dependencies {
- // Add the support lib that is appropriate for SDK 20
+ // Add the support lib that is appropriate for SDK 18
compile "com.android.support:support-v13:20.+"
diff --git a/prebuilts/gradle/ElizaChat/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/ElizaChat/Application/src/main/AndroidManifest.xml
index e653fa9..98d4d73 100644
--- a/prebuilts/gradle/ElizaChat/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/ElizaChat/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.elizachat" >
+ package="com.example.android.wearable.elizachat" >
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application
android:allowBackup="true"
@@ -36,8 +36,8 @@
<service
android:name=".ResponderService">
<intent-filter>
- <action android:name="com.example.android.elizachat.REPLY" />
- <action android:name="com.example.android.elizachat.CONVERSATION" />
+ <action android:name="com.example.android.wearable.elizachat.REPLY" />
+ <action android:name="com.example.android.wearable.elizachat.CONVERSATION" />
</intent-filter>
</service>
</application>
diff --git a/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/ElizaResponder.java b/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/ElizaResponder.java
new file mode 100644
index 0000000..e6c0542
--- /dev/null
+++ b/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/ElizaResponder.java
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.elizachat;
+
+import android.text.TextUtils;
+
+/**
+ * A basic chat bot based on ELIZA, one of the earliest programs to employ primitive natural
+ * language processing. Like ELIZA, this bot can simulate a Rogerian psychotherapist using a
+ * collection of vague and generic responses.
+ */
+public class ElizaResponder {
+
+ private static final String[] CONVERSATION_KEYWORDS = {
+ "CAN YOU", "CAN I", "YOU ARE", "YOURE", "I DONT", "I FEEL", "WHY DONT YOU", "WHY CANT I",
+ "ARE YOU", "I CANT", "I AM", " IM ", "YOU", "I WANT", "WHAT", "HOW", "WHO", "WHERE",
+ "WHEN", "WHY", "NAME", "CAUSE", "SORRY", "DREAM", "HELLO", "HI", "MAYBE", "NO", "YOUR",
+ "ALWAYS", "THINK", "ALIKE", "YES", "FRIEND", "COMPUTER", "NOKEYFOUND" };
+
+ private static String[] WORDS_TO_REPLACE = {"ARE","AM","WERE","WAS","YOU","I","YOUR","MY",
+ "IVE","YOUVE","IM","YOURE", "YOU", "ME"};
+
+ private static String[] QUESTIONS = {
+ "DON'T YOU BELIEVE THAT I CAN.", "PERHAPS YOU WOULD LIKE TO BE ABLE TO.",
+ "YOU WANT ME TO BE ABLE TO*", "PERHAPS YOU DON'T WANT TO*",
+ "DO YOU WANT TO BE ABLE TO*", "WHAT MAKES YOU THINK I AM*",
+ "DOES IT PLEASE YOU TO BELIEVE I AM*", "PERHAPS YOU WOULD LIKE TO BE*",
+ "DO YOU SOMETIMES WISH YOU WERE*", "DON'T YOU REALLY*", "WHY DON'T YOU*",
+ "DO YOU WISH TO BE ABLE TO*", "DOES THAT TROUBLE YOU?",
+ "TELL ME MORE ABOUT SUCH FEELINGS*", "DO YOU OFTEN FEEL*",
+ "DO YOU ENJOY FEELING*", "DO YOU REALLY BELIEVE I DON'T*",
+ "PERHAPS IN TIME I WILL*", "DO YOU WANT ME TO*",
+ "DO YOU THINK YOU SHOULD BE ABLE TO*", "WHY CAN'T YOU*",
+ "WHAT MAKES YOU WONDER WHETHER OR NOT I AM*",
+ "WOULD YOU PREFER IF I WERE NOT*", "PERHAPS IN YOUR FANTASIES I AM*",
+ "HOW DO YOU KNOW YOU CAN'T*", "HAVE YOU TRIED?", "PERHAPS YOU CAN NOW*",
+ "DID YOU COME TO ME BECAUSE YOU ARE*", "HOW LONG HAVE YOU BEEN*",
+ "DO YOU BELIEVE IT IS NORMAL TO BE*", "DO YOU ENJOY BEING*",
+ "I AM MORE INTERESTED IN TALKING ABOUT YOU.", "OH, I*",
+ "ARE YOU REALLY SO INTERESTED IN SOMEONE LIKE ME?",
+ "WHAT WOULD IT MEAN TO YOU IF YOU GOT*", "WHY DO YOU WANT*",
+ "SUPPOSE YOU SOON GOT*", "WHAT IF YOU NEVER GOT*", "I SOMETIMES ALSO WANT*",
+ "WHY DO YOU ASK?", "DOES THAT QUESTION INTEREST YOU?",
+ "WHAT ANSWER WOULD PLEASE YOU THE MOST?", "WHAT DO YOU THINK?",
+ "ARE SUCH QUESTIONS ON YOUR MIND OFTEN?",
+ "WHAT IS IT THAT YOU REALLY WANT TO KNOW?", "HAVE YOU ASKED ANYONE ELSE?",
+ "HAVE YOU ASKED SUCH QUESTIONS BEFORE?",
+ "WHAT ELSE COMES TO MIND WHEN YOU ASK THAT?", "WE CAN KEEP THIS ANONYMOUS.",
+ "NO NEED TO SPECIFY ANY NAMES-- PLEASE GO ON.", "IS THAT THE REAL REASON?",
+ "DON'T ANY OTHER REASONS COME TO MIND?",
+ "DOES THAT REASON EXPLAIN ANYTHING ELSE?", "WHAT OTHER REASONS MIGHT THERE BE?",
+ "PLEASE DON'T APOLOGIZE.", "APOLOGIES ARE NOT NECESSARY.",
+ "WHAT FEELINGS DO YOU HAVE WHEN YOU APOLOGIZE?", "NO NEED TO BE DEFENSIVE!",
+ "WHAT DOES THAT DREAM SUGGEST TO YOU?", "DO YOU DREAM OFTEN?",
+ "WHAT PERSONS APPEAR IN YOUR DREAMS?", "DO YOU HAVE PLEASANT DREAMS?",
+ "HOW DO YOU DO ... PLEASE STATE YOUR PROBLEM.", "YOU DON'T SEEM QUITE CERTAIN.",
+ "WHY THE UNCERTAIN TONE?", "LET'S TRY TO KEEP THIS POSITIVE.", "YOU AREN'T SURE?",
+ "DON'T YOU KNOW?", "IS THAT A DEFINITE NO OR MIGHT YOU CHANGE YOUR MIND?",
+ "I AM SENSING SOME NEGATIVITY.", "WHY NOT?", "ARE YOU SURE?", "WHY NO?",
+ "WHY ARE YOU CONCERNED ABOUT MY*", "WHAT ABOUT YOUR OWN*",
+ "CAN'T YOU THINK OF A SPECIFIC EXAMPLE?", "WHEN?", "WHAT ARE YOU THINKING OF?",
+ "REALLY. ALWAYS?", "DO YOU REALLY THINK SO?", "BUT YOU ARE NOT SURE YOU.",
+ "BELIEVE IN YOURSELF.", "IN WHAT WAY?", "WHAT RESEMBLANCE DO YOU SEE?",
+ "WHAT DOES THE SIMILARITY SUGGEST TO YOU?",
+ "WHAT OTHER CONNECTIONS DO YOU SEE?", "COULD THERE REALLY BE SOME CONNECTION?",
+ "HOW?", "YOU SEEM QUITE POSITIVE.", "ARE YOU SURE?", "I SEE.", "I UNDERSTAND.",
+ "TELL ME ABOUT YOUR FRIENDS.", "ARE YOU WORRIED ABOUT YOUR FRIENDS?",
+ "DO YOUR FRIENDS EVER GIVE YOU A HARD TIME?", "WHAT DO YOU LIKE ABOUT YOUR FRIENDS?",
+ "DO YOU LOVE YOUR FRIENDS?", "PERHAPS YOUR LOVE FOR FRIENDS WORRIES YOU.",
+ "DO COMPUTERS EXCITE YOU?", "ARE YOU TALKING ABOUT ME IN PARTICULAR?",
+ "HOW DO YOU LIKE YOUR WATCH?", "WHY DO YOU MENTION COMPUTERS?",
+ "DO YOU FIND MACHINES AS FASCINATING AS I DO?",
+ "DON'T YOU THINK COMPUTERS CAN HELP PEOPLE?",
+ "WHAT ABOUT MACHINES EXCITES YOU THE MOST?",
+ "HEY THERE, HOW CAN I HELP YOU?",
+ "WHAT DOES THAT SUGGEST TO YOU?", "I SEE.",
+ "I'M NOT SURE I UNDERSTAND YOU FULLY.", "COME COME ELUCIDATE YOUR THOUGHTS.",
+ "CAN YOU ELABORATE ON THAT?", "THAT IS QUITE INTERESTING."};
+
+ private static char[] CONVERSATION_TO_RESPONSES_MAP = {
+ 1,3,4,2,6,4,6,4,10,4,14,3,17,3,20,2,22,3,25,3,
+ 28,4,28,4,32,3,35,5,40,9,40,9,40,9,40,9,40,9,40,9,
+ 49,2,51,4,55,4,59,4,63,1,63,1,64,5,69,5,74,2,76,4,
+ 80,3,83,7,90,3,93,6,99,7,106,6};
+
+ private int[] responseStarts = new int[36];
+ private int[] responseCurrentIndices = new int[36];
+ private int[] responseEnds = new int[36];
+ private String previousInput = null;
+
+ public ElizaResponder() {
+ for (int i = 0; i < CONVERSATION_TO_RESPONSES_MAP.length / 2; i++) {
+ responseStarts[i] = CONVERSATION_TO_RESPONSES_MAP[2 * i];
+ responseCurrentIndices[i] = CONVERSATION_TO_RESPONSES_MAP[2 * i];
+ responseEnds[i] = responseStarts[i] + CONVERSATION_TO_RESPONSES_MAP[2 * i + 1];
+ }
+ }
+
+ public String elzTalk(String input) {
+ if (null == input) {
+ input = "";
+ }
+ String result = "";
+
+ input = " " + input.toUpperCase().replace("\'", "") + " ";
+
+ if (previousInput != null && input.equals(previousInput)) {
+ return "DIDN'T YOU JUST SAY THAT?\n";
+ }
+ previousInput = input;
+
+ int keywordIndex = 0;
+ for (; keywordIndex < CONVERSATION_KEYWORDS.length; ++keywordIndex) {
+ int index = input.indexOf(CONVERSATION_KEYWORDS[keywordIndex]);
+ if (index != -1) {
+ break;
+ }
+ }
+
+ String afterKeyword = "";
+ if (keywordIndex == CONVERSATION_KEYWORDS.length) {
+ keywordIndex = 35;
+ } else {
+ int index = input.indexOf(CONVERSATION_KEYWORDS[keywordIndex]);
+ afterKeyword = input.substring(index + CONVERSATION_KEYWORDS[keywordIndex].length());
+ String[] parts = afterKeyword.split("\\s+");
+ for (int i = 0; i < WORDS_TO_REPLACE.length / 2; i++) {
+ String first = WORDS_TO_REPLACE[i * 2];
+ String second = WORDS_TO_REPLACE[i * 2 + 1];
+ for (int j = 0; j < parts.length; ++j) {
+ if (parts[j].equals(first)) {
+ parts[j] = second;
+ } else if (parts[j].equals(second)) {
+ parts[j] = first;
+ }
+ }
+ }
+ afterKeyword = TextUtils.join(" ", parts);
+ }
+
+ String question = QUESTIONS[responseCurrentIndices[keywordIndex] - 1];
+ responseCurrentIndices[keywordIndex] = responseCurrentIndices[keywordIndex] + 1;
+ if (responseCurrentIndices[keywordIndex] > responseEnds[keywordIndex]) {
+ responseCurrentIndices[keywordIndex] = responseStarts[keywordIndex];
+ }
+ result += question;
+ if (result.endsWith("*")) {
+ result = result.substring(0, result.length() - 1);
+ result += " " + afterKeyword;
+ }
+
+ return result;
+ }
+}
diff --git a/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/MainActivity.java b/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/MainActivity.java
new file mode 100644
index 0000000..982e3de
--- /dev/null
+++ b/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/MainActivity.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.elizachat;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.support.v4.content.LocalBroadcastManager;
+import android.text.TextUtils;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.widget.TextView;
+
+public class MainActivity extends Activity {
+
+ @SuppressWarnings("unused")
+ private static final String TAG = "MainActivity";
+
+ public static final String EXTRA_MESSAGE = "message";
+
+ public static final String ACTION_NOTIFY = "com.example.android.wearable.elizachat.NOTIFY";
+
+ public static final String ACTION_GET_CONVERSATION
+ = "com.example.android.wearable.elizachat.CONVERSATION";
+
+ private BroadcastReceiver mReceiver;
+
+ private TextView mHistoryView;
+
+ @Override
+ protected void onCreate(Bundle saved) {
+ super.onCreate(saved);
+ setContentView(R.layout.main);
+ mReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ processMessage(intent);
+ }
+ };
+ mHistoryView = (TextView) findViewById(R.id.history);
+ startResponderService();
+ }
+
+ private void startResponderService() {
+ Intent serviceIntent = new Intent(ResponderService.ACTION_INCOMING);
+ startService(serviceIntent);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
+ new IntentFilter(ACTION_NOTIFY));
+ mHistoryView.setText("");
+ Intent serviceIntent = new Intent(ACTION_GET_CONVERSATION);
+ startService(serviceIntent);
+
+ }
+
+ @Override
+ protected void onPause() {
+ LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
+ super.onPause();
+ }
+
+ private void processMessage(Intent intent) {
+ String text = intent.getStringExtra(EXTRA_MESSAGE);
+ if (!TextUtils.isEmpty(text)) {
+ mHistoryView.append("\n" + text);
+ }
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ super.onCreateOptionsMenu(menu);
+ getMenuInflater().inflate(R.menu.main, menu);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case R.id.action_stop_service:
+ stopService(new Intent(this, ResponderService.class));
+ finish();
+ break;
+ }
+ return true;
+ }
+}
diff --git a/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/ResponderService.java b/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/ResponderService.java
new file mode 100644
index 0000000..3bef19c
--- /dev/null
+++ b/prebuilts/gradle/ElizaChat/Application/src/main/java/com/example/android/wearable/elizachat/ResponderService.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.elizachat;
+
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.app.Service;
+import android.content.Intent;
+import android.graphics.BitmapFactory;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.support.v4.app.NotificationCompat;
+import android.support.v4.app.RemoteInput;
+import android.support.v4.content.LocalBroadcastManager;
+import android.support.v4.app.NotificationManagerCompat;
+import android.text.TextUtils;
+import android.util.Log;
+
+/**
+ * A service that runs in the background and provides responses to the incoming messages from the
+ * wearable. It also keeps a record of the chat session history, which it can provide upon request.
+ */
+public class ResponderService extends Service {
+
+ public static final String ACTION_INCOMING = "com.example.android.wearable.elizachat.INCOMING";
+
+ public static final String ACTION_RESPONSE = "com.example.android.wearable.elizachat.REPLY";
+
+ public static final String EXTRA_REPLY = "reply";
+
+ private static final String TAG = "ResponderService";
+
+ private ElizaResponder mResponder;
+
+ private String mLastResponse = null;
+
+ private StringBuffer mCompleteConversation = new StringBuffer();
+
+ private LocalBroadcastManager mBroadcastManager;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Chat Service started");
+ }
+ mResponder = new ElizaResponder();
+ mBroadcastManager = LocalBroadcastManager.getInstance(this);
+ processIncoming(null);
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ if (null == intent || null == intent.getAction()) {
+ return Service.START_STICKY;
+ }
+ String action = intent.getAction();
+ if (action.equals(ACTION_RESPONSE)) {
+ Bundle remoteInputResults = RemoteInput.getResultsFromIntent(intent);
+ CharSequence replyMessage = "";
+ if (remoteInputResults != null) {
+ replyMessage = remoteInputResults.getCharSequence(EXTRA_REPLY);
+ }
+ processIncoming(replyMessage.toString());
+ } else if (action.equals(MainActivity.ACTION_GET_CONVERSATION)) {
+ broadcastMessage(mCompleteConversation.toString());
+ }
+ return Service.START_STICKY;
+ }
+
+ private void showNotification() {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Sent: " + mLastResponse);
+ }
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
+ .setContentTitle(getString(R.string.eliza))
+ .setContentText(mLastResponse)
+ .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bg_eliza))
+ .setSmallIcon(R.drawable.bg_eliza)
+ .setPriority(NotificationCompat.PRIORITY_MIN);
+
+ Intent intent = new Intent(ACTION_RESPONSE);
+ PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
+ PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
+ Notification notification = builder
+ .extend(new NotificationCompat.WearableExtender()
+ .addAction(new NotificationCompat.Action.Builder(
+ R.drawable.ic_full_reply, getString(R.string.reply), pendingIntent)
+ .addRemoteInput(new RemoteInput.Builder(EXTRA_REPLY)
+ .setLabel(getString(R.string.reply))
+ .build())
+ .build()))
+ .build();
+ NotificationManagerCompat.from(this).notify(0, notification);
+ }
+
+ private void processIncoming(String text) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Received: " + text);
+ }
+ mLastResponse = mResponder.elzTalk(text);
+ String line = TextUtils.isEmpty(text) ? mLastResponse : text + "\n" + mLastResponse;
+
+ // Send a new line of conversation to update the Activity, unless the incoming text was
+ // empty.
+ if (!TextUtils.isEmpty(text)) {
+ broadcastMessage(line);
+ }
+ NotificationManagerCompat.from(this).cancelAll();
+ showNotification();
+ mCompleteConversation.append("\n" + line);
+ }
+
+ private void broadcastMessage(String message) {
+ Intent intent = new Intent(MainActivity.ACTION_NOTIFY);
+ intent.putExtra(MainActivity.EXTRA_MESSAGE, message);
+ mBroadcastManager.sendBroadcast(intent);
+ }
+
+ @Override
+ public void onDestroy() {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Chat Service stopped");
+ }
+ NotificationManagerCompat.from(this).cancel(0);
+ mBroadcastManager = null;
+ super.onDestroy();
+ }
+}
diff --git a/prebuilts/gradle/ElizaChat/screenshots/companion_eliza_chat.png b/prebuilts/gradle/ElizaChat/screenshots/companion_eliza_chat.png
new file mode 100644
index 0000000..b7fd266
--- /dev/null
+++ b/prebuilts/gradle/ElizaChat/screenshots/companion_eliza_chat.png
Binary files differ
diff --git a/prebuilts/gradle/ElizaChat/screenshots/companion_eliza_chat_response.png b/prebuilts/gradle/ElizaChat/screenshots/companion_eliza_chat_response.png
new file mode 100644
index 0000000..cea063c
--- /dev/null
+++ b/prebuilts/gradle/ElizaChat/screenshots/companion_eliza_chat_response.png
Binary files differ
diff --git a/prebuilts/gradle/ElizaChat/screenshots/wearable_eliza_notification.png b/prebuilts/gradle/ElizaChat/screenshots/wearable_eliza_notification.png
new file mode 100644
index 0000000..c5ced49
--- /dev/null
+++ b/prebuilts/gradle/ElizaChat/screenshots/wearable_eliza_notification.png
Binary files differ
diff --git a/prebuilts/gradle/ElizaChat/screenshots/wearable_voice_reply.png b/prebuilts/gradle/ElizaChat/screenshots/wearable_voice_reply.png
new file mode 100644
index 0000000..032e037
--- /dev/null
+++ b/prebuilts/gradle/ElizaChat/screenshots/wearable_voice_reply.png
Binary files differ
diff --git a/prebuilts/gradle/EmbeddedApp/Application/build.gradle b/prebuilts/gradle/EmbeddedApp/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/EmbeddedApp/Application/build.gradle
+++ b/prebuilts/gradle/EmbeddedApp/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/EmbeddedApp/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/EmbeddedApp/Application/src/main/AndroidManifest.xml
index 2d266f2..eb2e01c 100644
--- a/prebuilts/gradle/EmbeddedApp/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/EmbeddedApp/Application/src/main/AndroidManifest.xml
@@ -15,8 +15,8 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.embeddedapp" >
- <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="19" />
+ package="com.example.android.wearable.embeddedapp" >
+ <uses-sdk android:minSdkVersion="18" android:targetSdkVersion="20" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
diff --git a/prebuilts/gradle/EmbeddedApp/Application/src/main/java/com/example/android/wearable/embeddedapp/PhoneActivity.java b/prebuilts/gradle/EmbeddedApp/Application/src/main/java/com/example/android/wearable/embeddedapp/PhoneActivity.java
new file mode 100644
index 0000000..5a2f5ca
--- /dev/null
+++ b/prebuilts/gradle/EmbeddedApp/Application/src/main/java/com/example/android/wearable/embeddedapp/PhoneActivity.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.embeddedapp;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class PhoneActivity extends Activity {
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_phone);
+ }
+}
diff --git a/prebuilts/gradle/EmbeddedApp/Wearable/build.gradle b/prebuilts/gradle/EmbeddedApp/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/EmbeddedApp/Wearable/build.gradle
+++ b/prebuilts/gradle/EmbeddedApp/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/EmbeddedApp/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/EmbeddedApp/Wearable/src/main/AndroidManifest.xml
index fd07d3c..2c1d52c 100644
--- a/prebuilts/gradle/EmbeddedApp/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/EmbeddedApp/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.embeddedapp" >
+ package="com.example.android.wearable.embeddedapp" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
diff --git a/prebuilts/gradle/EmbeddedApp/Wearable/src/main/java/com/example/android/wearable/embeddedapp/WearableActivity.java b/prebuilts/gradle/EmbeddedApp/Wearable/src/main/java/com/example/android/wearable/embeddedapp/WearableActivity.java
new file mode 100644
index 0000000..3703f34
--- /dev/null
+++ b/prebuilts/gradle/EmbeddedApp/Wearable/src/main/java/com/example/android/wearable/embeddedapp/WearableActivity.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.embeddedapp;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class WearableActivity extends Activity {
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_wearable);
+ }
+}
diff --git a/prebuilts/gradle/EmbeddedApp/screenshots/embedded_wearable_app.png b/prebuilts/gradle/EmbeddedApp/screenshots/embedded_wearable_app.png
new file mode 100644
index 0000000..414afe5
--- /dev/null
+++ b/prebuilts/gradle/EmbeddedApp/screenshots/embedded_wearable_app.png
Binary files differ
diff --git a/prebuilts/gradle/EmbeddedApp/screenshots/phone_app.png b/prebuilts/gradle/EmbeddedApp/screenshots/phone_app.png
new file mode 100644
index 0000000..46c3d89
--- /dev/null
+++ b/prebuilts/gradle/EmbeddedApp/screenshots/phone_app.png
Binary files differ
diff --git a/prebuilts/gradle/EmbeddedApp/settings.gradle b/prebuilts/gradle/EmbeddedApp/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/EmbeddedApp/settings.gradle
+++ b/prebuilts/gradle/EmbeddedApp/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/FindMyPhone/Application/build.gradle b/prebuilts/gradle/FindMyPhone/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/FindMyPhone/Application/build.gradle
+++ b/prebuilts/gradle/FindMyPhone/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/FindMyPhone/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/FindMyPhone/Application/src/main/AndroidManifest.xml
index 5ca8c8a..0427025 100644
--- a/prebuilts/gradle/FindMyPhone/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/FindMyPhone/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.findphone">
+ package="com.example.android.wearable.findphone">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
@@ -32,7 +32,7 @@
android:value="@integer/google_play_services_version" />
<service
- android:name="com.example.android.findphone.SoundAlarmListenerService" >
+ android:name="com.example.android.wearable.findphone.SoundAlarmListenerService" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
diff --git a/prebuilts/gradle/FindMyPhone/Application/src/main/java/com/example/android/wearable/findphone/SoundAlarmListenerService.java b/prebuilts/gradle/FindMyPhone/Application/src/main/java/com/example/android/wearable/findphone/SoundAlarmListenerService.java
new file mode 100644
index 0000000..c89db9d
--- /dev/null
+++ b/prebuilts/gradle/FindMyPhone/Application/src/main/java/com/example/android/wearable/findphone/SoundAlarmListenerService.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.findphone;
+
+import android.media.AudioManager;
+import android.media.MediaPlayer;
+import android.media.RingtoneManager;
+import android.net.Uri;
+import android.util.Log;
+
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.WearableListenerService;
+
+import java.io.IOException;
+
+/**
+ * Listens for disconnection from home device.
+ */
+public class SoundAlarmListenerService extends WearableListenerService {
+
+ private static final String TAG = "ExampleFindPhoneApp";
+
+ private static final String FIELD_ALARM_ON = "alarm_on";
+
+ private AudioManager mAudioManager;
+ private static int mOrigVolume;
+ private int mMaxVolume;
+ private Uri mAlarmSound;
+ private MediaPlayer mMediaPlayer;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
+ mOrigVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
+ mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM);
+ mAlarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
+ mMediaPlayer = new MediaPlayer();
+ }
+
+ @Override
+ public void onDestroy() {
+ // Reset the alarm volume to the user's original setting.
+ mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mOrigVolume, 0);
+ mMediaPlayer.release();
+ super.onDestroy();
+ }
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onDataChanged: " + dataEvents + " for " + getPackageName());
+ }
+ for (DataEvent event : dataEvents) {
+ if (event.getType() == DataEvent.TYPE_DELETED) {
+ Log.i(TAG, event + " deleted");
+ } else if (event.getType() == DataEvent.TYPE_CHANGED) {
+ Boolean alarmOn =
+ DataMap.fromByteArray(event.getDataItem().getData()).get(FIELD_ALARM_ON);
+ if (alarmOn) {
+ mOrigVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_ALARM);
+ mMediaPlayer.reset();
+ // Sound alarm at max volume.
+ mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mMaxVolume, 0);
+ mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
+ try {
+ mMediaPlayer.setDataSource(getApplicationContext(), mAlarmSound);
+ mMediaPlayer.prepare();
+ } catch (IOException e) {
+ Log.e(TAG, "Failed to prepare media player to play alarm.", e);
+ }
+ mMediaPlayer.start();
+ } else {
+ // Reset the alarm volume to the user's original setting.
+ mAudioManager.setStreamVolume(AudioManager.STREAM_ALARM, mOrigVolume, 0);
+ if (mMediaPlayer.isPlaying()) {
+ mMediaPlayer.stop();
+ }
+ }
+ }
+ }
+ dataEvents.close();
+ }
+
+}
diff --git a/prebuilts/gradle/FindMyPhone/Wearable/build.gradle b/prebuilts/gradle/FindMyPhone/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/FindMyPhone/Wearable/build.gradle
+++ b/prebuilts/gradle/FindMyPhone/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/FindMyPhone/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/FindMyPhone/Wearable/src/main/AndroidManifest.xml
index b81dd33..fd6d274 100644
--- a/prebuilts/gradle/FindMyPhone/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/FindMyPhone/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.findphone" >
+ package="com.example.android.wearable.findphone" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -39,7 +39,7 @@
</intent-filter>
</service>
- <service android:name="com.example.android.findphone.FindPhoneService"/>
+ <service android:name="com.example.android.wearable.findphone.FindPhoneService"/>
<activity
android:name=".FindPhoneActivity"
diff --git a/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/DisconnectListenerService.java b/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/DisconnectListenerService.java
new file mode 100644
index 0000000..42237de
--- /dev/null
+++ b/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/DisconnectListenerService.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.findphone;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+
+import com.google.android.gms.wearable.WearableListenerService;
+
+/**
+ * Listens for disconnection from home device.
+ */
+public class DisconnectListenerService extends WearableListenerService {
+
+ private static final String TAG = "ExampleFindPhoneApp";
+
+ private static final int FORGOT_PHONE_NOTIFICATION_ID = 1;
+
+ @Override
+ public void onPeerDisconnected(com.google.android.gms.wearable.Node peer) {
+ // Create a "forgot phone" notification when phone connection is broken.
+ Notification.Builder notificationBuilder = new Notification.Builder(this)
+ .setContentTitle(getString(R.string.left_phone_title))
+ .setContentText(getString(R.string.left_phone_content))
+ .setVibrate(new long[] {0, 200}) // Vibrate for 200 milliseconds.
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setLocalOnly(true)
+ .setPriority(Notification.PRIORITY_MAX);
+ Notification card = notificationBuilder.build();
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(FORGOT_PHONE_NOTIFICATION_ID, card);
+ }
+
+ @Override
+ public void onPeerConnected(com.google.android.gms.wearable.Node peer) {
+ // Remove the "forgot phone" notification when connection is restored.
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .cancel(FORGOT_PHONE_NOTIFICATION_ID);
+ }
+
+}
diff --git a/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/FindPhoneActivity.java b/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/FindPhoneActivity.java
new file mode 100644
index 0000000..d4eb18b
--- /dev/null
+++ b/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/FindPhoneActivity.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.findphone;
+
+import android.app.Activity;
+import android.app.Notification;
+import android.app.Notification.Action;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.text.Spannable;
+import android.text.SpannableString;
+import android.text.style.RelativeSizeSpan;
+
+
+public class FindPhoneActivity extends Activity {
+
+ private static final int FIND_PHONE_NOTIFICATION_ID = 2;
+ private static Notification.Builder notification;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ // Create a notification with an action to toggle an alarm on the phone.
+ Intent toggleAlarmOperation = new Intent(this, FindPhoneService.class);
+ toggleAlarmOperation.setAction(FindPhoneService.ACTION_TOGGLE_ALARM);
+ PendingIntent toggleAlarmIntent = PendingIntent.getService(this, 0, toggleAlarmOperation,
+ PendingIntent.FLAG_CANCEL_CURRENT);
+ Action alarmAction = new Action(R.drawable.alarm_action_icon, "", toggleAlarmIntent);
+ // This intent turns off the alarm if the user dismisses the card from the wearable.
+ Intent cancelAlarmOperation = new Intent(this, FindPhoneService.class);
+ cancelAlarmOperation.setAction(FindPhoneService.ACTION_CANCEL_ALARM);
+ PendingIntent cancelAlarmIntent = PendingIntent.getService(this, 0, cancelAlarmOperation,
+ PendingIntent.FLAG_CANCEL_CURRENT);
+ // Use a spannable string for the notification title to resize it.
+ SpannableString title = new SpannableString(getString(R.string.app_name));
+ title.setSpan(new RelativeSizeSpan(0.85f), 0, title.length(), Spannable.SPAN_POINT_MARK);
+ notification = new Notification.Builder(this)
+ .setContentTitle(title)
+ .setContentText(getString(R.string.turn_alarm_on))
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setVibrate(new long[] {0, 50}) // Vibrate to bring card to top of stream.
+ .setDeleteIntent(cancelAlarmIntent)
+ .extend(new Notification.WearableExtender()
+ .addAction(alarmAction)
+ .setContentAction(0)
+ .setHintHideIcon(true))
+ .setLocalOnly(true)
+ .setPriority(Notification.PRIORITY_MAX);
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(FIND_PHONE_NOTIFICATION_ID, notification.build());
+
+ finish();
+ }
+
+ /**
+ * Updates the text on the wearable notification. This is used so the notification reflects the
+ * current state of the alarm on the phone. For instance, if the alarm is turned on, the
+ * notification text indicates that the user can tap it to turn it off, and vice-versa.
+ *
+ * @param context
+ * @param notificationText The new text to display on the wearable notification.
+ */
+ public static void updateNotification(Context context, String notificationText) {
+ notification.setContentText(notificationText);
+ ((NotificationManager) context.getSystemService(NOTIFICATION_SERVICE))
+ .notify(FIND_PHONE_NOTIFICATION_ID, notification.build());
+ }
+
+}
diff --git a/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/FindPhoneService.java b/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/FindPhoneService.java
new file mode 100644
index 0000000..e5fa6c0
--- /dev/null
+++ b/prebuilts/gradle/FindMyPhone/Wearable/src/main/java/com/example/android/wearable/findphone/FindPhoneService.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.findphone;
+
+import android.app.IntentService;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.DataItemBuffer;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Creates a sound on the paired phone to find it.
+ */
+public class FindPhoneService extends IntentService implements GoogleApiClient.ConnectionCallbacks,
+ GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String TAG = "ExampleFindPhoneApp";
+
+ private static final String FIELD_ALARM_ON = "alarm_on";
+ private static final String PATH_SOUND_ALARM = "/sound_alarm";
+ public static final String ACTION_TOGGLE_ALARM = "action_toggle_alarm";
+ public static final String ACTION_CANCEL_ALARM = "action_alarm_off";
+
+ // Timeout for making a connection to GoogleApiClient (in milliseconds).
+ private static final long CONNECTION_TIME_OUT_MS = 100;
+ private GoogleApiClient mGoogleApiClient;
+
+ public FindPhoneService() {
+ super(FindPhoneService.class.getSimpleName());
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
+ if (Log.isLoggable(TAG, Log.VERBOSE)) {
+ Log.v(TAG, "FindPhoneService.onHandleIntent");
+ }
+ if (mGoogleApiClient.isConnected()) {
+ // Set the alarm off by default.
+ boolean alarmOn = false;
+ if (intent.getAction().equals(ACTION_TOGGLE_ALARM)) {
+ // Get current state of the alarm.
+ DataItemBuffer result = Wearable.DataApi.getDataItems(mGoogleApiClient).await();
+ if (result.getStatus().isSuccess()) {
+ if (result.getCount() == 1) {
+ alarmOn = DataMap.fromByteArray(result.get(0).getData())
+ .getBoolean(FIELD_ALARM_ON, false);
+ } else {
+ Log.e(TAG, "Unexpected number of DataItems found.\n"
+ + "\tExpected: 1\n"
+ + "\tActual: " + result.getCount());
+ }
+ } else if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onHandleIntent: failed to get current alarm state");
+ }
+ result.close();
+ // Toggle alarm.
+ alarmOn = !alarmOn;
+ // Change notification text based on new value of alarmOn.
+ String notificationText = alarmOn ? getString(R.string.turn_alarm_off)
+ : getString(R.string.turn_alarm_on);
+ FindPhoneActivity.updateNotification(this, notificationText);
+ }
+ // Use alarmOn boolean to update the DataItem - phone will respond accordingly
+ // when it receives the change.
+ PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(PATH_SOUND_ALARM);
+ putDataMapRequest.getDataMap().putBoolean(FIELD_ALARM_ON, alarmOn);
+ Wearable.DataApi.putDataItem(mGoogleApiClient, putDataMapRequest.asPutDataRequest())
+ .await();
+ } else {
+ Log.e(TAG, "Failed to toggle alarm on phone - Client disconnected from Google Play "
+ + "Services");
+ }
+ mGoogleApiClient.disconnect();
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ }
+
+}
diff --git a/prebuilts/gradle/FindMyPhone/screenshots/find_my_phone_activity.png b/prebuilts/gradle/FindMyPhone/screenshots/find_my_phone_activity.png
new file mode 100644
index 0000000..8cff992
--- /dev/null
+++ b/prebuilts/gradle/FindMyPhone/screenshots/find_my_phone_activity.png
Binary files differ
diff --git a/prebuilts/gradle/FindMyPhone/screenshots/find_my_phone_notification.png b/prebuilts/gradle/FindMyPhone/screenshots/find_my_phone_notification.png
new file mode 100644
index 0000000..a8ed867
--- /dev/null
+++ b/prebuilts/gradle/FindMyPhone/screenshots/find_my_phone_notification.png
Binary files differ
diff --git a/prebuilts/gradle/FindMyPhone/settings.gradle b/prebuilts/gradle/FindMyPhone/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/FindMyPhone/settings.gradle
+++ b/prebuilts/gradle/FindMyPhone/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/Flashlight/Application/build.gradle b/prebuilts/gradle/Flashlight/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/Flashlight/Application/build.gradle
+++ b/prebuilts/gradle/Flashlight/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/Flashlight/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/Flashlight/Application/src/main/AndroidManifest.xml
index 2710313..73d1d52 100644
--- a/prebuilts/gradle/Flashlight/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Flashlight/Application/src/main/AndroidManifest.xml
@@ -16,10 +16,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.flashlight">
+ package="com.example.android.wearable.flashlight">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application android:allowBackup="true"
android:label="@string/app_name">
diff --git a/prebuilts/gradle/Flashlight/Wearable/build.gradle b/prebuilts/gradle/Flashlight/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/Flashlight/Wearable/build.gradle
+++ b/prebuilts/gradle/Flashlight/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/Flashlight/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/Flashlight/Wearable/src/main/AndroidManifest.xml
index f22e1ab..1800e76 100644
--- a/prebuilts/gradle/Flashlight/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Flashlight/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.flashlight" >
+ package="com.example.android.wearable.flashlight" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
diff --git a/prebuilts/gradle/Flashlight/Wearable/src/main/java/com/example/android/wearable/flashlight/MainActivity.java b/prebuilts/gradle/Flashlight/Wearable/src/main/java/com/example/android/wearable/flashlight/MainActivity.java
new file mode 100644
index 0000000..f87cae8
--- /dev/null
+++ b/prebuilts/gradle/Flashlight/Wearable/src/main/java/com/example/android/wearable/flashlight/MainActivity.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.flashlight;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.os.Bundle;
+import android.support.v13.app.FragmentPagerAdapter;
+import android.support.v4.view.ViewPager;
+import android.support.v4.view.ViewPager.OnPageChangeListener;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import java.util.ArrayList;
+
+/**
+ * Let there be light.
+ */
+public class MainActivity extends Activity {
+
+ private ViewPager mViewPager;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.main);
+ mViewPager = (ViewPager) findViewById(R.id.pager);
+ final LightFragmentAdapter adapter = new LightFragmentAdapter(getFragmentManager());
+ adapter.addFragment(new WhiteLightFragment());
+ final PartyLightFragment partyFragment = new PartyLightFragment();
+ adapter.addFragment(partyFragment);
+ mViewPager.setAdapter(adapter);
+ mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
+
+ @Override
+ public void onPageSelected(int position) {
+ if (position == 1) {
+ partyFragment.startCycling();
+ } else {
+ partyFragment.stopCycling();
+ }
+ }
+
+ @Override
+ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
+ }
+
+ @Override
+ public void onPageScrollStateChanged(int state) {
+ }
+ });
+ }
+
+ static class LightFragmentAdapter extends FragmentPagerAdapter {
+ private ArrayList<Fragment> mFragments;
+
+ public LightFragmentAdapter(FragmentManager fm) {
+ super(fm);
+ mFragments = new ArrayList<Fragment>();
+ }
+
+ @Override
+ public Fragment getItem(int position) {
+ return mFragments.get(position);
+ }
+
+ @Override
+ public int getCount() {
+ return mFragments.size();
+ }
+
+ public void addFragment(Fragment fragment) {
+ mFragments.add(fragment);
+ // Update the pager when adding a fragment.
+ notifyDataSetChanged();
+ }
+ }
+
+ public static class WhiteLightFragment extends Fragment {
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ return inflater.inflate(R.layout.white_light, container, false);
+ }
+ }
+
+ public static class PartyLightFragment extends Fragment {
+
+ private PartyLightView mView;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ mView = (PartyLightView) inflater.inflate(R.layout.party_light, container, false);
+ return mView;
+ }
+
+ public void startCycling() {
+ mView.startCycling();
+ }
+
+ public void stopCycling() {
+ mView.stopCycling();
+ }
+
+ }
+}
diff --git a/prebuilts/gradle/Flashlight/Wearable/src/main/java/com/example/android/wearable/flashlight/PartyLightView.java b/prebuilts/gradle/Flashlight/Wearable/src/main/java/com/example/android/wearable/flashlight/PartyLightView.java
new file mode 100644
index 0000000..33f061e
--- /dev/null
+++ b/prebuilts/gradle/Flashlight/Wearable/src/main/java/com/example/android/wearable/flashlight/PartyLightView.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.flashlight;
+
+import android.animation.ArgbEvaluator;
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.os.Handler;
+import android.os.Message;
+import android.util.AttributeSet;
+import android.view.View;
+
+/**
+ * Flashing party lights!
+ */
+public class PartyLightView extends View {
+
+ private int[] mColors = new int[] {
+ Color.RED,
+ Color.GREEN,
+ Color.BLUE,
+ Color.CYAN,
+ Color.MAGENTA
+ };
+
+ private int mFromColorIndex;
+ private int mToColorIndex;
+
+ /**
+ * Value b/t 0 and 1.
+ */
+ private float mProgress;
+
+ private ArgbEvaluator mEvaluator;
+
+ private int mCurrentColor;
+
+ private Handler mHandler;
+
+ public PartyLightView(Context context) {
+ super(context);
+ init();
+ }
+
+ public PartyLightView(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ init();
+ }
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+ canvas.drawColor(mCurrentColor);
+ super.onDraw(canvas);
+ }
+
+ public void startCycling() {
+ mHandler.sendEmptyMessage(0);
+ }
+
+ public void stopCycling() {
+ mHandler.removeMessages(0);
+ }
+
+ private void init() {
+ mEvaluator = new ArgbEvaluator();
+ mHandler = new Handler() {
+
+ @Override
+ public void handleMessage(Message msg) {
+ mCurrentColor = getColor(mProgress, mColors[mFromColorIndex],
+ mColors[mToColorIndex]);
+ postInvalidate();
+ mProgress += 0.1;
+ if (mProgress > 1.0) {
+ mFromColorIndex = mToColorIndex;
+ // Find a new color.
+ mToColorIndex++;
+ if (mToColorIndex >= mColors.length) {
+ mToColorIndex = 0;
+ }
+ }
+ mHandler.sendEmptyMessageDelayed(0, 100);
+ }
+ };
+ }
+
+ private int getColor(float fraction, int colorStart, int colorEnd) {
+ int startInt = colorStart;
+ int startA = (startInt >> 24) & 0xff;
+ int startR = (startInt >> 16) & 0xff;
+ int startG = (startInt >> 8) & 0xff;
+ int startB = startInt & 0xff;
+
+ int endInt = colorEnd;
+ int endA = (endInt >> 24) & 0xff;
+ int endR = (endInt >> 16) & 0xff;
+ int endG = (endInt >> 8) & 0xff;
+ int endB = endInt & 0xff;
+
+ return (startA + (int)(fraction * (endA - startA))) << 24 |
+ (startR + (int)(fraction * (endR - startR))) << 16 |
+ (startG + (int)(fraction * (endG - startG))) << 8 |
+ ((startB + (int)(fraction * (endB - startB))));
+ }
+}
diff --git a/prebuilts/gradle/Flashlight/screenshots/flashlight.png b/prebuilts/gradle/Flashlight/screenshots/flashlight.png
new file mode 100644
index 0000000..02fca20
--- /dev/null
+++ b/prebuilts/gradle/Flashlight/screenshots/flashlight.png
Binary files differ
diff --git a/prebuilts/gradle/Flashlight/screenshots/party_mode.gif b/prebuilts/gradle/Flashlight/screenshots/party_mode.gif
new file mode 100644
index 0000000..8258b7d
--- /dev/null
+++ b/prebuilts/gradle/Flashlight/screenshots/party_mode.gif
Binary files differ
diff --git a/prebuilts/gradle/Flashlight/settings.gradle b/prebuilts/gradle/Flashlight/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/Flashlight/settings.gradle
+++ b/prebuilts/gradle/Flashlight/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/Geofencing/Application/build.gradle b/prebuilts/gradle/Geofencing/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/Geofencing/Application/build.gradle
+++ b/prebuilts/gradle/Geofencing/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/Geofencing/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/Geofencing/Application/src/main/AndroidManifest.xml
index 519aa14..b5b57f6 100644
--- a/prebuilts/gradle/Geofencing/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Geofencing/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.geofencing">
+ package="com.example.android.wearable.geofencing">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
diff --git a/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/Constants.java b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/Constants.java
new file mode 100644
index 0000000..6da9151
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/Constants.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+import android.net.Uri;
+
+import com.google.android.gms.location.Geofence;
+
+/** Constants used in companion app. */
+public final class Constants {
+
+ private Constants() {
+ }
+
+ public static final String TAG = "ExampleGeofencingApp";
+
+ // Request code to attempt to resolve Google Play services connection failures.
+ public final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
+ // Timeout for making a connection to GoogleApiClient (in milliseconds).
+ public static final long CONNECTION_TIME_OUT_MS = 100;
+
+ // For the purposes of this demo, the geofences are hard-coded and should not expire.
+ // An app with dynamically-created geofences would want to include a reasonable expiration time.
+ public static final long GEOFENCE_EXPIRATION_TIME = Geofence.NEVER_EXPIRE;
+
+ // Geofence parameters for the Android building on Google's main campus in Mountain View.
+ public static final String ANDROID_BUILDING_ID = "1";
+ public static final double ANDROID_BUILDING_LATITUDE = 37.420092;
+ public static final double ANDROID_BUILDING_LONGITUDE = -122.083648;
+ public static final float ANDROID_BUILDING_RADIUS_METERS = 60.0f;
+
+ // Geofence parameters for the Yerba Buena Gardens near the Moscone Center in San Francisco.
+ public static final String YERBA_BUENA_ID = "2";
+ public static final double YERBA_BUENA_LATITUDE = 37.784886;
+ public static final double YERBA_BUENA_LONGITUDE = -122.402671;
+ public static final float YERBA_BUENA_RADIUS_METERS = 72.0f;
+
+
+ // The constants below are less interesting than those above.
+
+ // Path for the DataItem containing the last geofence id entered.
+ public static final String GEOFENCE_DATA_ITEM_PATH = "/geofenceid";
+ public static final Uri GEOFENCE_DATA_ITEM_URI =
+ new Uri.Builder().scheme("wear").path(GEOFENCE_DATA_ITEM_PATH).build();
+ public static final String KEY_GEOFENCE_ID = "geofence_id";
+
+ // Keys for flattened geofences stored in SharedPreferences.
+ public static final String KEY_LATITUDE = "com.example.wearable.geofencing.KEY_LATITUDE";
+ public static final String KEY_LONGITUDE = "com.example.wearable.geofencing.KEY_LONGITUDE";
+ public static final String KEY_RADIUS = "com.example.wearable.geofencing.KEY_RADIUS";
+ public static final String KEY_EXPIRATION_DURATION =
+ "com.example.wearable.geofencing.KEY_EXPIRATION_DURATION";
+ public static final String KEY_TRANSITION_TYPE =
+ "com.example.wearable.geofencing.KEY_TRANSITION_TYPE";
+ // The prefix for flattened geofence keys.
+ public static final String KEY_PREFIX = "com.example.wearable.geofencing.KEY";
+
+ // Invalid values, used to test geofence storage when retrieving geofences.
+ public static final long INVALID_LONG_VALUE = -999l;
+ public static final float INVALID_FLOAT_VALUE = -999.0f;
+ public static final int INVALID_INT_VALUE = -999;
+
+}
diff --git a/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/GeofenceTransitionsIntentService.java b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/GeofenceTransitionsIntentService.java
new file mode 100644
index 0000000..5d1ea48
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/GeofenceTransitionsIntentService.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+import static com.example.android.wearable.geofencing.Constants.CONNECTION_TIME_OUT_MS;
+import static com.example.android.wearable.geofencing.Constants.GEOFENCE_DATA_ITEM_PATH;
+import static com.example.android.wearable.geofencing.Constants.GEOFENCE_DATA_ITEM_URI;
+import static com.example.android.wearable.geofencing.Constants.KEY_GEOFENCE_ID;
+import static com.example.android.wearable.geofencing.Constants.TAG;
+
+import android.app.IntentService;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.location.Geofence;
+import com.google.android.gms.location.LocationClient;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Listens for geofence transition changes.
+ */
+public class GeofenceTransitionsIntentService extends IntentService
+ implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
+
+ private GoogleApiClient mGoogleApiClient;
+
+ public GeofenceTransitionsIntentService() {
+ super(GeofenceTransitionsIntentService.class.getSimpleName());
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ /**
+ * Handles incoming intents.
+ * @param intent The Intent sent by Location Services. This Intent is provided to Location
+ * Services (inside a PendingIntent) when addGeofences() is called.
+ */
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ // First check for errors.
+ if (LocationClient.hasError(intent)) {
+ int errorCode = LocationClient.getErrorCode(intent);
+ Log.e(TAG, "Location Services error: " + errorCode);
+ } else {
+ // Get the type of geofence transition (i.e. enter or exit in this sample).
+ int transitionType = LocationClient.getGeofenceTransition(intent);
+ // Create a DataItem when a user enters one of the geofences. The wearable app will
+ // receive this and create a notification to prompt him/her to check in.
+ if (Geofence.GEOFENCE_TRANSITION_ENTER == transitionType) {
+ // Connect to the Google Api service in preparation for sending a DataItem.
+ mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
+ // Get the geofence id triggered. Note that only one geofence can be triggered at a
+ // time in this example, but in some cases you might want to consider the full list
+ // of geofences triggered.
+ String triggeredGeofenceId = LocationClient.getTriggeringGeofences(intent).get(0)
+ .getRequestId();
+ // Create a DataItem with this geofence's id. The wearable can use this to create
+ // a notification.
+ final PutDataMapRequest putDataMapRequest =
+ PutDataMapRequest.create(GEOFENCE_DATA_ITEM_PATH);
+ putDataMapRequest.getDataMap().putString(KEY_GEOFENCE_ID, triggeredGeofenceId);
+ if (mGoogleApiClient.isConnected()) {
+ Wearable.DataApi.putDataItem(
+ mGoogleApiClient, putDataMapRequest.asPutDataRequest()).await();
+ } else {
+ Log.e(TAG, "Failed to send data item: " + putDataMapRequest
+ + " - Client disconnected from Google Play Services");
+ }
+ mGoogleApiClient.disconnect();
+ } else if (Geofence.GEOFENCE_TRANSITION_EXIT == transitionType) {
+ // Delete the data item when leaving a geofence region.
+ mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
+ Wearable.DataApi.deleteDataItems(mGoogleApiClient, GEOFENCE_DATA_ITEM_URI).await();
+ mGoogleApiClient.disconnect();
+ }
+ }
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ }
+
+}
diff --git a/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/MainActivity.java b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/MainActivity.java
new file mode 100644
index 0000000..baef217
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/MainActivity.java
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+import static com.example.android.wearable.geofencing.Constants.ANDROID_BUILDING_ID;
+import static com.example.android.wearable.geofencing.Constants.ANDROID_BUILDING_LATITUDE;
+import static com.example.android.wearable.geofencing.Constants.ANDROID_BUILDING_LONGITUDE;
+import static com.example.android.wearable.geofencing.Constants.ANDROID_BUILDING_RADIUS_METERS;
+import static com.example.android.wearable.geofencing.Constants.CONNECTION_FAILURE_RESOLUTION_REQUEST;
+import static com.example.android.wearable.geofencing.Constants.GEOFENCE_EXPIRATION_TIME;
+import static com.example.android.wearable.geofencing.Constants.TAG;
+import static com.example.android.wearable.geofencing.Constants.YERBA_BUENA_ID;
+import static com.example.android.wearable.geofencing.Constants.YERBA_BUENA_LATITUDE;
+import static com.example.android.wearable.geofencing.Constants.YERBA_BUENA_LONGITUDE;
+import static com.example.android.wearable.geofencing.Constants.YERBA_BUENA_RADIUS_METERS;
+
+import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.content.IntentSender;
+import android.os.Bundle;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
+import com.google.android.gms.common.GooglePlayServicesUtil;
+import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
+import com.google.android.gms.location.Geofence;
+import com.google.android.gms.location.LocationClient;
+import com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;
+import com.google.android.gms.location.LocationStatusCodes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MainActivity extends Activity implements ConnectionCallbacks,
+ OnConnectionFailedListener, OnAddGeofencesResultListener {
+
+ // Internal List of Geofence objects. In a real app, these might be provided by an API based on
+ // locations within the user's proximity.
+ List<Geofence> mGeofenceList;
+
+ // These will store hard-coded geofences in this sample app.
+ private SimpleGeofence mAndroidBuildingGeofence;
+ private SimpleGeofence mYerbaBuenaGeofence;
+
+ // Persistent storage for geofences.
+ private SimpleGeofenceStore mGeofenceStorage;
+
+ private LocationClient mLocationClient;
+ // Stores the PendingIntent used to request geofence monitoring.
+ private PendingIntent mGeofenceRequestIntent;
+
+ // Defines the allowable request types (in this example, we only add geofences).
+ private enum REQUEST_TYPE {ADD}
+ private REQUEST_TYPE mRequestType;
+ // Flag that indicates if a request is underway.
+ private boolean mInProgress;
+
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ // Rather than displayng this activity, simply display a toast indicating that the geofence
+ // service is being created. This should happen in less than a second.
+ Toast.makeText(this, getString(R.string.start_geofence_service), Toast.LENGTH_SHORT).show();
+
+ // Instantiate a new geofence storage area.
+ mGeofenceStorage = new SimpleGeofenceStore(this);
+ // Instantiate the current List of geofences.
+ mGeofenceList = new ArrayList<Geofence>();
+ // Start with the request flag set to false.
+ mInProgress = false;
+
+ createGeofences();
+ addGeofences();
+
+ finish();
+ }
+
+ /**
+ * In this sample, the geofences are predetermined and are hard-coded here. A real app might
+ * dynamically create geofences based on the user's location.
+ */
+ public void createGeofences() {
+ // Create internal "flattened" objects containing the geofence data.
+ mAndroidBuildingGeofence = new SimpleGeofence(
+ ANDROID_BUILDING_ID, // geofenceId.
+ ANDROID_BUILDING_LATITUDE,
+ ANDROID_BUILDING_LONGITUDE,
+ ANDROID_BUILDING_RADIUS_METERS,
+ GEOFENCE_EXPIRATION_TIME,
+ Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT
+ );
+ mYerbaBuenaGeofence = new SimpleGeofence(
+ YERBA_BUENA_ID, // geofenceId.
+ YERBA_BUENA_LATITUDE,
+ YERBA_BUENA_LONGITUDE,
+ YERBA_BUENA_RADIUS_METERS,
+ GEOFENCE_EXPIRATION_TIME,
+ Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT
+ );
+
+ // Store these flat versions in SharedPreferences and add them to the geofence list.
+ mGeofenceStorage.setGeofence(ANDROID_BUILDING_ID, mAndroidBuildingGeofence);
+ mGeofenceStorage.setGeofence(YERBA_BUENA_ID, mYerbaBuenaGeofence);
+ mGeofenceList.add(mAndroidBuildingGeofence.toGeofence());
+ mGeofenceList.add(mYerbaBuenaGeofence.toGeofence());
+ }
+
+ /**
+ * Start a request for geofence monitoring by calling LocationClient.connect().
+ */
+ public void addGeofences() {
+ // Start a request to add geofences.
+ mRequestType = REQUEST_TYPE.ADD;
+ // Test for Google Play services after setting the request type.
+ if (!isGooglePlayServicesAvailable()) {
+ Log.e(TAG, "Unable to add geofences - Google Play services unavailable.");
+ return;
+ }
+ // Create a new location client object. Since this activity class implements
+ // ConnectionCallbacks and OnConnectionFailedListener, it can be used as the listener for
+ // both parameters.
+ mLocationClient = new LocationClient(this, this, this);
+ // If a request is not already underway.
+ if (!mInProgress) {
+ // Indicate that a request is underway.
+ mInProgress = true;
+ // Request a connection from the client to Location Services.
+ mLocationClient.connect();
+ // A request is already underway, so disconnect the client and retry the request.
+ } else {
+ mLocationClient.disconnect();
+ mLocationClient.connect();
+ }
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult connectionResult) {
+ mInProgress = false;
+ // If the error has a resolution, start a Google Play services activity to resolve it.
+ if (connectionResult.hasResolution()) {
+ try {
+ connectionResult.startResolutionForResult(this,
+ CONNECTION_FAILURE_RESOLUTION_REQUEST);
+ } catch (IntentSender.SendIntentException e) {
+ Log.e(TAG, "Exception while resolving connection error.", e);
+ }
+ } else {
+ int errorCode = connectionResult.getErrorCode();
+ Log.e(TAG, "Connection to Google Play services failed with error code " + errorCode);
+ }
+ }
+
+ /**
+ * Called by Location Services if the location client disconnects.
+ */
+ @Override
+ public void onDisconnected() {
+ // Turn off the request flag.
+ mInProgress = false;
+ // Destroy the current location client.
+ mLocationClient = null;
+ }
+
+ /**
+ * Once the connection is available, send a request to add the Geofences.
+ */
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ // Use mRequestType to determine what action to take. Only ADD is used in this sample.
+ if (REQUEST_TYPE.ADD == mRequestType) {
+ // Get the PendingIntent for the geofence monitoring request.
+ mGeofenceRequestIntent = getGeofenceTransitionPendingIntent();
+ // Send a request to add the current geofences.
+ mLocationClient.addGeofences(mGeofenceList, mGeofenceRequestIntent, this);
+ }
+ }
+
+ /**
+ * Called when request to add geofences is complete, with a result status code.
+ */
+ @Override
+ public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
+ // Log if adding the geofences was successful.
+ if (LocationStatusCodes.SUCCESS == statusCode) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Added geofences successfully.");
+ }
+ } else {
+ Log.e(TAG, "Failed to add geofences. Status code: " + statusCode);
+ }
+ // Turn off the in progress flag and disconnect the client.
+ mInProgress = false;
+ mLocationClient.disconnect();
+ }
+
+ /**
+ * Checks if Google Play services is available.
+ * @return true if it is.
+ */
+ private boolean isGooglePlayServicesAvailable() {
+ int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
+ if (ConnectionResult.SUCCESS == resultCode) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Google Play services is available.");
+ }
+ return true;
+ } else {
+ Log.e(TAG, "Google Play services is unavailable.");
+ return false;
+ }
+ }
+
+ /**
+ * Create a PendingIntent that triggers GeofenceTransitionIntentService when a geofence
+ * transition occurs.
+ */
+ private PendingIntent getGeofenceTransitionPendingIntent() {
+ Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
+ return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
+ }
+
+}
diff --git a/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/SimpleGeofence.java b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/SimpleGeofence.java
new file mode 100644
index 0000000..50f02c3
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/SimpleGeofence.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+import com.google.android.gms.location.Geofence;
+
+/**
+ * A single Geofence object, defined by its center and radius.
+ */
+public class SimpleGeofence {
+
+ // Instance variables
+ private final String mId;
+ private final double mLatitude;
+ private final double mLongitude;
+ private final float mRadius;
+ private long mExpirationDuration;
+ private int mTransitionType;
+
+ /**
+ * @param geofenceId The Geofence's request ID.
+ * @param latitude Latitude of the Geofence's center in degrees.
+ * @param longitude Longitude of the Geofence's center in degrees.
+ * @param radius Radius of the geofence circle in meters.
+ * @param expiration Geofence expiration duration.
+ * @param transition Type of Geofence transition.
+ */
+ public SimpleGeofence(String geofenceId, double latitude, double longitude, float radius,
+ long expiration, int transition) {
+ // Set the instance fields from the constructor.
+ this.mId = geofenceId;
+ this.mLatitude = latitude;
+ this.mLongitude = longitude;
+ this.mRadius = radius;
+ this.mExpirationDuration = expiration;
+ this.mTransitionType = transition;
+ }
+
+ // Instance field getters.
+ public String getId() {
+ return mId;
+ }
+ public double getLatitude() {
+ return mLatitude;
+ }
+ public double getLongitude() {
+ return mLongitude;
+ }
+ public float getRadius() {
+ return mRadius;
+ }
+ public long getExpirationDuration() {
+ return mExpirationDuration;
+ }
+ public int getTransitionType() {
+ return mTransitionType;
+ }
+
+ /**
+ * Creates a Location Services Geofence object from a SimpleGeofence.
+ * @return A Geofence object.
+ */
+ public Geofence toGeofence() {
+ // Build a new Geofence object.
+ return new Geofence.Builder()
+ .setRequestId(mId)
+ .setTransitionTypes(mTransitionType)
+ .setCircularRegion(mLatitude, mLongitude, mRadius)
+ .setExpirationDuration(mExpirationDuration)
+ .build();
+ }
+
+}
diff --git a/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/SimpleGeofenceStore.java b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/SimpleGeofenceStore.java
new file mode 100644
index 0000000..47584f5
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Application/src/main/java/com/example/android/wearable/geofencing/SimpleGeofenceStore.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+import static com.example.android.wearable.geofencing.Constants.INVALID_FLOAT_VALUE;
+import static com.example.android.wearable.geofencing.Constants.INVALID_INT_VALUE;
+import static com.example.android.wearable.geofencing.Constants.INVALID_LONG_VALUE;
+import static com.example.android.wearable.geofencing.Constants.KEY_EXPIRATION_DURATION;
+import static com.example.android.wearable.geofencing.Constants.KEY_LATITUDE;
+import static com.example.android.wearable.geofencing.Constants.KEY_LONGITUDE;
+import static com.example.android.wearable.geofencing.Constants.KEY_PREFIX;
+import static com.example.android.wearable.geofencing.Constants.KEY_RADIUS;
+import static com.example.android.wearable.geofencing.Constants.KEY_TRANSITION_TYPE;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+
+/**
+ * Storage for geofence values, implemented in SharedPreferences.
+ */
+public class SimpleGeofenceStore {
+
+ // The SharedPreferences object in which geofences are stored.
+ private final SharedPreferences mPrefs;
+ // The name of the SharedPreferences.
+ private static final String SHARED_PREFERENCES = "SharedPreferences";
+
+ /**
+ * Create the SharedPreferences storage with private access only.
+ */
+ public SimpleGeofenceStore(Context context) {
+ mPrefs = context.getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
+ }
+
+ /**
+ * Returns a stored geofence by its id, or returns null if it's not found.
+ * @param id The ID of a stored geofence.
+ * @return A SimpleGeofence defined by its center and radius, or null if the ID is invalid.
+ */
+ public SimpleGeofence getGeofence(String id) {
+ // Get the latitude for the geofence identified by id, or INVALID_FLOAT_VALUE if it doesn't
+ // exist (similarly for the other values that follow).
+ double lat = mPrefs.getFloat(getGeofenceFieldKey(id, KEY_LATITUDE),
+ INVALID_FLOAT_VALUE);
+ double lng = mPrefs.getFloat(getGeofenceFieldKey(id, KEY_LONGITUDE),
+ INVALID_FLOAT_VALUE);
+ float radius = mPrefs.getFloat(getGeofenceFieldKey(id, KEY_RADIUS),
+ INVALID_FLOAT_VALUE);
+ long expirationDuration =
+ mPrefs.getLong(getGeofenceFieldKey(id, KEY_EXPIRATION_DURATION),
+ INVALID_LONG_VALUE);
+ int transitionType = mPrefs.getInt(getGeofenceFieldKey(id, KEY_TRANSITION_TYPE),
+ INVALID_INT_VALUE);
+ // If none of the values is incorrect, return the object.
+ if (lat != INVALID_FLOAT_VALUE
+ && lng != INVALID_FLOAT_VALUE
+ && radius != INVALID_FLOAT_VALUE
+ && expirationDuration != INVALID_LONG_VALUE
+ && transitionType != INVALID_INT_VALUE) {
+ return new SimpleGeofence(id, lat, lng, radius, expirationDuration, transitionType);
+ }
+ // Otherwise, return null.
+ return null;
+ }
+
+ /**
+ * Save a geofence.
+ * @param geofence The SimpleGeofence with the values you want to save in SharedPreferences.
+ */
+ public void setGeofence(String id, SimpleGeofence geofence) {
+ // Get a SharedPreferences editor instance. Among other things, SharedPreferences
+ // ensures that updates are atomic and non-concurrent.
+ SharedPreferences.Editor prefs = mPrefs.edit();
+ // Write the Geofence values to SharedPreferences.
+ prefs.putFloat(getGeofenceFieldKey(id, KEY_LATITUDE), (float) geofence.getLatitude());
+ prefs.putFloat(getGeofenceFieldKey(id, KEY_LONGITUDE), (float) geofence.getLongitude());
+ prefs.putFloat(getGeofenceFieldKey(id, KEY_RADIUS), geofence.getRadius());
+ prefs.putLong(getGeofenceFieldKey(id, KEY_EXPIRATION_DURATION),
+ geofence.getExpirationDuration());
+ prefs.putInt(getGeofenceFieldKey(id, KEY_TRANSITION_TYPE),
+ geofence.getTransitionType());
+ // Commit the changes.
+ prefs.commit();
+ }
+
+ /**
+ * Remove a flattened geofence object from storage by removing all of its keys.
+ */
+ public void clearGeofence(String id) {
+ SharedPreferences.Editor prefs = mPrefs.edit();
+ prefs.remove(getGeofenceFieldKey(id, KEY_LATITUDE));
+ prefs.remove(getGeofenceFieldKey(id, KEY_LONGITUDE));
+ prefs.remove(getGeofenceFieldKey(id, KEY_RADIUS));
+ prefs.remove(getGeofenceFieldKey(id, KEY_EXPIRATION_DURATION));
+ prefs.remove(getGeofenceFieldKey(id, KEY_TRANSITION_TYPE));
+ prefs.commit();
+ }
+
+ /**
+ * Given a Geofence object's ID and the name of a field (for example, KEY_LATITUDE), return
+ * the key name of the object's values in SharedPreferences.
+ * @param id The ID of a Geofence object.
+ * @param fieldName The field represented by the key.
+ * @return The full key name of a value in SharedPreferences.
+ */
+ private String getGeofenceFieldKey(String id, String fieldName) {
+ return KEY_PREFIX + "_" + id + "_" + fieldName;
+ }
+
+}
diff --git a/prebuilts/gradle/Geofencing/Wearable/build.gradle b/prebuilts/gradle/Geofencing/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/Geofencing/Wearable/build.gradle
+++ b/prebuilts/gradle/Geofencing/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/Geofencing/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/Geofencing/Wearable/src/main/AndroidManifest.xml
index 85c41cd..97ce90e 100644
--- a/prebuilts/gradle/Geofencing/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Geofencing/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.geofencing" >
+ package="com.example.android.wearable.geofencing" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -32,7 +32,7 @@
android:value="@integer/google_play_services_version" />
<service
- android:name="com.example.android.geofencing.HomeListenerService" >
+ android:name="com.example.android.wearable.geofencing.HomeListenerService" >
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
diff --git a/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/CheckInAndDeleteDataItemsService.java b/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/CheckInAndDeleteDataItemsService.java
new file mode 100644
index 0000000..7b8ba11
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/CheckInAndDeleteDataItemsService.java
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.Wearable;
+
+import android.app.IntentService;
+import android.app.NotificationManager;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.wearable.activity.ConfirmationActivity;
+import android.util.Log;
+
+import java.util.concurrent.TimeUnit;
+
+import static com.example.android.wearable.geofencing.Constants.ACTION_CHECK_IN;
+import static com.example.android.wearable.geofencing.Constants.ACTION_DELETE_DATA_ITEM;
+import static com.example.android.wearable.geofencing.Constants.CONNECTION_TIME_OUT_MS;
+import static com.example.android.wearable.geofencing.Constants.NOTIFICATION_ID;
+import static com.example.android.wearable.geofencing.Constants.TAG;
+
+/**
+ * Handles "Check In" action on the location-based notification. Also deletes orphan DataItems
+ * when a notification is dismissed from the wearable.
+ */
+public class CheckInAndDeleteDataItemsService extends IntentService
+ implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
+
+ private GoogleApiClient mGoogleApiClient;
+
+ public CheckInAndDeleteDataItemsService() {
+ super(CheckInAndDeleteDataItemsService.class.getSimpleName());
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ if (ACTION_CHECK_IN.equals(intent.getAction())) {
+ // In a real app, code for checking in would go here. For this sample, we will simply
+ // display a success animation.
+ startConfirmationActivity(ConfirmationActivity.SUCCESS_ANIMATION,
+ getString(R.string.check_in_success));
+ // Dismiss the check-in notification.
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID);
+ } else if (!ACTION_DELETE_DATA_ITEM.equals(intent.getAction())) {
+ // The only possible actions should be checking in or dismissing the notification
+ // (which causes an intent with ACTION_DELETE_DATA_ITEM).
+ Log.e(TAG, "Unrecognized action: " + intent.getAction());
+ return;
+ }
+ // Regardless of the action, delete the DataItem (we are only be handling intents
+ // if the notification is dismissed or if the user has chosen to check in, either of which
+ // would be completed at this point).
+ mGoogleApiClient.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
+ Uri dataItemUri = intent.getData();
+ if (mGoogleApiClient.isConnected()) {
+ DataApi.DeleteDataItemsResult result = Wearable.DataApi
+ .deleteDataItems(mGoogleApiClient, dataItemUri).await();
+ if (!result.getStatus().isSuccess()) {
+ Log.e(TAG, "CheckInAndDeleteDataItemsService.onHandleIntent: "
+ + "Failed to delete dataItem: " + dataItemUri);
+ } else if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Successfully deleted data item: " + dataItemUri);
+ }
+ } else {
+ Log.e(TAG, "Failed to delete data item: " + dataItemUri
+ + " - Client disconnected from Google Play Services");
+ }
+ mGoogleApiClient.disconnect();
+ }
+
+ /**
+ * Helper method to create confirmation animations on the wearable.
+ * @param animationType Defined by constants in ConfirmationActivity.
+ * @param message The message to display with the animation.
+ */
+ private void startConfirmationActivity(int animationType, String message) {
+ Intent confirmationActivity = new Intent(this, ConfirmationActivity.class)
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION)
+ .putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, animationType)
+ .putExtra(ConfirmationActivity.EXTRA_MESSAGE, message);
+ startActivity(confirmationActivity);
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ }
+
+}
diff --git a/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/Constants.java b/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/Constants.java
new file mode 100644
index 0000000..ef6e8c6
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/Constants.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+/** Constants used in wearable app. */
+public final class Constants {
+
+ private Constants() {
+ }
+
+ public static final String TAG = "ExampleGeofencingApp";
+
+ // Timeout for making a connection to GoogleApiClient (in milliseconds).
+ public static final long CONNECTION_TIME_OUT_MS = 100;
+
+ public static final int NOTIFICATION_ID = 1;
+ public static final String ANDROID_BUILDING_ID = "1";
+ public static final String YERBA_BUENA_ID = "2";
+
+ public static final String ACTION_CHECK_IN = "check_in";
+ public static final String ACTION_DELETE_DATA_ITEM = "delete_data_item";
+ public static final String KEY_GEOFENCE_ID = "geofence_id";
+
+}
diff --git a/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/HomeListenerService.java b/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/HomeListenerService.java
new file mode 100644
index 0000000..415fc46
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/Wearable/src/main/java/com/example/android/wearable/geofencing/HomeListenerService.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.geofencing;
+
+import static com.example.android.wearable.geofencing.Constants.ACTION_CHECK_IN;
+import static com.example.android.wearable.geofencing.Constants.ACTION_DELETE_DATA_ITEM;
+import static com.example.android.wearable.geofencing.Constants.ANDROID_BUILDING_ID;
+import static com.example.android.wearable.geofencing.Constants.KEY_GEOFENCE_ID;
+import static com.example.android.wearable.geofencing.Constants.NOTIFICATION_ID;
+import static com.example.android.wearable.geofencing.Constants.TAG;
+import static com.example.android.wearable.geofencing.Constants.YERBA_BUENA_ID;
+
+import android.app.Notification;
+import android.app.Notification.Action;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.net.Uri;
+import android.text.Spannable;
+import android.text.SpannableString;
+import android.text.style.RelativeSizeSpan;
+import android.util.Log;
+
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.DataItem;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.Wearable;
+import com.google.android.gms.wearable.WearableListenerService;
+
+/**
+ * Listens to DataItem events on the wearable device.
+ */
+public class HomeListenerService extends WearableListenerService {
+
+ private GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this.getApplicationContext())
+ .addApi(Wearable.API)
+ .build();
+ mGoogleApiClient.connect();
+ }
+
+ /**
+ * Listen for DataItems added/deleted from the geofence service running on the companion.
+ */
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onDataChanged: " + dataEvents + " for " + getPackageName());
+ }
+ for (DataEvent event : dataEvents) {
+ if (event.getType() == DataEvent.TYPE_DELETED) {
+ cancelNotificationForDataItem(event.getDataItem());
+ } else if (event.getType() == DataEvent.TYPE_CHANGED) {
+ // The user has entered a geofence - post a notification!
+ String geofenceId = DataMap.fromByteArray(event.getDataItem().getData())
+ .getString(KEY_GEOFENCE_ID);
+ postNotificationForGeofenceId(geofenceId, event.getDataItem().getUri());
+ }
+ }
+ dataEvents.close();
+ }
+
+ /**
+ * Deletes the check-in notification when the DataItem is deleted.
+ * @param dataItem Used only for logging in this sample, but could be used to identify which
+ * notification to cancel (in this case, there is at most 1 notification).
+ */
+ private void cancelNotificationForDataItem(DataItem dataItem) {
+ if (Log.isLoggable(TAG, Log.VERBOSE)) {
+ Log.v(TAG, "onDataItemDeleted:DataItem=" + dataItem.getUri());
+ }
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID);
+ }
+
+ /**
+ * Posts a local notification for the given geofence id, with an option to check in.
+ * @param geofenceId The geofence id that the user has triggered.
+ * @param dataItemUri The Uri for the DataItem that triggered this notification. Used to delete
+ * this DataItem when the notification is dismissed.
+ */
+ private void postNotificationForGeofenceId(String geofenceId, Uri dataItemUri) {
+ // Use the geofenceId to determine the title and background of the check-in notification.
+ // A SpannableString is used for the notification title for resizing capabilities.
+ SpannableString checkInTitle;
+ Bitmap notificationBackground;
+ if (ANDROID_BUILDING_ID.equals(geofenceId)) {
+ checkInTitle = new SpannableString(getText(R.string.android_building_title));
+ notificationBackground =
+ BitmapFactory.decodeResource(getResources(), R.drawable.android_building);
+ } else if (YERBA_BUENA_ID.equals(geofenceId)) {
+ checkInTitle = new SpannableString(getText(R.string.yerba_buena_title));
+ notificationBackground =
+ BitmapFactory.decodeResource(getResources(), R.drawable.yerba_buena);
+ } else {
+ Log.e(TAG, "Unrecognized geofence id: " + geofenceId);
+ return;
+ }
+ // Resize the title to avoid truncation.
+ checkInTitle.setSpan(new RelativeSizeSpan(0.8f), 0, checkInTitle.length(),
+ Spannable.SPAN_POINT_MARK);
+
+ Intent checkInOperation =
+ new Intent(this, CheckInAndDeleteDataItemsService.class).setData(dataItemUri);
+ PendingIntent checkInIntent = PendingIntent.getService(this, 0,
+ checkInOperation.setAction(ACTION_CHECK_IN), PendingIntent.FLAG_CANCEL_CURRENT);
+ PendingIntent deleteDataItemIntent = PendingIntent.getService(this, 1,
+ checkInOperation.setAction(ACTION_DELETE_DATA_ITEM),
+ PendingIntent.FLAG_CANCEL_CURRENT);
+ // This action will be embedded into the notification.
+ Action checkInAction = new Action(R.drawable.ic_action_check_in,
+ getText(R.string.check_in_prompt), checkInIntent);
+
+ Notification notification = new Notification.Builder(this)
+ .setContentTitle(checkInTitle)
+ .setContentText(getText(R.string.check_in_prompt))
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setDeleteIntent(deleteDataItemIntent)
+ .extend(new Notification.WearableExtender()
+ .setBackground(notificationBackground)
+ .addAction(checkInAction)
+ .setContentAction(0)
+ .setHintHideIcon(true))
+ .setLocalOnly(true)
+ .build();
+
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(NOTIFICATION_ID, notification);
+ }
+
+}
diff --git a/prebuilts/gradle/Geofencing/screenshots/android_building_check_in.png b/prebuilts/gradle/Geofencing/screenshots/android_building_check_in.png
new file mode 100644
index 0000000..5101e77
--- /dev/null
+++ b/prebuilts/gradle/Geofencing/screenshots/android_building_check_in.png
Binary files differ
diff --git a/prebuilts/gradle/Geofencing/settings.gradle b/prebuilts/gradle/Geofencing/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/Geofencing/settings.gradle
+++ b/prebuilts/gradle/Geofencing/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/GridViewPager/Application/build.gradle b/prebuilts/gradle/GridViewPager/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/GridViewPager/Application/build.gradle
+++ b/prebuilts/gradle/GridViewPager/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/GridViewPager/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/GridViewPager/Application/src/main/AndroidManifest.xml
index eaa91d7..add48f1 100644
--- a/prebuilts/gradle/GridViewPager/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/GridViewPager/Application/src/main/AndroidManifest.xml
@@ -16,10 +16,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.gridviewpager">
+ package="com.example.android.wearable.gridviewpager">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application android:allowBackup="true"
android:label="@string/app_name">
diff --git a/prebuilts/gradle/GridViewPager/Wearable/build.gradle b/prebuilts/gradle/GridViewPager/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/GridViewPager/Wearable/build.gradle
+++ b/prebuilts/gradle/GridViewPager/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/GridViewPager/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/GridViewPager/Wearable/src/main/AndroidManifest.xml
index baadee2..3f9c4b1 100644
--- a/prebuilts/gradle/GridViewPager/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/GridViewPager/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.gridviewpager" >
+ package="com.example.android.wearable.gridviewpager" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -28,7 +28,7 @@
android:label="@string/app_name"
android:theme="@android:style/Theme.DeviceDefault.Light" >
<activity
- android:name="com.example.android.gridviewpager.MainActivity"
+ android:name="com.example.android.wearable.gridviewpager.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
diff --git a/prebuilts/gradle/GridViewPager/Wearable/src/main/java/com/example/android/wearable/gridviewpager/MainActivity.java b/prebuilts/gradle/GridViewPager/Wearable/src/main/java/com/example/android/wearable/gridviewpager/MainActivity.java
new file mode 100644
index 0000000..20751a3
--- /dev/null
+++ b/prebuilts/gradle/GridViewPager/Wearable/src/main/java/com/example/android/wearable/gridviewpager/MainActivity.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.gridviewpager;
+
+import android.app.Activity;
+import android.content.res.Resources;
+import android.os.Bundle;
+import android.support.wearable.view.GridViewPager;
+import android.view.View;
+import android.view.View.OnApplyWindowInsetsListener;
+import android.view.WindowInsets;
+
+public class MainActivity extends Activity {
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+ final Resources res = getResources();
+ final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
+ pager.setOnApplyWindowInsetsListener(new OnApplyWindowInsetsListener() {
+ @Override
+ public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
+ // Adjust page margins:
+ // A little extra horizontal spacing between pages looks a bit
+ // less crowded on a round display.
+ final boolean round = insets.isRound();
+ int rowMargin = res.getDimensionPixelOffset(R.dimen.page_row_margin);
+ int colMargin = res.getDimensionPixelOffset(round ?
+ R.dimen.page_column_margin_round : R.dimen.page_column_margin);
+ pager.setPageMargins(rowMargin, colMargin);
+
+ // GridViewPager relies on insets to properly handle
+ // layout for round displays. They must be explicitly
+ // applied since this listener has taken them over.
+ pager.onApplyWindowInsets(insets);
+ return insets;
+ }
+ });
+ pager.setAdapter(new SampleGridPagerAdapter(this, getFragmentManager()));
+ }
+}
diff --git a/prebuilts/gradle/GridViewPager/Wearable/src/main/java/com/example/android/wearable/gridviewpager/SampleGridPagerAdapter.java b/prebuilts/gradle/GridViewPager/Wearable/src/main/java/com/example/android/wearable/gridviewpager/SampleGridPagerAdapter.java
new file mode 100644
index 0000000..8f9bcf9
--- /dev/null
+++ b/prebuilts/gradle/GridViewPager/Wearable/src/main/java/com/example/android/wearable/gridviewpager/SampleGridPagerAdapter.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.gridviewpager;
+
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.content.Context;
+import android.support.wearable.view.CardFragment;
+import android.support.wearable.view.FragmentGridPagerAdapter;
+import android.support.wearable.view.ImageReference;
+import android.view.Gravity;
+
+/**
+ * Constructs fragments as requested by the GridViewPager. For each row a
+ * different background is provided.
+ */
+public class SampleGridPagerAdapter extends FragmentGridPagerAdapter {
+
+ private final Context mContext;
+
+ public SampleGridPagerAdapter(Context ctx, FragmentManager fm) {
+ super(fm);
+ mContext = ctx;
+ }
+
+ static final int[] BG_IMAGES = new int[] {
+ R.drawable.debug_background_1,
+ R.drawable.debug_background_2,
+ R.drawable.debug_background_3,
+ R.drawable.debug_background_4,
+ R.drawable.debug_background_5
+ };
+
+ /** A simple container for static data in each page */
+ private static class Page {
+ int titleRes;
+ int textRes;
+ int iconRes;
+ int cardGravity = Gravity.BOTTOM;
+ boolean expansionEnabled = true;
+ float expansionFactor = 1.0f;
+ int expansionDirection = CardFragment.EXPAND_DOWN;
+
+ public Page(int titleRes, int textRes, boolean expansion) {
+ this(titleRes, textRes, 0);
+ this.expansionEnabled = expansion;
+ }
+
+ public Page(int titleRes, int textRes, boolean expansion, float expansionFactor) {
+ this(titleRes, textRes, 0);
+ this.expansionEnabled = expansion;
+ this.expansionFactor = expansionFactor;
+ }
+
+ public Page(int titleRes, int textRes, int iconRes) {
+ this.titleRes = titleRes;
+ this.textRes = textRes;
+ this.iconRes = iconRes;
+ }
+
+ public Page(int titleRes, int textRes, int iconRes, int gravity) {
+ this.titleRes = titleRes;
+ this.textRes = textRes;
+ this.iconRes = iconRes;
+ this.cardGravity = gravity;
+ }
+ }
+
+ private final Page[][] PAGES = {
+ {
+ new Page(R.string.welcome_title, R.string.welcome_text, R.drawable.bugdroid,
+ Gravity.CENTER_VERTICAL),
+ },
+ {
+ new Page(R.string.about_title, R.string.about_text, false),
+ },
+ {
+ new Page(R.string.cards_title, R.string.cards_text, true, 2),
+ new Page(R.string.expansion_title, R.string.expansion_text, true, 10),
+ },
+ {
+ new Page(R.string.backgrounds_title, R.string.backgrounds_text, true, 2),
+ new Page(R.string.columns_title, R.string.columns_text, true, 2)
+ },
+ {
+ new Page(R.string.dismiss_title, R.string.dismiss_text, R.drawable.bugdroid,
+ Gravity.CENTER_VERTICAL),
+ },
+
+ };
+
+ @Override
+ public Fragment getFragment(int row, int col) {
+ Page page = PAGES[row][col];
+ String title = page.titleRes != 0 ? mContext.getString(page.titleRes) : null;
+ String text = page.textRes != 0 ? mContext.getString(page.textRes) : null;
+ CardFragment fragment = CardFragment.create(title, text, page.iconRes);
+ // Advanced settings
+ fragment.setCardGravity(page.cardGravity);
+ fragment.setExpansionEnabled(page.expansionEnabled);
+ fragment.setExpansionDirection(page.expansionDirection);
+ fragment.setExpansionFactor(page.expansionFactor);
+ return fragment;
+ }
+
+ @Override
+ public ImageReference getBackground(int row, int column) {
+ return ImageReference.forDrawable(BG_IMAGES[row % BG_IMAGES.length]);
+ }
+
+ @Override
+ public int getRowCount() {
+ return PAGES.length;
+ }
+
+ @Override
+ public int getColumnCount(int rowNum) {
+ return PAGES[rowNum].length;
+ }
+}
diff --git a/prebuilts/gradle/GridViewPager/screenshots/grid_view_pager.gif b/prebuilts/gradle/GridViewPager/screenshots/grid_view_pager.gif
new file mode 100644
index 0000000..f70dafc
--- /dev/null
+++ b/prebuilts/gradle/GridViewPager/screenshots/grid_view_pager.gif
Binary files differ
diff --git a/prebuilts/gradle/GridViewPager/settings.gradle b/prebuilts/gradle/GridViewPager/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/GridViewPager/settings.gradle
+++ b/prebuilts/gradle/GridViewPager/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/ImmersiveMode/Application/build.gradle b/prebuilts/gradle/ImmersiveMode/Application/build.gradle
index 78ae552..bd1120c 100644
--- a/prebuilts/gradle/ImmersiveMode/Application/build.gradle
+++ b/prebuilts/gradle/ImmersiveMode/Application/build.gradle
@@ -26,12 +26,12 @@
'template'] // boilerplate code that is generated by the sample template process
android {
- compileSdkVersion 19
+ compileSdkVersion 21
buildToolsVersion "21.0.0"
defaultConfig {
minSdkVersion 4
- targetSdkVersion 19
+ targetSdkVersion 21
}
sourceSets {
diff --git a/prebuilts/gradle/JobScheduler/Application/src/main/java/com/example/android/jobscheduler/MainActivity.java b/prebuilts/gradle/JobScheduler/Application/src/main/java/com/example/android/jobscheduler/MainActivity.java
index f495bf1..624e22d 100644
--- a/prebuilts/gradle/JobScheduler/Application/src/main/java/com/example/android/jobscheduler/MainActivity.java
+++ b/prebuilts/gradle/JobScheduler/Application/src/main/java/com/example/android/jobscheduler/MainActivity.java
@@ -140,9 +140,9 @@
boolean requiresUnmetered = mWiFiConnectivityRadioButton.isChecked();
boolean requiresAnyConnectivity = mAnyConnectivityRadioButton.isChecked();
if (requiresUnmetered) {
- builder.setRequiredNetworkCapabilities(JobInfo.NetworkType.UNMETERED);
+ builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
} else if (requiresAnyConnectivity) {
- builder.setRequiredNetworkCapabilities(JobInfo.NetworkType.ANY);
+ builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
}
builder.setRequiresDeviceIdle(mRequiresIdleCheckbox.isChecked());
builder.setRequiresCharging(mRequiresChargingCheckBox.isChecked());
diff --git a/prebuilts/gradle/JumpingJack/Application/build.gradle b/prebuilts/gradle/JumpingJack/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/JumpingJack/Application/build.gradle
+++ b/prebuilts/gradle/JumpingJack/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/JumpingJack/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/JumpingJack/Application/src/main/AndroidManifest.xml
index 652f895..f7a0efd 100644
--- a/prebuilts/gradle/JumpingJack/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/JumpingJack/Application/src/main/AndroidManifest.xml
@@ -16,10 +16,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.jumpingjack">
+ package="com.example.android.wearable.jumpingjack">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application android:allowBackup="true"
android:label="@string/app_name">
diff --git a/prebuilts/gradle/JumpingJack/Wearable/build.gradle b/prebuilts/gradle/JumpingJack/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/JumpingJack/Wearable/build.gradle
+++ b/prebuilts/gradle/JumpingJack/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/JumpingJack/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/JumpingJack/Wearable/src/main/AndroidManifest.xml
index e0448d9..f123f77 100644
--- a/prebuilts/gradle/JumpingJack/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/JumpingJack/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.jumpingjack">
+ package="com.example.android.wearable.jumpingjack">
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
diff --git a/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/MainActivity.java b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/MainActivity.java
new file mode 100644
index 0000000..cdaaf6e
--- /dev/null
+++ b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/MainActivity.java
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
+ *
+ * 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.example.android.wearable.jumpingjack;
+
+import com.example.android.wearable.jumpingjack.fragments.CounterFragment;
+import com.example.android.wearable.jumpingjack.fragments.SettingsFragment;
+
+import android.app.Activity;
+import android.content.Context;
+import android.hardware.Sensor;
+import android.hardware.SensorEvent;
+import android.hardware.SensorEventListener;
+import android.hardware.SensorManager;
+import android.os.Bundle;
+import android.os.Handler;
+import android.support.v4.view.ViewPager;
+import android.util.Log;
+import android.view.WindowManager;
+import android.widget.ImageView;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+/**
+ * The main activity for the Jumping Jack application. This activity registers itself to receive
+ * sensor values. Since on wearable devices a full screen activity is very short-lived, we set the
+ * FLAG_KEEP_SCREEN_ON to give user adequate time for taking actions but since we don't want to
+ * keep screen on for an extended period of time, there is a SCREEN_ON_TIMEOUT_MS that is enforced
+ * if no interaction is discovered.
+ *
+ * This activity includes a {@link android.support.v4.view.ViewPager} with two pages, one that
+ * shows the current count and one that allows user to reset the counter. the current value of the
+ * counter is persisted so that upon re-launch, the counter picks up from the last value. At any
+ * stage, user can set this counter to 0.
+ */
+public class MainActivity extends Activity
+ implements SensorEventListener {
+
+ private static final String TAG = "JJMainActivity";
+
+ /** How long to keep the screen on when no activity is happening **/
+ private static final long SCREEN_ON_TIMEOUT_MS = 20000; // in milliseconds
+
+ /** an up-down movement that takes more than this will not be registered as such **/
+ private static final long TIME_THRESHOLD_NS = 2000000000; // in nanoseconds (= 2sec)
+
+ /**
+ * Earth gravity is around 9.8 m/s^2 but user may not completely direct his/her hand vertical
+ * during the exercise so we leave some room. Basically if the x-component of gravity, as
+ * measured by the Gravity sensor, changes with a variation (delta) > GRAVITY_THRESHOLD,
+ * we consider that a successful count.
+ */
+ private static final float GRAVITY_THRESHOLD = 7.0f;
+
+ private SensorManager mSensorManager;
+ private Sensor mSensor;
+ private long mLastTime = 0;
+ private boolean mUp = false;
+ private int mJumpCounter = 0;
+ private ViewPager mPager;
+ private CounterFragment mCounterPage;
+ private SettingsFragment mSettingPage;
+ private ImageView mSecondIndicator;
+ private ImageView mFirstIndicator;
+ private Timer mTimer;
+ private TimerTask mTimerTask;
+ private Handler mHandler;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.jj_layout);
+ setupViews();
+ mHandler = new Handler();
+ mJumpCounter = Utils.getCounterFromPreference(this);
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ renewTimer();
+ mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
+ mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
+ }
+
+ private void setupViews() {
+ mPager = (ViewPager) findViewById(R.id.pager);
+ mFirstIndicator = (ImageView) findViewById(R.id.indicator_0);
+ mSecondIndicator = (ImageView) findViewById(R.id.indicator_1);
+ final PagerAdapter adapter = new PagerAdapter(getFragmentManager());
+ mCounterPage = new CounterFragment();
+ mSettingPage = new SettingsFragment(this);
+ adapter.addFragment(mCounterPage);
+ adapter.addFragment(mSettingPage);
+ setIndicator(0);
+ mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
+ @Override
+ public void onPageScrolled(int i, float v, int i2) {
+ }
+
+ @Override
+ public void onPageSelected(int i) {
+ setIndicator(i);
+ renewTimer();
+ }
+
+ @Override
+ public void onPageScrollStateChanged(int i) {
+ }
+ });
+
+ mPager.setAdapter(adapter);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (mSensorManager.registerListener(this, mSensor,
+ SensorManager.SENSOR_DELAY_NORMAL)) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Successfully registered for the sensor updates");
+ }
+ }
+ }
+
+ @Override
+ protected void onPause() {
+ super.onPause();
+ mSensorManager.unregisterListener(this);
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Unregistered for sensor events");
+ }
+ }
+
+ @Override
+ public void onSensorChanged(SensorEvent event) {
+ detectJump(event.values[0], event.timestamp);
+ }
+
+ @Override
+ public void onAccuracyChanged(Sensor sensor, int accuracy) {
+ }
+
+ /**
+ * A simple algorithm to detect a successful up-down movement of hand(s). The algorithm is
+ * based on the assumption that when a person is wearing the watch, the x-component of gravity
+ * as measured by the Gravity Sensor is +9.8 when the hand is downward and -9.8 when the hand
+ * is upward (signs are reversed if the watch is worn on the right hand). Since the upward or
+ * downward may not be completely accurate, we leave some room and instead of 9.8, we use
+ * GRAVITY_THRESHOLD. We also consider the up <-> down movement successful if it takes less than
+ * TIME_THRESHOLD_NS.
+ */
+ private void detectJump(float xValue, long timestamp) {
+ if ((Math.abs(xValue) > GRAVITY_THRESHOLD)) {
+ if(timestamp - mLastTime < TIME_THRESHOLD_NS && mUp != (xValue > 0)) {
+ onJumpDetected(!mUp);
+ }
+ mUp = xValue > 0;
+ mLastTime = timestamp;
+ }
+ }
+
+ /**
+ * Called on detection of a successful down -> up or up -> down movement of hand.
+ */
+ private void onJumpDetected(boolean up) {
+ // we only count a pair of up and down as one successful movement
+ if (up) {
+ return;
+ }
+ mJumpCounter++;
+ setCounter(mJumpCounter);
+ renewTimer();
+ }
+
+ /**
+ * Updates the counter on UI, saves it to preferences and vibrates the watch when counter
+ * reaches a multiple of 10.
+ */
+ private void setCounter(int i) {
+ mCounterPage.setCounter(i);
+ Utils.saveCounterToPreference(this, i);
+ if (i > 0 && i % 10 == 0) {
+ Utils.vibrate(this, 0);
+ }
+ }
+
+ public void resetCounter() {
+ setCounter(0);
+ renewTimer();
+ }
+
+ /**
+ * Starts a timer to clear the flag FLAG_KEEP_SCREEN_ON.
+ */
+ private void renewTimer() {
+ if (null != mTimer) {
+ mTimer.cancel();
+ }
+ mTimerTask = new TimerTask() {
+ @Override
+ public void run() {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG,
+ "Removing the FLAG_KEEP_SCREEN_ON flag to allow going to background");
+ }
+ resetFlag();
+ }
+ };
+ mTimer = new Timer();
+ mTimer.schedule(mTimerTask, SCREEN_ON_TIMEOUT_MS);
+ }
+
+ /**
+ * Resets the FLAG_KEEP_SCREEN_ON flag so activity can go into background.
+ */
+ private void resetFlag() {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Resetting FLAG_KEEP_SCREEN_ON flag to allow going to background");
+ }
+ getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ finish();
+ }
+ });
+ }
+
+ /**
+ * Sets the page indicator for the ViewPager.
+ */
+ private void setIndicator(int i) {
+ switch (i) {
+ case 0:
+ mFirstIndicator.setImageResource(R.drawable.full_10);
+ mSecondIndicator.setImageResource(R.drawable.empty_10);
+ break;
+ case 1:
+ mFirstIndicator.setImageResource(R.drawable.empty_10);
+ mSecondIndicator.setImageResource(R.drawable.full_10);
+ break;
+ }
+ }
+
+
+}
diff --git a/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/PagerAdapter.java b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/PagerAdapter.java
new file mode 100644
index 0000000..f7ac2b0
--- /dev/null
+++ b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/PagerAdapter.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
+ *
+ * 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.example.android.wearable.jumpingjack;
+
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.support.v13.app.FragmentPagerAdapter;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * A simple adapter for the {@link android.support.v4.view.ViewPager}
+ */
+public class PagerAdapter extends FragmentPagerAdapter {
+
+ List<Fragment> mFragments = null;
+
+ public PagerAdapter(FragmentManager fm) {
+ super(fm);
+ mFragments = new ArrayList<Fragment>();
+ }
+
+ @Override
+ public Fragment getItem(int position) {
+ return mFragments.get(position);
+ }
+
+ @Override
+ public int getCount() {
+ return mFragments.size();
+ }
+
+ public void addFragment(Fragment fragment) {
+ mFragments.add(fragment);
+ notifyDataSetChanged();
+ }
+}
diff --git a/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/Utils.java b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/Utils.java
new file mode 100644
index 0000000..4db66c9
--- /dev/null
+++ b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/Utils.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
+ *
+ * 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.example.android.wearable.jumpingjack;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.os.Vibrator;
+import android.preference.PreferenceManager;
+
+/**
+ * A utility class for some helper methods.
+ */
+public class Utils {
+
+ private static final int DEFAULT_VIBRATION_DURATION_MS = 200; // in millis
+ private static final String PREF_KEY_COUNTER = "counter";
+
+ /**
+ * Causes device to vibrate for the given duration (in millis). If duration is set to 0, then it
+ * will use the <code>DEFAULT_VIBRATION_DURATION_MS</code>.
+ */
+ public final static void vibrate(Context context, int duration) {
+ if (duration == 0) {
+ duration = DEFAULT_VIBRATION_DURATION_MS;
+ }
+ Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
+ v.vibrate(duration);
+ }
+
+ /**
+ * Saves the counter value in the preference storage. If <code>value</code>
+ * is negative, then the value will be removed from the preferences.
+ */
+ public static void saveCounterToPreference(Context context, int value) {
+ SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
+ if (value < 0) {
+ // we want to remove
+ pref.edit().remove(PREF_KEY_COUNTER).apply();
+ } else {
+ pref.edit().putInt(PREF_KEY_COUNTER, value).apply();
+ }
+ }
+
+ /**
+ * Retrieves the value of counter from preference manager. If no value exists, it will return
+ * <code>0</code>.
+ */
+ public static int getCounterFromPreference(Context context) {
+ SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
+ return pref.getInt(PREF_KEY_COUNTER, 0);
+ }
+
+}
diff --git a/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/fragments/CounterFragment.java b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/fragments/CounterFragment.java
new file mode 100644
index 0000000..c55eb9b
--- /dev/null
+++ b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/fragments/CounterFragment.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
+ *
+ * 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.example.android.wearable.jumpingjack.fragments;
+
+import com.example.android.wearable.jumpingjack.R;
+import com.example.android.wearable.jumpingjack.Utils;
+
+import android.app.Fragment;
+import android.graphics.drawable.Drawable;
+import android.os.Bundle;
+import android.os.Handler;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import java.util.Timer;
+import java.util.TimerTask;
+
+/**
+ * A simple fragment for showing the count
+ */
+public class CounterFragment extends Fragment {
+
+ private static final long ANIMATION_INTERVAL_MS = 500; // in milliseconds
+ private TextView mCounterText;
+ private Timer mAnimationTimer;
+ private Handler mHandler;
+ private TimerTask mAnimationTask;
+ private boolean up = false;
+ private Drawable mDownDrawable;
+ private Drawable mUpDrawable;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.counter_layout, container, false);
+ mDownDrawable = getResources().getDrawable(R.drawable.jump_down_50);
+ mUpDrawable = getResources().getDrawable(R.drawable.jump_up_50);
+ mCounterText = (TextView) view.findViewById(R.id.counter);
+ mCounterText.setCompoundDrawablesWithIntrinsicBounds(mUpDrawable, null, null, null);
+ setCounter(Utils.getCounterFromPreference(getActivity()));
+ mHandler = new Handler();
+ startAnimation();
+ return view;
+ }
+
+ private void startAnimation() {
+ mAnimationTask = new TimerTask() {
+ @Override
+ public void run() {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mCounterText.setCompoundDrawablesWithIntrinsicBounds(
+ up ? mUpDrawable : mDownDrawable, null, null, null);
+ up = !up;
+ }
+ });
+ }
+ };
+ mAnimationTimer = new Timer();
+ mAnimationTimer.scheduleAtFixedRate(mAnimationTask, ANIMATION_INTERVAL_MS,
+ ANIMATION_INTERVAL_MS);
+ }
+
+ public void setCounter(String text) {
+ mCounterText.setText(text);
+ }
+
+ public void setCounter(int i) {
+ setCounter(i < 0 ? "0" : String.valueOf(i));
+ }
+
+ @Override
+ public void onDetach() {
+ mAnimationTimer.cancel();
+ super.onDetach();
+ }
+}
diff --git a/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/fragments/SettingsFragment.java b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/fragments/SettingsFragment.java
new file mode 100644
index 0000000..fffe8fb
--- /dev/null
+++ b/prebuilts/gradle/JumpingJack/Wearable/src/main/java/com/example/android/wearable/jumpingjack/fragments/SettingsFragment.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2014 Google Inc. All Rights Reserved.
+ *
+ * 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.example.android.wearable.jumpingjack.fragments;
+
+import com.example.android.wearable.jumpingjack.MainActivity;
+import com.example.android.wearable.jumpingjack.R;
+
+import android.app.Fragment;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+
+/**
+ * A simple fragment that shows a button to reset the counter
+ */
+public class SettingsFragment extends Fragment {
+
+ private Button mButton;
+ private MainActivity mMainActivity;
+
+ public SettingsFragment(MainActivity mainActivity) {
+ mMainActivity = mainActivity;
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.setting_layout, container, false);
+ mButton = (Button) view.findViewById(R.id.btn);
+ mButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ mMainActivity.resetCounter();
+ }
+ });
+ return view;
+ }
+
+}
diff --git a/prebuilts/gradle/JumpingJack/screenshots/jumping_jack.gif b/prebuilts/gradle/JumpingJack/screenshots/jumping_jack.gif
new file mode 100644
index 0000000..86c4faa
--- /dev/null
+++ b/prebuilts/gradle/JumpingJack/screenshots/jumping_jack.gif
Binary files differ
diff --git a/prebuilts/gradle/JumpingJack/settings.gradle b/prebuilts/gradle/JumpingJack/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/JumpingJack/settings.gradle
+++ b/prebuilts/gradle/JumpingJack/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/AndroidManifest.xml b/prebuilts/gradle/MediaEffects/Application/src/main/AndroidManifest.xml
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/AndroidManifest.xml
rename to prebuilts/gradle/MediaEffects/Application/src/main/AndroidManifest.xml
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/java/com/example/android/mediaeffects/GLToolbox.java b/prebuilts/gradle/MediaEffects/Application/src/main/java/com/example/android/mediaeffects/GLToolbox.java
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/java/com/example/android/mediaeffects/GLToolbox.java
rename to prebuilts/gradle/MediaEffects/Application/src/main/java/com/example/android/mediaeffects/GLToolbox.java
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/java/com/example/android/mediaeffects/MediaEffectsFragment.java b/prebuilts/gradle/MediaEffects/Application/src/main/java/com/example/android/mediaeffects/MediaEffectsFragment.java
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/java/com/example/android/mediaeffects/MediaEffectsFragment.java
rename to prebuilts/gradle/MediaEffects/Application/src/main/java/com/example/android/mediaeffects/MediaEffectsFragment.java
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/java/com/example/android/mediaeffects/TextureRenderer.java b/prebuilts/gradle/MediaEffects/Application/src/main/java/com/example/android/mediaeffects/TextureRenderer.java
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/java/com/example/android/mediaeffects/TextureRenderer.java
rename to prebuilts/gradle/MediaEffects/Application/src/main/java/com/example/android/mediaeffects/TextureRenderer.java
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-hdpi/ic_launcher.png b/prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-hdpi/ic_launcher.png
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-hdpi/ic_launcher.png
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-mdpi/ic_launcher.png b/prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-mdpi/ic_launcher.png
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-mdpi/ic_launcher.png
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-nodpi/puppy.jpg b/prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-nodpi/puppy.jpg
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-nodpi/puppy.jpg
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-nodpi/puppy.jpg
Binary files differ
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-xhdpi/ic_launcher.png b/prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-xhdpi/ic_launcher.png
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-xhdpi/ic_launcher.png
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-xxhdpi/ic_launcher.png b/prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/drawable-xxhdpi/ic_launcher.png
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/layout/fragment_media_effects.xml b/prebuilts/gradle/MediaEffects/Application/src/main/res/layout/fragment_media_effects.xml
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/layout/fragment_media_effects.xml
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/layout/fragment_media_effects.xml
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/menu/media_effects.xml b/prebuilts/gradle/MediaEffects/Application/src/main/res/menu/media_effects.xml
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/menu/media_effects.xml
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/menu/media_effects.xml
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/values/strings.xml b/prebuilts/gradle/MediaEffects/Application/src/main/res/values/strings.xml
similarity index 100%
rename from prebuilts/gradle/MediaEffects/MediaEffectsSample/src/main/res/values/strings.xml
rename to prebuilts/gradle/MediaEffects/Application/src/main/res/values/strings.xml
diff --git a/prebuilts/gradle/MediaEffects/MediaEffectsSample/README-fragmentview.txt b/prebuilts/gradle/MediaEffects/MediaEffectsSample/README-fragmentview.txt
deleted file mode 100644
index 8853b23..0000000
--- a/prebuilts/gradle/MediaEffects/MediaEffectsSample/README-fragmentview.txt
+++ /dev/null
@@ -1,37 +0,0 @@
-<!--
- Copyright 2014 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.
--->
-
-Steps to implement FragmentView template:
--in template-params.xml.ftl:
- -add the following line to common imports
- <common src="activities"/>
-
--Add a Fragment to show behavior. In your MainActivity.java class, it will reference a Fragment
- called (yourProjectName)Fragment.java. Create that file in your project, using the "main" source
- folder instead of "common" or "templates".
- For instance, if your package name is com.example.foo, create the file
- src/main/java/com/example/foo/FooFragment.java
-
-
--Within this fragment, make sure that the onCreate method has the line
- "setHasOptionsMenu(true);", to enable the fragment to handle menu events.
-
--In order to override menu events, override onOptionsItemSelected.
-
--refer to sampleSamples/fragmentViewSample for a reference implementation of a
-project built on this template.
-
-
diff --git a/prebuilts/gradle/MediaEffects/settings.gradle b/prebuilts/gradle/MediaEffects/settings.gradle
index f678548..9464a35 100644
--- a/prebuilts/gradle/MediaEffects/settings.gradle
+++ b/prebuilts/gradle/MediaEffects/settings.gradle
@@ -1,4 +1 @@
-
-
-
-include 'MediaEffectsSample'
+include 'Application'
diff --git a/prebuilts/gradle/DocumentCentricApps/Application/Application.iml b/prebuilts/gradle/NavigationDrawer/Application/Application.iml
similarity index 88%
rename from prebuilts/gradle/DocumentCentricApps/Application/Application.iml
rename to prebuilts/gradle/NavigationDrawer/Application/Application.iml
index 1bed7be..0019769 100644
--- a/prebuilts/gradle/DocumentCentricApps/Application/Application.iml
+++ b/prebuilts/gradle/NavigationDrawer/Application/Application.iml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="DocumentCentricApps" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="NavigationDrawer" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android-gradle" name="Android-Gradle">
<configuration>
@@ -13,6 +13,7 @@
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugJava" />
<option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />
<option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
+ <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
@@ -37,8 +38,8 @@
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
@@ -46,8 +47,8 @@
<sourceFolder url="file://$MODULE_DIR$/src/common/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/template/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/common/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/template/java" isTestSource="false" />
@@ -55,8 +56,8 @@
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/tests/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/tests/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/tests/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/tests/aidl" isTestSource="true" />
- <sourceFolder url="file://$MODULE_DIR$/tests/assets" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests/src" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests/rs" isTestSource="true" />
@@ -83,10 +84,11 @@
</content>
<orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
- <orderEntry type="library" exported="" name="support-annotations-21.0.0-rc1" level="project" />
- <orderEntry type="library" exported="" name="support-v4-21.0.0-rc1" level="project" />
- <orderEntry type="library" exported="" name="cardview-v7-21.0.0-rc1" level="project" />
- <orderEntry type="library" exported="" name="support-v13-21.0.0-rc1" level="project" />
+ <orderEntry type="library" exported="" name="support-v13-20.0.0" level="project" />
+ <orderEntry type="library" exported="" name="recyclerview-v7-21.0.0" level="project" />
+ <orderEntry type="library" exported="" name="support-annotations-21.0.0" level="project" />
+ <orderEntry type="library" exported="" name="support-v4-21.0.0" level="project" />
+ <orderEntry type="library" exported="" name="appcompat-v7-20.0.0" level="project" />
</component>
</module>
diff --git a/prebuilts/gradle/NavigationDrawer/Application/build.gradle b/prebuilts/gradle/NavigationDrawer/Application/build.gradle
index 4378338..a9e6534 100644
--- a/prebuilts/gradle/NavigationDrawer/Application/build.gradle
+++ b/prebuilts/gradle/NavigationDrawer/Application/build.gradle
@@ -17,6 +17,7 @@
compile "com.android.support:support-v13:20.+"
compile "com.android.support:appcompat-v7:20.+"
compile "com.android.support:recyclerview-v7:+"
+ compile "com.android.support:cardview-v7:21.+"
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/NavigationDrawer/Application/src/main/res/values/template-attrs.xml b/prebuilts/gradle/NavigationDrawer/Application/src/main/res/values/template-attrs.xml
new file mode 100644
index 0000000..442ed77
--- /dev/null
+++ b/prebuilts/gradle/NavigationDrawer/Application/src/main/res/values/template-attrs.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2014 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.
+-->
+
+<resources>
+</resources>
\ No newline at end of file
diff --git a/prebuilts/gradle/Notifications/Application/build.gradle b/prebuilts/gradle/Notifications/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/Notifications/Application/build.gradle
+++ b/prebuilts/gradle/Notifications/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/Notifications/Application/src/main/AndroidManifest.xml
index 005d745..c7b2da7 100644
--- a/prebuilts/gradle/Notifications/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Notifications/Application/src/main/AndroidManifest.xml
@@ -15,11 +15,11 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.notifications" >
+ package="com.example.android.support.wearable.notifications" >
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application
android:allowBackup="true"
@@ -40,9 +40,9 @@
<receiver android:name=".NotificationIntentReceiver"
android:exported="false">
<intent-filter>
- <action android:name="com.example.android.notifications.ACTION_EXAMPLE" />
- <action android:name="com.example.android.notifications.ACTION_ENABLE_MESSAGES" />
- <action android:name="com.example.android.notifications.ACTION_DISABLE_MESSAGES" />
+ <action android:name="com.example.android.support.wearable.notifications.ACTION_EXAMPLE" />
+ <action android:name="com.example.android.support.wearable.notifications.ACTION_ENABLE_MESSAGES" />
+ <action android:name="com.example.android.support.wearable.notifications.ACTION_DISABLE_MESSAGES" />
</intent-filter>
</receiver>
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/ActionsPreset.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/ActionsPreset.java
new file mode 100644
index 0000000..a550912
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/ActionsPreset.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.content.Context;
+import android.support.v4.app.NotificationCompat;
+
+/**
+ * Base class for notification actions presets.
+ */
+public abstract class ActionsPreset extends NamedPreset {
+ public ActionsPreset(int nameResId) {
+ super(nameResId);
+ }
+
+ /** Apply the priority to a notification builder */
+ public abstract void apply(Context context, NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions);
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/ActionsPresets.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/ActionsPresets.java
new file mode 100644
index 0000000..ff639dc
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/ActionsPresets.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.content.Context;
+import android.support.v4.app.NotificationCompat;
+import android.support.v4.app.RemoteInput;
+
+/**
+ * Collection of notification actions presets.
+ */
+public class ActionsPresets {
+ public static final ActionsPreset NO_ACTIONS_PRESET = new NoActionsPreset();
+ public static final ActionsPreset SINGLE_ACTION_PRESET = new SingleActionPreset();
+
+ public static final ActionsPreset[] PRESETS = new ActionsPreset[] {
+ NO_ACTIONS_PRESET,
+ SINGLE_ACTION_PRESET,
+ new ReplyActionPreset(),
+ new ReplyWithChoicesActionPreset(),
+ new DifferentActionsOnPhoneAndWearable(),
+ new LongTitleActionPreset()
+ };
+
+ private static class NoActionsPreset extends ActionsPreset {
+ public NoActionsPreset() {
+ super(R.string.no_actions);
+ }
+
+ @Override
+ public void apply(Context context, NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions) {
+ }
+ }
+
+ private static class SingleActionPreset extends ActionsPreset {
+ public SingleActionPreset() {
+ super(R.string.single_action);
+ }
+
+ @Override
+ public void apply(Context context, NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions) {
+ builder.addAction(R.drawable.ic_full_action,
+ context.getString(R.string.example_action),
+ NotificationUtil.getExamplePendingIntent(context,
+ R.string.example_action_clicked))
+ .build();
+ }
+ }
+
+ private static class LongTitleActionPreset extends ActionsPreset {
+ public LongTitleActionPreset() {
+ super(R.string.long_title_action);
+ }
+
+ @Override
+ public void apply(Context context, NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions) {
+ builder.addAction(R.drawable.ic_full_action,
+ context.getString(R.string.example_action_long_title),
+ NotificationUtil.getExamplePendingIntent(context,
+ R.string.example_action_clicked))
+ .build();
+ }
+ }
+
+ private static class ReplyActionPreset extends ActionsPreset {
+ public ReplyActionPreset() {
+ super(R.string.reply_action);
+ }
+
+ @Override
+ public void apply(Context context, NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions) {
+ RemoteInput remoteInput = new RemoteInput.Builder(NotificationUtil.EXTRA_REPLY)
+ .setLabel(context.getString(R.string.example_reply_label))
+ .build();
+ NotificationCompat.Action action = new NotificationCompat.Action.Builder(
+ R.drawable.ic_full_reply,
+ context.getString(R.string.example_reply_action),
+ NotificationUtil.getExamplePendingIntent(context,
+ R.string.example_reply_action_clicked))
+ .addRemoteInput(remoteInput)
+ .build();
+ builder.addAction(action);
+ }
+ }
+
+ private static class ReplyWithChoicesActionPreset extends ActionsPreset {
+ public ReplyWithChoicesActionPreset() {
+ super(R.string.reply_action_with_choices);
+ }
+
+ @Override
+ public void apply(Context context, NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions) {
+ RemoteInput remoteInput = new RemoteInput.Builder(NotificationUtil.EXTRA_REPLY)
+ .setLabel(context.getString(R.string.example_reply_answer_label))
+ .setChoices(new String[] { context.getString(R.string.yes),
+ context.getString(R.string.no), context.getString(R.string.maybe) })
+ .build();
+ NotificationCompat.Action action = new NotificationCompat.Action.Builder(
+ R.drawable.ic_full_reply,
+ context.getString(R.string.example_reply_action),
+ NotificationUtil.getExamplePendingIntent(context,
+ R.string.example_reply_action_clicked))
+ .addRemoteInput(remoteInput)
+ .build();
+ wearableOptions.addAction(action);
+ }
+ }
+
+ private static class DifferentActionsOnPhoneAndWearable extends ActionsPreset {
+ public DifferentActionsOnPhoneAndWearable() {
+ super(R.string.different_actions_on_phone_and_wearable);
+ }
+
+ @Override
+ public void apply(Context context, NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions) {
+ NotificationCompat.Action phoneAction = new NotificationCompat.Action.Builder(
+ R.drawable.ic_full_action,
+ context.getString(R.string.phone_action),
+ NotificationUtil.getExamplePendingIntent(context,
+ R.string.phone_action_clicked))
+ .build();
+ builder.addAction(phoneAction);
+
+ RemoteInput remoteInput = new RemoteInput.Builder(NotificationUtil.EXTRA_REPLY)
+ .setLabel(context.getString(R.string.example_reply_label))
+ .build();
+
+ NotificationCompat.Action wearableAction = new NotificationCompat.Action.Builder(
+ R.drawable.ic_full_reply,
+ context.getString(R.string.wearable_action),
+ NotificationUtil.getExamplePendingIntent(context,
+ R.string.wearable_action_clicked))
+ .addRemoteInput(remoteInput)
+ .build();
+ wearableOptions.addAction(wearableAction);
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/BackgroundPickers.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/BackgroundPickers.java
new file mode 100644
index 0000000..aedd548
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/BackgroundPickers.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Manages the background image pickers.
+ */
+public class BackgroundPickers {
+
+ public interface OnBackgroundPickersChangedListener {
+ public void onBackgroundPickersChanged(BackgroundPickers pickers);
+ }
+
+ private final ViewGroup mContainer;
+ private final OnPickedListener mOnPickedListener;
+ private final List<ViewGroup> mPickers;
+ private final OnBackgroundPickersChangedListener listener;
+
+ public BackgroundPickers(ViewGroup container, OnBackgroundPickersChangedListener listener) {
+ this.mContainer = container;
+ this.mOnPickedListener = new OnPickedListener();
+ this.mPickers = new ArrayList<ViewGroup>();
+ this.listener = listener;
+ }
+
+ /**
+ * Generates the pickers as necessary.
+ */
+ public void generatePickers(int count) {
+ // Clear existing containers.
+ clear();
+
+ // Fill in new pickers.
+ LayoutInflater inflater = LayoutInflater.from(mContainer.getContext());
+ Resources res = mContainer.getResources();
+ for (int i = 0; i < count; i++) {
+ View picker = inflater.inflate(R.layout.background_picker, mContainer, false);
+ TextView label = (TextView) picker.findViewById(R.id.bg_picker_label);
+ label.setText(String.format(res.getString(R.string.bg_picker_label), i+1));
+ ViewGroup pickerBox = (ViewGroup) picker.findViewById(R.id.bg_picker_container);
+ mPickers.add(pickerBox);
+ for (int j = 0; j < pickerBox.getChildCount(); j++) {
+ ImageView img = (ImageView) pickerBox.getChildAt(j);
+ img.setOnClickListener(mOnPickedListener);
+ }
+ mContainer.addView(picker);
+ }
+ }
+
+ /**
+ * Returns the background resource for the picker at the given index.
+ * @param position Index of the background picker.
+ * @return Id of the background image resource. null if no image is picked.
+ */
+ public Integer getRes(int position) {
+ String tag = (String) mPickers.get(position).getTag();
+ if (tag == null) {
+ return null;
+ }
+
+ Context context = mContainer.getContext();
+ return context.getResources().getIdentifier(tag, "drawable", context.getPackageName());
+ }
+
+ /**
+ * Returns the all the background resources for the pickers managed by this object. Returns null
+ * if no pickers exist.
+ */
+ public Integer[] getRes() {
+ if (mPickers.size() == 0) {
+ return null;
+ }
+
+ Integer[] res = new Integer[mPickers.size()];
+ for (int i = 0; i < mPickers.size(); i++) {
+ res[i] = getRes(i);
+ }
+ return res;
+ }
+
+ /**
+ * Clears the pickers.
+ */
+ public void clear() {
+ mContainer.removeAllViews();
+ mPickers.clear();
+ }
+
+ public int getCount() {
+ return mPickers.size();
+ }
+
+ private class OnPickedListener implements View.OnClickListener {
+
+ @Override
+ public void onClick(View view) {
+ ImageView pickedView = (ImageView) view;
+ ViewGroup pickerBox = (ViewGroup) view.getParent();
+
+ // Clear old selection.
+ for (int i = 0; i < pickerBox.getChildCount(); i++) {
+ ImageView childView = (ImageView) pickerBox.getChildAt(i);
+ childView.setBackgroundResource(R.drawable.unselected_background);
+ }
+
+ // Set new selection.
+ pickedView.setBackgroundResource(R.drawable.selected_background);
+ pickerBox.setTag(pickedView.getTag());
+
+ if (listener != null) {
+ listener.onBackgroundPickersChanged(BackgroundPickers.this);
+ }
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/MainActivity.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/MainActivity.java
new file mode 100644
index 0000000..c2be395
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/MainActivity.java
@@ -0,0 +1,352 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Activity;
+import android.app.Notification;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.support.v4.app.NotificationManagerCompat;
+import android.text.Editable;
+import android.text.TextWatcher;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.CheckBox;
+import android.widget.CompoundButton;
+import android.widget.EditText;
+import android.widget.Spinner;
+import android.widget.TextView;
+
+import java.util.Arrays;
+
+/**
+ * Main activity which posts a notification when resumed, and allows customization
+ * of that notification via controls.
+ */
+public class MainActivity extends Activity implements Handler.Callback {
+ private static final int MSG_POST_NOTIFICATIONS = 0;
+ private static final long POST_NOTIFICATIONS_DELAY_MS = 200;
+
+ private Handler mHandler;
+ private Spinner mPresetSpinner;
+ private EditText mTitleEditText;
+ private EditText mTextEditText;
+ private TextWatcher mTextChangedListener;
+ private Spinner mPrioritySpinner;
+ private Spinner mActionsSpinner;
+ private CheckBox mIncludeLargeIconCheckbox;
+ private CheckBox mLocalOnlyCheckbox;
+ private CheckBox mIncludeContentIntentCheckbox;
+ private CheckBox mVibrateCheckbox;
+ private BackgroundPickers mBackgroundPickers;
+ private int postedNotificationCount = 0;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main);
+
+ mHandler = new Handler(this);
+ mTextChangedListener = new UpdateNotificationsOnTextChangeListener();
+
+ initPresetSpinner();
+ initTitleEditText();
+ initTextEditText();
+ initPrioritySpinner();
+ initActionsSpinner();
+ initIncludeLargeIconCheckbox();
+ initLocalOnlyCheckbox();
+ initIncludeContentIntentCheckbox();
+ initVibrateCheckbox();
+ initBackgroundPickers();
+
+ NotificationPreset preset = NotificationPresets.PRESETS[
+ mPresetSpinner.getSelectedItemPosition()];
+ updateTextEditors(preset);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ updateNotifications(false /* cancelExisting */);
+ }
+
+ private void initPresetSpinner() {
+ mPresetSpinner = (Spinner) findViewById(R.id.preset_spinner);
+ mPresetSpinner.setAdapter(new NamedPresetSpinnerArrayAdapter(this,
+ NotificationPresets.PRESETS));
+ mPresetSpinner.post(new Runnable() {
+ @Override
+ public void run() {
+ mPresetSpinner.setOnItemSelectedListener(new PresetSpinnerListener());
+ }
+ });
+ }
+
+ private void initTitleEditText() {
+ mTitleEditText = (EditText) findViewById(R.id.title_editor);
+ }
+
+ private void initTextEditText() {
+ mTextEditText = (EditText) findViewById(R.id.text_editor);
+ }
+
+ private void initPrioritySpinner() {
+ mPrioritySpinner = (Spinner) findViewById(R.id.priority_spinner);
+ mPrioritySpinner.setAdapter(new NamedPresetSpinnerArrayAdapter(this,
+ PriorityPresets.PRESETS));
+ mPrioritySpinner.setSelection(Arrays.asList(PriorityPresets.PRESETS)
+ .indexOf(PriorityPresets.DEFAULT));
+ mPrioritySpinner.post(new Runnable() {
+ @Override
+ public void run() {
+ mPrioritySpinner.setOnItemSelectedListener(
+ new UpdateNotificationsOnItemSelectedListener(true /* cancelExisting */));
+ }
+ });
+ }
+
+ private void initActionsSpinner() {
+ mActionsSpinner = (Spinner) findViewById(R.id.actions_spinner);
+ mActionsSpinner.setAdapter(new NamedPresetSpinnerArrayAdapter(this,
+ ActionsPresets.PRESETS));
+ mActionsSpinner.post(new Runnable() {
+ @Override
+ public void run() {
+ mActionsSpinner.setOnItemSelectedListener(
+ new UpdateNotificationsOnItemSelectedListener(false /* cancelExisting */));
+ }
+ });
+ }
+
+ private void initIncludeLargeIconCheckbox() {
+ mIncludeLargeIconCheckbox = (CheckBox) findViewById(R.id.include_large_icon_checkbox);
+ mIncludeLargeIconCheckbox.setOnCheckedChangeListener(
+ new UpdateNotificationsOnCheckedChangeListener(false /* cancelExisting */));
+ }
+
+ private void initLocalOnlyCheckbox() {
+ mLocalOnlyCheckbox = (CheckBox) findViewById(R.id.local_only_checkbox);
+ mLocalOnlyCheckbox.setOnCheckedChangeListener(
+ new UpdateNotificationsOnCheckedChangeListener(false /* cancelExisting */));
+ }
+
+ private void initIncludeContentIntentCheckbox() {
+ mIncludeContentIntentCheckbox = (CheckBox) findViewById(
+ R.id.include_content_intent_checkbox);
+ mIncludeContentIntentCheckbox.setOnCheckedChangeListener(
+ new UpdateNotificationsOnCheckedChangeListener(false /* cancelExisting */));
+ }
+
+ private void initVibrateCheckbox() {
+ mVibrateCheckbox = (CheckBox) findViewById(R.id.vibrate_checkbox);
+ mVibrateCheckbox.setOnCheckedChangeListener(
+ new UpdateNotificationsOnCheckedChangeListener(false /* cancelExisting */));
+ }
+
+ private void initBackgroundPickers() {
+ mBackgroundPickers = new BackgroundPickers(
+ (ViewGroup) findViewById(R.id.background_pickers),
+ new BackgroundPickerListener());
+ }
+
+ private void updateTextEditors(NotificationPreset preset) {
+ if (preset == NotificationPresets.BASIC) {
+ findViewById(R.id.title_edit_field).setVisibility(View.VISIBLE);
+ mTitleEditText.setText(getString(preset.titleResId));
+ mTitleEditText.addTextChangedListener(mTextChangedListener);
+ findViewById(R.id.text_edit_field).setVisibility(View.VISIBLE);
+ mTextEditText.setText(getString(preset.textResId));
+ mTextEditText.addTextChangedListener(mTextChangedListener);
+ } else {
+ findViewById(R.id.title_edit_field).setVisibility(View.GONE);
+ mTitleEditText.removeTextChangedListener(mTextChangedListener);
+ findViewById(R.id.text_edit_field).setVisibility(View.GONE);
+ mTextEditText.removeTextChangedListener(mTextChangedListener);
+ }
+ }
+
+ /**
+ * Begin to re-post the sample notification(s).
+ */
+ private void updateNotifications(boolean cancelExisting) {
+ // Disable messages to skip notification deleted messages during cancel.
+ sendBroadcast(new Intent(NotificationIntentReceiver.ACTION_DISABLE_MESSAGES)
+ .setClass(this, NotificationIntentReceiver.class));
+
+ if (cancelExisting) {
+ // Cancel all existing notifications to trigger fresh-posting behavior: For example,
+ // switching from HIGH to LOW priority does not cause a reordering in Notification Shade.
+ NotificationManagerCompat.from(this).cancelAll();
+ postedNotificationCount = 0;
+
+ // Post the updated notifications on a delay to avoid a cancel+post race condition
+ // with notification manager.
+ mHandler.removeMessages(MSG_POST_NOTIFICATIONS);
+ mHandler.sendEmptyMessageDelayed(MSG_POST_NOTIFICATIONS, POST_NOTIFICATIONS_DELAY_MS);
+ } else {
+ postNotifications();
+ }
+ }
+
+ /**
+ * Post the sample notification(s) using current options.
+ */
+ private void postNotifications() {
+ sendBroadcast(new Intent(NotificationIntentReceiver.ACTION_ENABLE_MESSAGES)
+ .setClass(this, NotificationIntentReceiver.class));
+
+ NotificationPreset preset = NotificationPresets.PRESETS[
+ mPresetSpinner.getSelectedItemPosition()];
+ CharSequence titlePreset = mTitleEditText.getText();
+ CharSequence textPreset = mTextEditText.getText();
+ PriorityPreset priorityPreset = PriorityPresets.PRESETS[
+ mPrioritySpinner.getSelectedItemPosition()];
+ ActionsPreset actionsPreset = ActionsPresets.PRESETS[
+ mActionsSpinner.getSelectedItemPosition()];
+ if (preset.actionsRequired() && actionsPreset == ActionsPresets.NO_ACTIONS_PRESET) {
+ // If actions are required, but the no-actions preset was selected, change presets.
+ actionsPreset = ActionsPresets.SINGLE_ACTION_PRESET;
+ mActionsSpinner.setSelection(Arrays.asList(ActionsPresets.PRESETS).indexOf(
+ actionsPreset), true);
+ }
+ NotificationPreset.BuildOptions options = new NotificationPreset.BuildOptions(
+ titlePreset,
+ textPreset,
+ priorityPreset,
+ actionsPreset,
+ mIncludeLargeIconCheckbox.isChecked(),
+ mLocalOnlyCheckbox.isChecked(),
+ mIncludeContentIntentCheckbox.isChecked(),
+ mVibrateCheckbox.isChecked(),
+ mBackgroundPickers.getRes());
+ Notification[] notifications = preset.buildNotifications(this, options);
+
+ // Post new notifications
+ for (int i = 0; i < notifications.length; i++) {
+ NotificationManagerCompat.from(this).notify(i, notifications[i]);
+ }
+ // Cancel any that are beyond the current count.
+ for (int i = notifications.length; i < postedNotificationCount; i++) {
+ NotificationManagerCompat.from(this).cancel(i);
+ }
+ postedNotificationCount = notifications.length;
+ }
+
+ @Override
+ public boolean handleMessage(Message message) {
+ switch (message.what) {
+ case MSG_POST_NOTIFICATIONS:
+ postNotifications();
+ return true;
+ }
+ return false;
+ }
+
+ private class PresetSpinnerListener implements AdapterView.OnItemSelectedListener {
+ @Override
+ public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
+ NotificationPreset preset = NotificationPresets.PRESETS[position];
+ mBackgroundPickers.generatePickers(preset.countBackgroundPickersRequired());
+ updateTextEditors(preset);
+ updateNotifications(false /* cancelExisting */);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView<?> adapterView) {
+ }
+ }
+
+ private class UpdateNotificationsOnTextChangeListener implements TextWatcher {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
+
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ }
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ updateNotifications(false /* cancelExisting */);
+ }
+ }
+
+ private class UpdateNotificationsOnItemSelectedListener
+ implements AdapterView.OnItemSelectedListener {
+ private final boolean mCancelExisting;
+
+ public UpdateNotificationsOnItemSelectedListener(boolean cancelExisting) {
+ mCancelExisting = cancelExisting;
+ }
+ @Override
+ public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
+ updateNotifications(mCancelExisting);
+ }
+
+ @Override
+ public void onNothingSelected(AdapterView<?> adapterView) {
+ }
+ }
+
+ private class UpdateNotificationsOnCheckedChangeListener
+ implements CompoundButton.OnCheckedChangeListener {
+ private final boolean mCancelExisting;
+
+ public UpdateNotificationsOnCheckedChangeListener(boolean cancelExisting) {
+ mCancelExisting = cancelExisting;
+ }
+
+ @Override
+ public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
+ updateNotifications(mCancelExisting);
+ }
+ }
+
+ private class BackgroundPickerListener
+ implements BackgroundPickers.OnBackgroundPickersChangedListener {
+ @Override
+ public void onBackgroundPickersChanged(BackgroundPickers pickers) {
+ updateNotifications(false /* cancelExisting */);
+ }
+ }
+
+ private class NamedPresetSpinnerArrayAdapter extends ArrayAdapter<NamedPreset> {
+ public NamedPresetSpinnerArrayAdapter(Context context, NamedPreset[] presets) {
+ super(context, R.layout.simple_spinner_item, presets);
+ }
+
+ @Override
+ public View getDropDownView(int position, View convertView, ViewGroup parent) {
+ TextView view = (TextView) super.getDropDownView(position, convertView, parent);
+ view.setText(getString(getItem(position).nameResId));
+ return view;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ TextView view = (TextView) getLayoutInflater().inflate(
+ android.R.layout.simple_spinner_item, parent, false);
+ view.setText(getString(getItem(position).nameResId));
+ return view;
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NamedPreset.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NamedPreset.java
new file mode 100644
index 0000000..afc5f16
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NamedPreset.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+/**
+ * Base class for presets that have a simple name to display.
+ */
+public abstract class NamedPreset {
+ public final int nameResId;
+
+ public NamedPreset(int nameResId) {
+ this.nameResId = nameResId;
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationIntentReceiver.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationIntentReceiver.java
new file mode 100644
index 0000000..39a1c78
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationIntentReceiver.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.v4.app.RemoteInput;
+import android.widget.Toast;
+
+/**
+ * Broadcast receiver to post toast messages in response to notification intents firing.
+ */
+public class NotificationIntentReceiver extends BroadcastReceiver {
+ public static final String ACTION_EXAMPLE =
+ "com.example.android.support.wearable.notifications.ACTION_EXAMPLE";
+ public static final String ACTION_ENABLE_MESSAGES =
+ "com.example.android.support.wearable.notifications.ACTION_ENABLE_MESSAGES";
+ public static final String ACTION_DISABLE_MESSAGES =
+ "com.example.android.support.wearable.notifications.ACTION_DISABLE_MESSAGES";
+
+ private boolean mEnableMessages = true;
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (intent.getAction().equals(ACTION_EXAMPLE)) {
+ if (mEnableMessages) {
+ String message = intent.getStringExtra(NotificationUtil.EXTRA_MESSAGE);
+ Bundle remoteInputResults = RemoteInput.getResultsFromIntent(intent);
+ CharSequence replyMessage = null;
+ if (remoteInputResults != null) {
+ replyMessage = remoteInputResults.getCharSequence(NotificationUtil.EXTRA_REPLY);
+ }
+ if (replyMessage != null) {
+ message = message + ": \"" + replyMessage + "\"";
+ }
+ Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
+ }
+ } else if (intent.getAction().equals(ACTION_ENABLE_MESSAGES)) {
+ mEnableMessages = true;
+ } else if (intent.getAction().equals(ACTION_DISABLE_MESSAGES)) {
+ mEnableMessages = false;
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationPreset.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationPreset.java
new file mode 100644
index 0000000..a0dff18
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationPreset.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Notification;
+import android.content.Context;
+
+/**
+ * Base class for notification preset generators.
+ */
+public abstract class NotificationPreset extends NamedPreset {
+ public final int titleResId;
+ public final int textResId;
+
+ public NotificationPreset(int nameResId, int titleResId, int textResId) {
+ super(nameResId);
+ this.titleResId = titleResId;
+ this.textResId = textResId;
+ }
+
+ public static class BuildOptions {
+ public final CharSequence titlePreset;
+ public final CharSequence textPreset;
+ public final PriorityPreset priorityPreset;
+ public final ActionsPreset actionsPreset;
+ public final boolean includeLargeIcon;
+ public final boolean isLocalOnly;
+ public final boolean hasContentIntent;
+ public final boolean vibrate;
+ public final Integer[] backgroundIds;
+
+ public BuildOptions(CharSequence titlePreset, CharSequence textPreset,
+ PriorityPreset priorityPreset, ActionsPreset actionsPreset,
+ boolean includeLargeIcon, boolean isLocalOnly, boolean hasContentIntent,
+ boolean vibrate, Integer[] backgroundIds) {
+ this.titlePreset = titlePreset;
+ this.textPreset = textPreset;
+ this.priorityPreset = priorityPreset;
+ this.actionsPreset = actionsPreset;
+ this.includeLargeIcon = includeLargeIcon;
+ this.isLocalOnly = isLocalOnly;
+ this.hasContentIntent = hasContentIntent;
+ this.vibrate = vibrate;
+ this.backgroundIds = backgroundIds;
+ }
+ }
+
+ /** Build a notification with this preset and the provided options */
+ public abstract Notification[] buildNotifications(Context context, BuildOptions options);
+
+ /** Whether actions are required to use this preset. */
+ public boolean actionsRequired() {
+ return false;
+ }
+
+ /** Number of background pickers required */
+ public int countBackgroundPickersRequired() {
+ return 0;
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationPresets.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationPresets.java
new file mode 100644
index 0000000..e175d11
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationPresets.java
@@ -0,0 +1,479 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Notification;
+import android.content.Context;
+import android.graphics.BitmapFactory;
+import android.graphics.Color;
+import android.graphics.Typeface;
+import android.support.v4.app.NotificationCompat;
+import android.text.SpannableStringBuilder;
+import android.text.style.ForegroundColorSpan;
+import android.text.style.RelativeSizeSpan;
+import android.text.style.StrikethroughSpan;
+import android.text.style.StyleSpan;
+import android.text.style.SubscriptSpan;
+import android.text.style.SuperscriptSpan;
+import android.text.style.TypefaceSpan;
+import android.text.style.UnderlineSpan;
+import android.view.Gravity;
+
+/**
+ * Collection of notification builder presets.
+ */
+public class NotificationPresets {
+ private static final String EXAMPLE_GROUP_KEY = "example";
+
+ public static final NotificationPreset BASIC = new BasicNotificationPreset();
+ public static final NotificationPreset STYLIZED_TEXT = new StylizedTextNotificationPreset();
+ public static final NotificationPreset INBOX = new InboxNotificationPreset();
+ public static final NotificationPreset BIG_PICTURE = new BigPictureNotificationPreset();
+ public static final NotificationPreset BIG_TEXT = new BigTextNotificationPreset();
+ public static final NotificationPreset BOTTOM_ALIGNED = new BottomAlignedNotificationPreset();
+ public static final NotificationPreset GRAVITY = new GravityNotificationPreset();
+ public static final NotificationPreset CONTENT_ACTION = new ContentActionNotificationPreset();
+ public static final NotificationPreset CONTENT_ICON = new ContentIconNotificationPreset();
+ public static final NotificationPreset MULTIPLE_PAGE = new MultiplePageNotificationPreset();
+ public static final NotificationPreset BUNDLE = new NotificationBundlePreset();
+
+ public static final NotificationPreset[] PRESETS = new NotificationPreset[] {
+ BASIC,
+ STYLIZED_TEXT,
+ INBOX,
+ BIG_PICTURE,
+ BIG_TEXT,
+ BOTTOM_ALIGNED,
+ GRAVITY,
+ CONTENT_ACTION,
+ CONTENT_ICON,
+ MULTIPLE_PAGE,
+ BUNDLE
+ };
+
+ private static NotificationCompat.Builder applyBasicOptions(Context context,
+ NotificationCompat.Builder builder, NotificationCompat.WearableExtender wearableOptions,
+ NotificationPreset.BuildOptions options) {
+ builder.setContentTitle(options.titlePreset)
+ .setContentText(options.textPreset)
+ .setSmallIcon(R.mipmap.ic_launcher)
+ .setDeleteIntent(NotificationUtil.getExamplePendingIntent(
+ context, R.string.example_notification_deleted));
+ options.actionsPreset.apply(context, builder, wearableOptions);
+ options.priorityPreset.apply(builder, wearableOptions);
+ if (options.includeLargeIcon) {
+ builder.setLargeIcon(BitmapFactory.decodeResource(
+ context.getResources(), R.drawable.example_large_icon));
+ }
+ if (options.isLocalOnly) {
+ builder.setLocalOnly(true);
+ }
+ if (options.hasContentIntent) {
+ builder.setContentIntent(NotificationUtil.getExamplePendingIntent(context,
+ R.string.content_intent_clicked));
+ }
+ if (options.vibrate) {
+ builder.setVibrate(new long[] {0, 100, 50, 100} );
+ }
+ return builder;
+ }
+
+ private static class BasicNotificationPreset extends NotificationPreset {
+ public BasicNotificationPreset() {
+ super(R.string.basic_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, builder, wearableOptions, options);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+ }
+
+ private static class StylizedTextNotificationPreset extends NotificationPreset {
+ public StylizedTextNotificationPreset() {
+ super(R.string.stylized_text_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
+
+ SpannableStringBuilder title = new SpannableStringBuilder();
+ appendStyled(title, "Stylized", new StyleSpan(Typeface.BOLD_ITALIC));
+ title.append(" title");
+ SpannableStringBuilder text = new SpannableStringBuilder("Stylized text: ");
+ appendStyled(text, "C", new ForegroundColorSpan(Color.RED));
+ appendStyled(text, "O", new ForegroundColorSpan(Color.GREEN));
+ appendStyled(text, "L", new ForegroundColorSpan(Color.BLUE));
+ appendStyled(text, "O", new ForegroundColorSpan(Color.YELLOW));
+ appendStyled(text, "R", new ForegroundColorSpan(Color.MAGENTA));
+ appendStyled(text, "S", new ForegroundColorSpan(Color.CYAN));
+ text.append("; ");
+ appendStyled(text, "1.25x size", new RelativeSizeSpan(1.25f));
+ text.append("; ");
+ appendStyled(text, "0.75x size", new RelativeSizeSpan(0.75f));
+ text.append("; ");
+ appendStyled(text, "underline", new UnderlineSpan());
+ text.append("; ");
+ appendStyled(text, "strikethrough", new StrikethroughSpan());
+ text.append("; ");
+ appendStyled(text, "bold", new StyleSpan(Typeface.BOLD));
+ text.append("; ");
+ appendStyled(text, "italic", new StyleSpan(Typeface.ITALIC));
+ text.append("; ");
+ appendStyled(text, "sans-serif-thin", new TypefaceSpan("sans-serif-thin"));
+ text.append("; ");
+ appendStyled(text, "monospace", new TypefaceSpan("monospace"));
+ text.append("; ");
+ appendStyled(text, "sub", new SubscriptSpan());
+ text.append("script");
+ appendStyled(text, "super", new SuperscriptSpan());
+
+ style.setBigContentTitle(title);
+ style.bigText(text);
+
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
+ .setStyle(style);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, builder, wearableOptions, options);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+
+ private void appendStyled(SpannableStringBuilder builder, String str, Object... spans) {
+ builder.append(str);
+ for (Object span : spans) {
+ builder.setSpan(span, builder.length() - str.length(), builder.length(), 0);
+ }
+ }
+ }
+
+ private static class InboxNotificationPreset extends NotificationPreset {
+ public InboxNotificationPreset() {
+ super(R.string.inbox_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
+ style.addLine(context.getString(R.string.inbox_style_example_line1));
+ style.addLine(context.getString(R.string.inbox_style_example_line2));
+ style.addLine(context.getString(R.string.inbox_style_example_line3));
+ style.setBigContentTitle(context.getString(R.string.inbox_style_example_title));
+ style.setSummaryText(context.getString(R.string.inbox_style_example_summary_text));
+
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
+ .setStyle(style);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, builder, wearableOptions, options);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+ }
+
+ private static class BigPictureNotificationPreset extends NotificationPreset {
+ public BigPictureNotificationPreset() {
+ super(R.string.big_picture_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
+ style.bigPicture(BitmapFactory.decodeResource(context.getResources(),
+ R.drawable.example_big_picture));
+ style.setBigContentTitle(context.getString(R.string.big_picture_style_example_title));
+ style.setSummaryText(context.getString(
+ R.string.big_picture_style_example_summary_text));
+
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
+ .setStyle(style);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, builder, wearableOptions, options);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+ }
+
+ private static class BigTextNotificationPreset extends NotificationPreset {
+ public BigTextNotificationPreset() {
+ super(R.string.big_text_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
+ style.bigText(context.getString(R.string.big_text_example_big_text));
+ style.setBigContentTitle(context.getString(R.string.big_text_example_title));
+ style.setSummaryText(context.getString(R.string.big_text_example_summary_text));
+
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
+ .setStyle(style);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, builder, wearableOptions, options);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+ }
+
+ private static class BottomAlignedNotificationPreset extends NotificationPreset {
+ public BottomAlignedNotificationPreset() {
+ super(R.string.bottom_aligned_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, builder, wearableOptions, options);
+
+ NotificationCompat.Builder secondPageBuilder = new NotificationCompat.Builder(context);
+ secondPageBuilder.setContentTitle(
+ context.getString(R.string.second_page_content_title));
+ secondPageBuilder.setContentText(context.getString(R.string.big_text_example_big_text));
+ secondPageBuilder.extend(new NotificationCompat.WearableExtender()
+ .setStartScrollBottom(true));
+
+ wearableOptions.addPage(secondPageBuilder.build());
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+ }
+
+ private static class GravityNotificationPreset extends NotificationPreset {
+ public GravityNotificationPreset() {
+ super(R.string.gravity_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, builder, wearableOptions, options);
+
+ NotificationCompat.Builder secondPageBuilder = new NotificationCompat.Builder(context)
+ .setContentTitle(options.titlePreset)
+ .setContentText(options.textPreset)
+ .extend(new NotificationCompat.WearableExtender()
+ .setGravity(Gravity.CENTER_VERTICAL));
+ wearableOptions.addPage(secondPageBuilder.build());
+
+ NotificationCompat.Builder thirdPageBuilder = new NotificationCompat.Builder(context)
+ .setContentTitle(options.titlePreset)
+ .setContentText(options.textPreset)
+ .extend(new NotificationCompat.WearableExtender()
+ .setGravity(Gravity.TOP));
+ wearableOptions.addPage(thirdPageBuilder.build());
+
+ wearableOptions.setGravity(Gravity.BOTTOM);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+ }
+
+ private static class ContentActionNotificationPreset extends NotificationPreset {
+ public ContentActionNotificationPreset() {
+ super(R.string.content_action_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ Notification secondPage = new NotificationCompat.Builder(context)
+ .setContentTitle(context.getString(R.string.second_page_content_title))
+ .setContentText(context.getString(R.string.second_page_content_text))
+ .extend(new NotificationCompat.WearableExtender()
+ .setContentAction(1))
+ .build();
+
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
+ NotificationCompat.Action action = new NotificationCompat.Action.Builder(
+ R.drawable.ic_result_open, null, NotificationUtil.getExamplePendingIntent(
+ context, R.string.example_content_action_clicked)).build();
+ NotificationCompat.Action action2 = new NotificationCompat.Action.Builder(
+ R.drawable.ic_result_open, null, NotificationUtil.getExamplePendingIntent(
+ context, R.string.example_content_action2_clicked)).build();
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender()
+ .addAction(action)
+ .addAction(action2)
+ .addPage(secondPage)
+ .setContentAction(0)
+ .setHintHideIcon(true);
+ applyBasicOptions(context, builder, wearableOptions, options);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+
+ @Override
+ public boolean actionsRequired() {
+ return true;
+ }
+ }
+
+ private static class ContentIconNotificationPreset extends NotificationPreset {
+ public ContentIconNotificationPreset() {
+ super(R.string.content_icon_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ Notification secondPage = new NotificationCompat.Builder(context)
+ .setContentTitle(context.getString(R.string.second_page_content_title))
+ .setContentText(context.getString(R.string.second_page_content_text))
+ .extend(new NotificationCompat.WearableExtender()
+ .setContentIcon(R.drawable.content_icon_small)
+ .setContentIconGravity(Gravity.START))
+ .build();
+
+ Notification thirdPage = new NotificationCompat.Builder(context)
+ .setContentTitle(context.getString(R.string.third_page_content_title))
+ .setContentText(context.getString(R.string.third_page_content_text))
+ .extend(new NotificationCompat.WearableExtender()
+ .setContentIcon(R.drawable.content_icon_large))
+ .build();
+
+ Notification fourthPage = new NotificationCompat.Builder(context)
+ .setContentTitle(context.getString(R.string.fourth_page_content_title))
+ .setContentText(context.getString(R.string.fourth_page_content_text))
+ .extend(new NotificationCompat.WearableExtender()
+ .setContentIcon(R.drawable.content_icon_large)
+ .setContentIconGravity(Gravity.START))
+ .build();
+
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
+ NotificationCompat.WearableExtender wearableOptions =
+ new NotificationCompat.WearableExtender()
+ .setHintHideIcon(true)
+ .setContentIcon(R.drawable.content_icon_small)
+ .addPage(secondPage)
+ .addPage(thirdPage)
+ .addPage(fourthPage);
+ applyBasicOptions(context, builder, wearableOptions, options);
+ builder.extend(wearableOptions);
+ return new Notification[] { builder.build() };
+ }
+ }
+
+ private static class MultiplePageNotificationPreset extends NotificationPreset {
+ public MultiplePageNotificationPreset() {
+ super(R.string.multiple_page_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.Builder secondPageBuilder = new NotificationCompat.Builder(context)
+ .setContentTitle(context.getString(R.string.second_page_content_title))
+ .setContentText(context.getString(R.string.second_page_content_text));
+
+ NotificationCompat.Builder firstPageBuilder = new NotificationCompat.Builder(context);
+ NotificationCompat.WearableExtender firstPageWearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, firstPageBuilder, firstPageWearableOptions, options);
+
+ Integer firstBackground = options.backgroundIds == null
+ ? null : options.backgroundIds[0];
+ if (firstBackground != null) {
+ NotificationCompat.BigPictureStyle style =
+ new NotificationCompat.BigPictureStyle();
+ style.bigPicture(BitmapFactory.decodeResource(context.getResources(),
+ firstBackground));
+ firstPageBuilder.setStyle(style);
+ }
+
+ Integer secondBackground = options.backgroundIds == null
+ ? null : options.backgroundIds[1];
+ if (secondBackground != null) {
+ NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
+ style.bigPicture(BitmapFactory.decodeResource(context.getResources(),
+ secondBackground));
+ secondPageBuilder.setStyle(style);
+ }
+
+ firstPageBuilder.extend(
+ firstPageWearableOptions.addPage(secondPageBuilder.build()));
+
+ return new Notification[]{ firstPageBuilder.build() };
+ }
+
+ @Override
+ public int countBackgroundPickersRequired() {
+ return 2; // This sample does 2 pages notifications.
+ }
+ }
+
+ private static class NotificationBundlePreset extends NotificationPreset {
+ public NotificationBundlePreset() {
+ super(R.string.bundle_example, R.string.example_content_title,
+ R.string.example_content_text);
+ }
+
+ @Override
+ public Notification[] buildNotifications(Context context, BuildOptions options) {
+ NotificationCompat.Builder childBuilder1 = new NotificationCompat.Builder(context)
+ .setContentTitle(context.getString(R.string.first_child_content_title))
+ .setContentText(context.getString(R.string.first_child_content_text))
+ .setSmallIcon(R.mipmap.ic_launcher)
+ .setLocalOnly(options.isLocalOnly)
+ .setGroup(EXAMPLE_GROUP_KEY)
+ .setSortKey("0");
+
+ NotificationCompat.Builder childBuilder2 = new NotificationCompat.Builder(context)
+ .setContentTitle(context.getString(R.string.second_child_content_title))
+ .setContentText(context.getString(R.string.second_child_content_text))
+ .setSmallIcon(R.mipmap.ic_launcher)
+ .addAction(R.mipmap.ic_launcher,
+ context.getString(R.string.second_child_action),
+ NotificationUtil.getExamplePendingIntent(
+ context, R.string.second_child_action_clicked))
+ .setLocalOnly(options.isLocalOnly)
+ .setGroup(EXAMPLE_GROUP_KEY)
+ .setSortKey("1");
+
+ NotificationCompat.Builder summaryBuilder = new NotificationCompat.Builder(context)
+ .setGroup(EXAMPLE_GROUP_KEY)
+ .setGroupSummary(true);
+
+ NotificationCompat.WearableExtender summaryWearableOptions =
+ new NotificationCompat.WearableExtender();
+ applyBasicOptions(context, summaryBuilder, summaryWearableOptions, options);
+ summaryBuilder.extend(summaryWearableOptions);
+
+ return new Notification[] { summaryBuilder.build(), childBuilder1.build(),
+ childBuilder2.build() };
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationUtil.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationUtil.java
new file mode 100644
index 0000000..389b90a
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/NotificationUtil.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+
+public class NotificationUtil {
+ public static final String EXTRA_MESSAGE =
+ "com.example.android.support.wearable.notifications.MESSAGE";
+ public static final String EXTRA_REPLY =
+ "com.example.android.support.wearable.notifications.REPLY";
+
+ public static PendingIntent getExamplePendingIntent(Context context, int messageResId) {
+ Intent intent = new Intent(NotificationIntentReceiver.ACTION_EXAMPLE)
+ .setClass(context, NotificationIntentReceiver.class);
+ intent.putExtra(EXTRA_MESSAGE, context.getString(messageResId));
+ return PendingIntent.getBroadcast(context, messageResId /* requestCode */, intent,
+ PendingIntent.FLAG_UPDATE_CURRENT);
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/PriorityPreset.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/PriorityPreset.java
new file mode 100644
index 0000000..b4298fd
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/PriorityPreset.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.support.v4.app.NotificationCompat;
+
+/**
+ * Base class for notification priority presets.
+ */
+public abstract class PriorityPreset extends NamedPreset {
+ public PriorityPreset(int nameResId) {
+ super(nameResId);
+ }
+
+ /** Apply the priority to a notification builder */
+ public abstract void apply(NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions);
+}
diff --git a/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/PriorityPresets.java b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/PriorityPresets.java
new file mode 100644
index 0000000..c33b59d
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Application/src/main/java/com/example/android/support/wearable/notifications/PriorityPresets.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Notification;
+import android.support.v4.app.NotificationCompat;
+
+/**
+ * Collection of notification priority presets.
+ */
+public class PriorityPresets {
+ public static final PriorityPreset DEFAULT = new SimplePriorityPreset(
+ R.string.default_priority, Notification.PRIORITY_DEFAULT);
+
+ public static final PriorityPreset[] PRESETS = new PriorityPreset[] {
+ new SimplePriorityPreset(R.string.min_priority, Notification.PRIORITY_MIN),
+ new SimplePriorityPreset(R.string.low_priority, Notification.PRIORITY_LOW),
+ DEFAULT,
+ new SimplePriorityPreset(R.string.high_priority, Notification.PRIORITY_HIGH),
+ new SimplePriorityPreset(R.string.max_priority, Notification.PRIORITY_MAX)
+ };
+
+ /**
+ * Simple notification priority preset that sets a priority using
+ * {@link android.support.v4.app.NotificationCompat.Builder#setPriority}
+ */
+ private static class SimplePriorityPreset extends PriorityPreset {
+ private final int mPriority;
+
+ public SimplePriorityPreset(int nameResId, int priority) {
+ super(nameResId);
+ mPriority = priority;
+ }
+
+ @Override
+ public void apply(NotificationCompat.Builder builder,
+ NotificationCompat.WearableExtender wearableOptions) {
+ builder.setPriority(mPriority);
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Wearable/build.gradle b/prebuilts/gradle/Notifications/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/Notifications/Wearable/build.gradle
+++ b/prebuilts/gradle/Notifications/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/Notifications/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/Notifications/Wearable/src/main/AndroidManifest.xml
index 99640f5..57cd7c4 100644
--- a/prebuilts/gradle/Notifications/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Notifications/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.notifications" >
+ package="com.example.android.support.wearable.notifications" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
diff --git a/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/AnimatedNotificationDisplayActivity.java b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/AnimatedNotificationDisplayActivity.java
new file mode 100644
index 0000000..2e0b2ee
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/AnimatedNotificationDisplayActivity.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.animation.Animator;
+import android.animation.AnimatorListenerAdapter;
+import android.animation.ObjectAnimator;
+import android.animation.PropertyValuesHolder;
+import android.app.Activity;
+import android.content.Context;
+import android.os.Bundle;
+import android.view.ViewGroup;
+import android.view.animation.AccelerateDecelerateInterpolator;
+import android.widget.FrameLayout;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+import java.util.Random;
+
+/**
+ * Custom display activity for an animated sample notification.
+ */
+public class AnimatedNotificationDisplayActivity extends Activity {
+ public static final String EXTRA_TITLE = "title";
+
+ private static final int BASE_ANIMATION_DURATION_MS = 2000;
+
+ private Random mRandom;
+ private int mAnimationRange;
+ private ImageView mImageView;
+ private Animator mAnimation;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_animated_notification_display);
+
+ mRandom = new Random(System.currentTimeMillis());
+ mAnimationRange = getResources().getDimensionPixelSize(R.dimen.animation_range);
+
+ String title = getIntent().getStringExtra(EXTRA_TITLE);
+ ((TextView) findViewById(R.id.title)).setText(title);
+
+ mImageView = new ImageView(this);
+ mImageView.setImageResource(R.drawable.example_big_picture);
+
+ ImageZoomView zoomView = new ImageZoomView(this, mImageView, mAnimationRange);
+ zoomView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT));
+
+ ((FrameLayout) findViewById(R.id.container)).addView(zoomView, 0);
+
+ createNextAnimation(false);
+ }
+
+ private void createNextAnimation(boolean start) {
+ float startX = mImageView.getTranslationX();
+ float startY = mImageView.getTranslationY();
+ float endX = -mRandom.nextInt(mAnimationRange);
+ float endY = -mRandom.nextInt(mAnimationRange);
+ float distance = (float) Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));
+
+ mAnimation = ObjectAnimator.ofPropertyValuesHolder(mImageView,
+ PropertyValuesHolder.ofFloat("translationX", startX, endX),
+ PropertyValuesHolder.ofFloat("translationY", startY, endY));
+ mAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
+
+ mAnimation.setDuration(Math.max(BASE_ANIMATION_DURATION_MS / 10,
+ (int) (distance * BASE_ANIMATION_DURATION_MS / mAnimationRange)));
+
+ mAnimation.addListener(new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ super.onAnimationEnd(animation);
+ createNextAnimation(true);
+ }
+ });
+ if (start) {
+ mAnimation.start();
+ }
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ mAnimation.start();
+ }
+
+ @Override
+ protected void onPause() {
+ mAnimation.pause();
+ super.onPause();
+ }
+
+ /** Helper view that zooms in on a child image view */
+ private static class ImageZoomView extends ViewGroup {
+ private final int mZoomLength;
+
+ public ImageZoomView(Context context, ImageView imageView, int zoomLength) {
+ super(context);
+ addView(imageView);
+ mZoomLength = zoomLength;
+ }
+
+ @Override
+ protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
+ ImageView imageView = (ImageView) getChildAt(0);
+
+ // Resize the image view to be at least mZoomLength pixels larger in both
+ // dimensions than the containing view.
+ int imageWidth = imageView.getDrawable().getIntrinsicWidth();
+ int imageHeight = imageView.getDrawable().getIntrinsicHeight();
+ int minSize = Math.max(right - left, bottom - top) + mZoomLength;
+ if (imageWidth > imageHeight) {
+ imageWidth = minSize * imageWidth / imageHeight;
+ imageHeight = minSize;
+ } else {
+ imageHeight = minSize * imageHeight / imageWidth;
+ imageWidth = minSize;
+ }
+ imageView.layout(left, top, left + imageWidth, top + imageHeight);
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/BasicNotificationDisplayActivity.java b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/BasicNotificationDisplayActivity.java
new file mode 100644
index 0000000..d029f43
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/BasicNotificationDisplayActivity.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.widget.TextView;
+
+/**
+ * Custom display activity for a sample notification.
+ */
+public class BasicNotificationDisplayActivity extends Activity {
+ public static final String EXTRA_TITLE = "title";
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_notification_display);
+
+ String title = getIntent().getStringExtra(EXTRA_TITLE);
+
+ ((TextView) findViewById(R.id.title)).setText(title);
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/MainActivity.java b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/MainActivity.java
new file mode 100644
index 0000000..d564e13
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/MainActivity.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Activity;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.RemoteInput;
+import android.content.Context;
+import android.os.Bundle;
+import android.support.wearable.view.WearableListView;
+import android.text.TextUtils;
+import android.view.LayoutInflater;
+import android.view.ViewGroup;
+import android.widget.TextView;
+import android.widget.Toast;
+
+public class MainActivity extends Activity implements WearableListView.ClickListener {
+ private static final int SAMPLE_NOTIFICATION_ID = 0;
+ public static final String KEY_REPLY = "reply";
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ WearableListView listView = (WearableListView) findViewById(R.id.list);
+ listView.setAdapter(new Adapter(this));
+ listView.setClickListener(this);
+ }
+
+ @Override
+ protected void onResume() {
+ super.onResume();
+ if (getIntent() != null) {
+ Bundle inputResults = RemoteInput.getResultsFromIntent(getIntent());
+ if (inputResults != null) {
+ CharSequence replyText = inputResults.getCharSequence(KEY_REPLY);
+ if (replyText != null) {
+ Toast.makeText(this, TextUtils.concat(getString(R.string.reply_was), replyText),
+ Toast.LENGTH_LONG).show();
+ }
+ }
+ }
+ }
+
+ /** Post a new or updated notification using the selected notification options. */
+ private void updateNotification(int presetIndex) {
+ NotificationPreset preset = NotificationPresets.PRESETS[presetIndex];
+ Notification notif = preset.buildNotification(this);
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(SAMPLE_NOTIFICATION_ID, notif);
+ finish();
+ }
+
+ @Override
+ public void onClick(WearableListView.ViewHolder v) {
+ updateNotification((Integer) v.itemView.getTag());
+ }
+
+ @Override
+ public void onTopEmptyRegionClick() {
+ }
+
+ private static final class Adapter extends WearableListView.Adapter {
+ private final Context mContext;
+ private final LayoutInflater mInflater;
+
+ private Adapter(Context context) {
+ mContext = context;
+ mInflater = LayoutInflater.from(context);
+ }
+
+ @Override
+ public WearableListView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+ return new WearableListView.ViewHolder(
+ mInflater.inflate(R.layout.notif_preset_list_item, null));
+ }
+
+ @Override
+ public void onBindViewHolder(WearableListView.ViewHolder holder, int position) {
+ TextView view = (TextView) holder.itemView.findViewById(R.id.name);
+ view.setText(mContext.getString(NotificationPresets.PRESETS[position].nameResId));
+ holder.itemView.setTag(position);
+ }
+
+ @Override
+ public int getItemCount() {
+ return NotificationPresets.PRESETS.length;
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/NotificationPreset.java b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/NotificationPreset.java
new file mode 100644
index 0000000..d6570d5
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/NotificationPreset.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Notification;
+import android.content.Context;
+
+/**
+ * Base class for notification preset generators.
+ */
+public abstract class NotificationPreset {
+ public final int nameResId;
+
+ public NotificationPreset(int nameResId) {
+ this.nameResId = nameResId;
+ }
+
+ /** Start building a notification with this preset */
+ public abstract Notification buildNotification(Context context);
+}
diff --git a/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/NotificationPresets.java b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/NotificationPresets.java
new file mode 100644
index 0000000..5578659
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/NotificationPresets.java
@@ -0,0 +1,314 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.app.RemoteInput;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.BitmapFactory;
+import android.graphics.Color;
+import android.graphics.Typeface;
+import android.net.Uri;
+import android.text.SpannableStringBuilder;
+import android.text.style.ForegroundColorSpan;
+import android.text.style.RelativeSizeSpan;
+import android.text.style.StrikethroughSpan;
+import android.text.style.StyleSpan;
+import android.text.style.SubscriptSpan;
+import android.text.style.SuperscriptSpan;
+import android.text.style.TypefaceSpan;
+import android.text.style.UnderlineSpan;
+import android.util.TypedValue;
+import android.view.Gravity;
+
+/**
+ * Collection of notification builder presets.
+ */
+public class NotificationPresets {
+ public static final NotificationPreset[] PRESETS = new NotificationPreset[] {
+ new BasicPreset(),
+ new StylizedTextPreset(),
+ new DisplayIntentPreset(),
+ new MultiSizeDisplayIntentPreset(),
+ new AnimatedDisplayIntentPreset(),
+ new ContentIconPreset()
+ };
+
+ private static Notification.Builder buildBasicNotification(Context context) {
+ return new Notification.Builder(context)
+ .setContentTitle(context.getString(R.string.example_content_title))
+ .setContentText(context.getString(R.string.example_content_text))
+ // Set a content intent to return to this sample
+ .setContentIntent(PendingIntent.getActivity(context, 0,
+ new Intent(context, MainActivity.class), 0))
+ .setSmallIcon(R.mipmap.ic_launcher);
+ }
+
+ private static class BasicPreset extends NotificationPreset {
+ public BasicPreset() {
+ super(R.string.basic_example);
+ }
+
+ @Override
+ public Notification buildNotification(Context context) {
+ PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
+ new Intent(context, MainActivity.class), 0);
+
+ Notification page2 = buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setHintShowBackgroundOnly(true)
+ .setBackground(BitmapFactory.decodeResource(context.getResources(),
+ R.drawable.example_big_picture)))
+ .build();
+
+ Notification page3 = buildBasicNotification(context)
+ .setContentTitle(context.getString(R.string.third_page))
+ .setContentText(null)
+ .extend(new Notification.WearableExtender()
+ .setContentAction(0 /* action A */))
+ .build();
+
+ SpannableStringBuilder choice2 = new SpannableStringBuilder(
+ "This choice is best");
+ choice2.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 11, 0);
+
+ return buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .addAction(new Notification.Action(R.mipmap.ic_launcher,
+ context.getString(R.string.action_a), pendingIntent))
+ .addAction(new Notification.Action.Builder(R.mipmap.ic_launcher,
+ context.getString(R.string.reply), pendingIntent)
+ .addRemoteInput(new RemoteInput.Builder(MainActivity.KEY_REPLY)
+ .setChoices(new CharSequence[] {
+ context.getString(R.string.choice_1),
+ choice2 })
+ .build())
+ .build())
+ .addPage(page2)
+ .addPage(page3))
+ .build();
+ }
+ }
+
+ private static class StylizedTextPreset extends NotificationPreset {
+ public StylizedTextPreset() {
+ super(R.string.stylized_text_example);
+ }
+
+ @Override
+ public Notification buildNotification(Context context) {
+ Notification.Builder builder = buildBasicNotification(context);
+
+ Notification.BigTextStyle style = new Notification.BigTextStyle();
+
+ SpannableStringBuilder title = new SpannableStringBuilder();
+ appendStyled(title, "Stylized", new StyleSpan(Typeface.BOLD_ITALIC));
+ title.append(" title");
+ SpannableStringBuilder text = new SpannableStringBuilder("Stylized text: ");
+ appendStyled(text, "C", new ForegroundColorSpan(Color.RED));
+ appendStyled(text, "O", new ForegroundColorSpan(Color.GREEN));
+ appendStyled(text, "L", new ForegroundColorSpan(Color.BLUE));
+ appendStyled(text, "O", new ForegroundColorSpan(Color.YELLOW));
+ appendStyled(text, "R", new ForegroundColorSpan(Color.MAGENTA));
+ appendStyled(text, "S", new ForegroundColorSpan(Color.CYAN));
+ text.append("; ");
+ appendStyled(text, "1.25x size", new RelativeSizeSpan(1.25f));
+ text.append("; ");
+ appendStyled(text, "0.75x size", new RelativeSizeSpan(0.75f));
+ text.append("; ");
+ appendStyled(text, "underline", new UnderlineSpan());
+ text.append("; ");
+ appendStyled(text, "strikethrough", new StrikethroughSpan());
+ text.append("; ");
+ appendStyled(text, "bold", new StyleSpan(Typeface.BOLD));
+ text.append("; ");
+ appendStyled(text, "italic", new StyleSpan(Typeface.ITALIC));
+ text.append("; ");
+ appendStyled(text, "sans-serif-thin", new TypefaceSpan("sans-serif-thin"));
+ text.append("; ");
+ appendStyled(text, "monospace", new TypefaceSpan("monospace"));
+ text.append("; ");
+ appendStyled(text, "sub", new SubscriptSpan());
+ text.append("script");
+ appendStyled(text, "super", new SuperscriptSpan());
+
+ style.setBigContentTitle(title);
+ style.bigText(text);
+
+ builder.setStyle(style);
+ return builder.build();
+ }
+
+ private void appendStyled(SpannableStringBuilder builder, String str, Object... spans) {
+ builder.append(str);
+ for (Object span : spans) {
+ builder.setSpan(span, builder.length() - str.length(), builder.length(), 0);
+ }
+ }
+ }
+
+ private static class DisplayIntentPreset extends NotificationPreset {
+ public DisplayIntentPreset() {
+ super(R.string.display_intent_example);
+ }
+
+ @Override
+ public Notification buildNotification(Context context) {
+ Intent displayIntent = new Intent(context, BasicNotificationDisplayActivity.class);
+ displayIntent.putExtra(BasicNotificationDisplayActivity.EXTRA_TITLE,
+ context.getString(nameResId));
+ PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
+ 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+ return buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setDisplayIntent(displayPendingIntent))
+ .build();
+ }
+ }
+
+ private static class MultiSizeDisplayIntentPreset extends NotificationPreset {
+ public MultiSizeDisplayIntentPreset() {
+ super(R.string.multisize_display_intent_example);
+ }
+
+ @Override
+ public Notification buildNotification(Context context) {
+ PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
+ new Intent(context, MainActivity.class), 0);
+ Intent displayIntent = new Intent(context, BasicNotificationDisplayActivity.class)
+ .putExtra(BasicNotificationDisplayActivity.EXTRA_TITLE,
+ context.getString(R.string.xsmall_sized_display));
+ return buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setDisplayIntent(PendingIntent.getActivity(context, 0, displayIntent,
+ PendingIntent.FLAG_UPDATE_CURRENT))
+ .addPage(createPageForSizePreset(context,
+ Notification.WearableExtender.SIZE_SMALL,
+ R.string.small_sized_display, 0))
+ .addPage(createPageForSizePreset(context,
+ Notification.WearableExtender.SIZE_MEDIUM,
+ R.string.medium_sized_display, 1))
+ .addPage(createPageForSizePreset(context,
+ Notification.WearableExtender.SIZE_LARGE,
+ R.string.large_sized_display, 2))
+ .addPage(createPageForSizePreset(context,
+ Notification.WearableExtender.SIZE_FULL_SCREEN,
+ R.string.full_screen_display, 3))
+ .addPage(createPageForCustomHeight(context, 256,
+ R.string.dp256_height_display))
+ .addPage(createPageForCustomHeight(context, 512,
+ R.string.dp512_height_display))
+ .addAction(new Notification.Action(R.mipmap.ic_launcher,
+ context.getString(R.string.action_a), pendingIntent))
+ .addAction(new Notification.Action(R.mipmap.ic_launcher,
+ context.getString(R.string.action_b), pendingIntent))
+ .addAction(new Notification.Action(R.mipmap.ic_launcher,
+ context.getString(R.string.action_c), pendingIntent))
+ .addAction(new Notification.Action(R.mipmap.ic_launcher,
+ context.getString(R.string.action_d), pendingIntent))
+ .setCustomSizePreset(Notification.WearableExtender.SIZE_XSMALL))
+ .build();
+ }
+
+ private Notification createPageForCustomHeight(Context context, int heightDisplayDp,
+ int pageNameResId) {
+ int contentHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
+ heightDisplayDp, context.getResources().getDisplayMetrics());
+ Intent displayIntent = new Intent(context, BasicNotificationDisplayActivity.class)
+ .setData(Uri.fromParts("example", "height/" + heightDisplayDp, null))
+ .putExtra(BasicNotificationDisplayActivity.EXTRA_TITLE,
+ context.getString(pageNameResId));
+ return buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setDisplayIntent(PendingIntent.getActivity(context, 0, displayIntent,
+ PendingIntent.FLAG_UPDATE_CURRENT))
+ .setCustomContentHeight(contentHeight))
+ .build();
+ }
+
+ private Notification createPageForSizePreset(Context context, int sizePreset,
+ int pageNameResId, int contentAction) {
+ Intent displayIntent = new Intent(context, BasicNotificationDisplayActivity.class)
+ .setData(Uri.fromParts("example", "size/" + sizePreset, null))
+ .putExtra(BasicNotificationDisplayActivity.EXTRA_TITLE,
+ context.getString(pageNameResId));
+ return buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setDisplayIntent(PendingIntent.getActivity(context, 0, displayIntent,
+ PendingIntent.FLAG_UPDATE_CURRENT))
+ .setCustomSizePreset(sizePreset)
+ .setContentAction(contentAction))
+ .build();
+ }
+ }
+
+ private static class AnimatedDisplayIntentPreset extends NotificationPreset {
+ public AnimatedDisplayIntentPreset() {
+ super(R.string.animated_display_intent_example);
+ }
+
+ @Override
+ public Notification buildNotification(Context context) {
+ Intent displayIntent = new Intent(context, AnimatedNotificationDisplayActivity.class);
+ displayIntent.putExtra(BasicNotificationDisplayActivity.EXTRA_TITLE,
+ context.getString(nameResId));
+ PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
+ 0, displayIntent, 0);
+ return buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setDisplayIntent(displayPendingIntent))
+ .build();
+ }
+ }
+
+ private static class ContentIconPreset extends NotificationPreset {
+ public ContentIconPreset() {
+ super(R.string.content_icon_example);
+ }
+
+ @Override
+ public Notification buildNotification(Context context) {
+ Notification page2 = buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setContentIcon(R.drawable.content_icon_small)
+ .setContentIconGravity(Gravity.START))
+ .build();
+
+ Notification page3 = buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setContentIcon(R.drawable.content_icon_large))
+ .build();
+
+ Notification page4 = buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setContentIcon(R.drawable.content_icon_large)
+ .setContentIconGravity(Gravity.START))
+ .build();
+
+ return buildBasicNotification(context)
+ .extend(new Notification.WearableExtender()
+ .setHintHideIcon(true)
+ .setContentIcon(R.drawable.content_icon_small)
+ .addPage(page2)
+ .addPage(page3)
+ .addPage(page4))
+ .build();
+ }
+ }
+}
diff --git a/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/WearableListItemLayout.java b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/WearableListItemLayout.java
new file mode 100644
index 0000000..773dfe4
--- /dev/null
+++ b/prebuilts/gradle/Notifications/Wearable/src/main/java/com/example/android/support/wearable/notifications/WearableListItemLayout.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2014 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.example.android.support.wearable.notifications;
+
+import android.content.Context;
+import android.graphics.drawable.GradientDrawable;
+import android.support.wearable.view.WearableListView;
+import android.util.AttributeSet;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+public class WearableListItemLayout extends LinearLayout implements WearableListView.Item {
+
+ private final float mFadedTextAlpha;
+ private final int mFadedCircleColor;
+ private final int mChosenCircleColor;
+ private ImageView mCircle;
+ private float mScale;
+ private TextView mName;
+
+ public WearableListItemLayout(Context context) {
+ this(context, null);
+ }
+
+ public WearableListItemLayout(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public WearableListItemLayout(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ mFadedTextAlpha = getResources().getInteger(R.integer.action_text_faded_alpha) / 100f;
+ mFadedCircleColor = getResources().getColor(R.color.wl_gray);
+ mChosenCircleColor = getResources().getColor(R.color.wl_blue);
+ }
+
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+ mCircle = (ImageView) findViewById(R.id.circle);
+ mName = (TextView) findViewById(R.id.name);
+ }
+
+ @Override
+ public float getProximityMinValue() {
+ return 1f;
+ }
+
+ @Override
+ public float getProximityMaxValue() {
+ return 1.6f;
+ }
+
+ @Override
+ public float getCurrentProximityValue() {
+ return mScale;
+ }
+
+ @Override
+ public void setScalingAnimatorValue(float scale) {
+ mScale = scale;
+ mCircle.setScaleX(scale);
+ mCircle.setScaleY(scale);
+ }
+
+ @Override
+ public void onScaleUpStart() {
+ mName.setAlpha(1f);
+ ((GradientDrawable) mCircle.getDrawable()).setColor(mChosenCircleColor);
+ }
+
+ @Override
+ public void onScaleDownStart() {
+ ((GradientDrawable) mCircle.getDrawable()).setColor(mFadedCircleColor);
+ mName.setAlpha(mFadedTextAlpha);
+ }
+}
diff --git a/prebuilts/gradle/Notifications/screenshots/basic-menu.png b/prebuilts/gradle/Notifications/screenshots/basic-menu.png
new file mode 100644
index 0000000..75c29cc
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/basic-menu.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/basic.png b/prebuilts/gradle/Notifications/screenshots/basic.png
new file mode 100644
index 0000000..9e13b09
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/basic.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/bottom-aligned.png b/prebuilts/gradle/Notifications/screenshots/bottom-aligned.png
new file mode 100644
index 0000000..88c7ffa
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/bottom-aligned.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/bundle.png b/prebuilts/gradle/Notifications/screenshots/bundle.png
new file mode 100644
index 0000000..a6e1ad5
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/bundle.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/companion-bottom-aligned.png b/prebuilts/gradle/Notifications/screenshots/companion-bottom-aligned.png
new file mode 100644
index 0000000..2bda56c
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/companion-bottom-aligned.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/companion-bundle.png b/prebuilts/gradle/Notifications/screenshots/companion-bundle.png
new file mode 100644
index 0000000..90e0e08
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/companion-bundle.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/companion-content-action.png b/prebuilts/gradle/Notifications/screenshots/companion-content-action.png
new file mode 100644
index 0000000..07e6806
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/companion-content-action.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/companion-multiple-page.png b/prebuilts/gradle/Notifications/screenshots/companion-multiple-page.png
new file mode 100644
index 0000000..7f11521
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/companion-multiple-page.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/content-action.png b/prebuilts/gradle/Notifications/screenshots/content-action.png
new file mode 100644
index 0000000..415dd9f
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/content-action.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/content-action2.png b/prebuilts/gradle/Notifications/screenshots/content-action2.png
new file mode 100644
index 0000000..7f01994
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/content-action2.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/content-icon-menu.png b/prebuilts/gradle/Notifications/screenshots/content-icon-menu.png
new file mode 100644
index 0000000..6c810ce
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/content-icon-menu.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/content-icon1.png b/prebuilts/gradle/Notifications/screenshots/content-icon1.png
new file mode 100644
index 0000000..f9d12da
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/content-icon1.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/content-icon2.png b/prebuilts/gradle/Notifications/screenshots/content-icon2.png
new file mode 100644
index 0000000..a36b734
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/content-icon2.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/content-icon3.png b/prebuilts/gradle/Notifications/screenshots/content-icon3.png
new file mode 100644
index 0000000..e2c757e
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/content-icon3.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/content-icon4.png b/prebuilts/gradle/Notifications/screenshots/content-icon4.png
new file mode 100644
index 0000000..f5d0523
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/content-icon4.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/display-intent-menu.png b/prebuilts/gradle/Notifications/screenshots/display-intent-menu.png
new file mode 100644
index 0000000..567673f
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/display-intent-menu.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/display-intent.png b/prebuilts/gradle/Notifications/screenshots/display-intent.png
new file mode 100644
index 0000000..f3b333d
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/display-intent.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/multiple-page1.png b/prebuilts/gradle/Notifications/screenshots/multiple-page1.png
new file mode 100644
index 0000000..d6591d9
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/multiple-page1.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/multiple-page2.png b/prebuilts/gradle/Notifications/screenshots/multiple-page2.png
new file mode 100644
index 0000000..730cb30
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/multiple-page2.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/stylized-menu.png b/prebuilts/gradle/Notifications/screenshots/stylized-menu.png
new file mode 100644
index 0000000..2e94c93
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/stylized-menu.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/screenshots/stylized.png b/prebuilts/gradle/Notifications/screenshots/stylized.png
new file mode 100644
index 0000000..338c9cc
--- /dev/null
+++ b/prebuilts/gradle/Notifications/screenshots/stylized.png
Binary files differ
diff --git a/prebuilts/gradle/Notifications/settings.gradle b/prebuilts/gradle/Notifications/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/Notifications/settings.gradle
+++ b/prebuilts/gradle/Notifications/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/Quiz/Application/build.gradle b/prebuilts/gradle/Quiz/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/Quiz/Application/build.gradle
+++ b/prebuilts/gradle/Quiz/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/Quiz/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/Quiz/Application/src/main/AndroidManifest.xml
index 40e3602..0d14a71 100644
--- a/prebuilts/gradle/Quiz/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Quiz/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.quiz" >
+ package="com.example.android.wearable.quiz" >
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application
android:allowBackup="true"
@@ -29,7 +29,7 @@
android:value="@integer/google_play_services_version" />
<activity
- android:name="com.example.android.quiz.MainActivity"
+ android:name="com.example.android.wearable.quiz.MainActivity"
android:label="@string/app_name"
android:windowSoftInputMode="stateHidden"
android:configChanges="keyboardHidden|orientation|screenSize" >
diff --git a/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/Constants.java b/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/Constants.java
new file mode 100644
index 0000000..2bcfe5f
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/Constants.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+/** Constants used in the companion app. */
+public final class Constants {
+ private Constants() {
+ }
+
+ public static final String ANSWERS = "answers";
+ public static final String CHOSEN_ANSWER_CORRECT = "chosen_answer_correct";
+ public static final String CORRECT_ANSWER_INDEX = "correct_answer_index";
+ public static final String QUESTION = "question";
+ public static final String QUESTION_INDEX = "question_index";
+ public static final String QUESTION_WAS_ANSWERED = "question_was_answered";
+ public static final String QUESTION_WAS_DELETED = "question_was_deleted";
+
+ public static final String NUM_CORRECT = "num_correct";
+ public static final String NUM_INCORRECT = "num_incorrect";
+ public static final String NUM_SKIPPED = "num_skipped";
+
+ public static final String QUIZ_ENDED_PATH = "/quiz_ended";
+ public static final String QUIZ_EXITED_PATH = "/quiz_exited";
+ public static final String RESET_QUIZ_PATH = "/reset_quiz";
+}
diff --git a/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/JsonUtils.java b/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/JsonUtils.java
new file mode 100644
index 0000000..df8c899
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/JsonUtils.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+import android.content.Context;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+final class JsonUtils {
+ public static final String JSON_FIELD_QUESTIONS = "questions";
+ public static final String JSON_FIELD_QUESTION = "question";
+ public static final String JSON_FIELD_ANSWERS = "answers";
+ public static final String JSON_FIELD_CORRECT_INDEX = "correctIndex";
+ public static final int NUM_ANSWER_CHOICES = 4;
+
+ private JsonUtils() {
+ }
+
+ public static JSONObject loadJsonFile(Context context, String fileName) throws IOException,
+ JSONException {
+ InputStream is = context.getAssets().open(fileName);
+ int size = is.available();
+ byte[] buffer = new byte[size];
+ is.read(buffer);
+ is.close();
+ String jsonString = new String(buffer);
+ return new JSONObject(jsonString);
+ }
+}
diff --git a/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/MainActivity.java b/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/MainActivity.java
new file mode 100644
index 0000000..0ff41f4
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Application/src/main/java/com/example/android/wearable/quiz/MainActivity.java
@@ -0,0 +1,585 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+import static com.example.android.wearable.quiz.Constants.ANSWERS;
+import static com.example.android.wearable.quiz.Constants.CHOSEN_ANSWER_CORRECT;
+import static com.example.android.wearable.quiz.Constants.CORRECT_ANSWER_INDEX;
+import static com.example.android.wearable.quiz.Constants.NUM_CORRECT;
+import static com.example.android.wearable.quiz.Constants.NUM_INCORRECT;
+import static com.example.android.wearable.quiz.Constants.NUM_SKIPPED;
+import static com.example.android.wearable.quiz.Constants.QUESTION;
+import static com.example.android.wearable.quiz.Constants.QUESTION_INDEX;
+import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_ANSWERED;
+import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_DELETED;
+import static com.example.android.wearable.quiz.Constants.QUIZ_ENDED_PATH;
+import static com.example.android.wearable.quiz.Constants.QUIZ_EXITED_PATH;
+import static com.example.android.wearable.quiz.Constants.RESET_QUIZ_PATH;
+
+import android.app.Activity;
+import android.graphics.Color;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.Button;
+import android.widget.EditText;
+import android.widget.LinearLayout;
+import android.widget.RadioGroup;
+import android.widget.TextView;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.common.data.FreezableUtils;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.DataItem;
+import com.google.android.gms.wearable.DataItemBuffer;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.DataMapItem;
+import com.google.android.gms.wearable.MessageApi;
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.NodeApi;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.PutDataRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.PriorityQueue;
+
+/**
+ * Allows the user to create questions, which will be put as notifications on the watch's stream.
+ * The status of questions will be updated on the phone when the user answers them.
+ */
+public class MainActivity extends Activity implements DataApi.DataListener,
+ MessageApi.MessageListener, ConnectionCallbacks,
+ GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String TAG = "ExampleQuizApp";
+ private static final String QUIZ_JSON_FILE = "Quiz.json";
+
+ // Various UI components.
+ private EditText questionEditText;
+ private EditText choiceAEditText;
+ private EditText choiceBEditText;
+ private EditText choiceCEditText;
+ private EditText choiceDEditText;
+ private RadioGroup choicesRadioGroup;
+ private TextView quizStatus;
+ private LinearLayout quizButtons;
+ private LinearLayout questionsContainer;
+ private Button readQuizFromFileButton;
+ private Button resetQuizButton;
+
+ private GoogleApiClient mGoogleApiClient;
+ private PriorityQueue<Question> mFutureQuestions;
+ private int mQuestionIndex = 0;
+ private boolean mHasQuestionBeenAsked = false;
+
+ // Data to display in end report.
+ private int mNumCorrect = 0;
+ private int mNumIncorrect = 0;
+ private int mNumSkipped = 0;
+
+ private static final Map<Integer, Integer> radioIdToIndex;
+
+ static {
+ Map<Integer, Integer> temp = new HashMap<Integer, Integer>(4);
+ temp.put(R.id.choice_a_radio, 0);
+ temp.put(R.id.choice_b_radio, 1);
+ temp.put(R.id.choice_c_radio, 2);
+ temp.put(R.id.choice_d_radio, 3);
+ radioIdToIndex = Collections.unmodifiableMap(temp);
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.main);
+
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ mFutureQuestions = new PriorityQueue<Question>(10);
+
+ // Find UI components to be used later.
+ questionEditText = (EditText) findViewById(R.id.question_text);
+ choiceAEditText = (EditText) findViewById(R.id.choice_a_text);
+ choiceBEditText = (EditText) findViewById(R.id.choice_b_text);
+ choiceCEditText = (EditText) findViewById(R.id.choice_c_text);
+ choiceDEditText = (EditText) findViewById(R.id.choice_d_text);
+ choicesRadioGroup = (RadioGroup) findViewById(R.id.choices_radio_group);
+ quizStatus = (TextView) findViewById(R.id.quiz_status);
+ quizButtons = (LinearLayout) findViewById(R.id.quiz_buttons);
+ questionsContainer = (LinearLayout) findViewById(R.id.questions_container);
+ readQuizFromFileButton = (Button) findViewById(R.id.read_quiz_from_file_button);
+ resetQuizButton = (Button) findViewById(R.id.reset_quiz_button);
+ }
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ if (!mGoogleApiClient.isConnected()) {
+ mGoogleApiClient.connect();
+ }
+ }
+
+ @Override
+ protected void onStop() {
+ Wearable.DataApi.removeListener(mGoogleApiClient, this);
+ Wearable.MessageApi.removeListener(mGoogleApiClient, this);
+
+ // Tell the wearable to end the quiz (counting unanswered questions as skipped), and then
+ // disconnect mGoogleApiClient.
+ DataMap dataMap = new DataMap();
+ dataMap.putInt(NUM_CORRECT, mNumCorrect);
+ dataMap.putInt(NUM_INCORRECT, mNumIncorrect);
+ if (mHasQuestionBeenAsked) {
+ mNumSkipped += 1;
+ }
+ mNumSkipped += mFutureQuestions.size();
+ dataMap.putInt(NUM_SKIPPED, mNumSkipped);
+ if (mNumCorrect + mNumIncorrect + mNumSkipped > 0) {
+ sendMessageToWearable(QUIZ_EXITED_PATH, dataMap.toByteArray());
+ }
+
+ clearQuizStatus();
+ super.onStop();
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ Wearable.DataApi.addListener(mGoogleApiClient, this);
+ Wearable.MessageApi.addListener(mGoogleApiClient, this);
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ // Ignore
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ Log.e(TAG, "Failed to connect to Google Play Services");
+ }
+
+ @Override
+ public void onMessageReceived(MessageEvent messageEvent) {
+ if (messageEvent.getPath().equals(RESET_QUIZ_PATH)) {
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ resetQuiz(null);
+ }
+ });
+ }
+ }
+
+ /**
+ * Used to ensure questions with smaller indexes come before questions with larger
+ * indexes. For example, question0 should come before question1.
+ */
+ private static class Question implements Comparable<Question> {
+ private String question;
+ private int questionIndex;
+ private String[] answers;
+ private int correctAnswerIndex;
+
+ public Question(String question, int questionIndex, String[] answers,
+ int correctAnswerIndex) {
+ this.question = question;
+ this.questionIndex = questionIndex;
+ this.answers = answers;
+ this.correctAnswerIndex = correctAnswerIndex;
+ }
+
+ public static Question fromJson(JSONObject questionObject, int questionIndex)
+ throws JSONException {
+ String question = questionObject.getString(JsonUtils.JSON_FIELD_QUESTION);
+ JSONArray answersJsonArray = questionObject.getJSONArray(JsonUtils.JSON_FIELD_ANSWERS);
+ String[] answers = new String[JsonUtils.NUM_ANSWER_CHOICES];
+ for (int j = 0; j < answersJsonArray.length(); j++) {
+ answers[j] = answersJsonArray.getString(j);
+ }
+ int correctIndex = questionObject.getInt(JsonUtils.JSON_FIELD_CORRECT_INDEX);
+ return new Question(question, questionIndex, answers, correctIndex);
+ }
+
+ @Override
+ public int compareTo(Question that) {
+ return this.questionIndex - that.questionIndex;
+ }
+
+ public PutDataRequest toPutDataRequest() {
+ PutDataMapRequest request = PutDataMapRequest.create("/question/" + questionIndex);
+ DataMap dataMap = request.getDataMap();
+ dataMap.putString(QUESTION, question);
+ dataMap.putInt(QUESTION_INDEX, questionIndex);
+ dataMap.putStringArray(ANSWERS, answers);
+ dataMap.putInt(CORRECT_ANSWER_INDEX, correctAnswerIndex);
+ return request.asPutDataRequest();
+ }
+ }
+
+ /**
+ * Create a quiz, as defined in Quiz.json, when the user clicks on "Read quiz from file."
+ * @throws IOException
+ */
+ public void readQuizFromFile(View view) throws IOException, JSONException {
+ clearQuizStatus();
+ JSONObject jsonObject = JsonUtils.loadJsonFile(this, QUIZ_JSON_FILE);
+ JSONArray jsonArray = jsonObject.getJSONArray(JsonUtils.JSON_FIELD_QUESTIONS);
+ for (int i = 0; i < jsonArray.length(); i++) {
+ JSONObject questionObject = jsonArray.getJSONObject(i);
+ Question question = Question.fromJson(questionObject, mQuestionIndex++);
+ addQuestionDataItem(question);
+ setNewQuestionStatus(question.question);
+ }
+ }
+
+ /**
+ * Adds a question (with answer choices) when user clicks on "Add Question."
+ */
+ public void addQuestion(View view) {
+ // Retrieve the question and answers supplied by the user.
+ String question = questionEditText.getText().toString();
+ String[] answers = new String[4];
+ answers[0] = choiceAEditText.getText().toString();
+ answers[1] = choiceBEditText.getText().toString();
+ answers[2] = choiceCEditText.getText().toString();
+ answers[3] = choiceDEditText.getText().toString();
+ int correctAnswerIndex = radioIdToIndex.get(choicesRadioGroup.getCheckedRadioButtonId());
+
+ addQuestionDataItem(new Question(question, mQuestionIndex++, answers, correctAnswerIndex));
+ setNewQuestionStatus(question);
+
+ // Clear the edit boxes to let the user input a new question.
+ questionEditText.setText("");
+ choiceAEditText.setText("");
+ choiceBEditText.setText("");
+ choiceCEditText.setText("");
+ choiceDEditText.setText("");
+ }
+
+ /**
+ * Adds the questions (and answers) to the wearable's stream by creating a Data Item
+ * that will be received on the wearable, which will create corresponding notifications.
+ */
+ private void addQuestionDataItem(Question question) {
+ if (!mHasQuestionBeenAsked) {
+ // Ask the question now.
+ Wearable.DataApi.putDataItem(mGoogleApiClient, question.toPutDataRequest());
+ setHasQuestionBeenAsked(true);
+ } else {
+ // Enqueue the question to be asked in the future.
+ mFutureQuestions.add(question);
+ }
+ }
+
+ /**
+ * Sets the question's status to be the default "unanswered." This will be updated when the
+ * user chooses an answer for the question on the wearable.
+ */
+ private void setNewQuestionStatus(String question) {
+ quizStatus.setVisibility(View.VISIBLE);
+ quizButtons.setVisibility(View.VISIBLE);
+ LayoutInflater inflater = LayoutInflater.from(this);
+ View questionStatusElem = inflater.inflate(R.layout.question_status_element, null, false);
+ ((TextView) questionStatusElem.findViewById(R.id.question)).setText(question);
+ ((TextView) questionStatusElem.findViewById(R.id.status))
+ .setText(R.string.question_unanswered);
+ questionsContainer.addView(questionStatusElem);
+ }
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
+ dataEvents.close();
+ runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ for (DataEvent event : events) {
+ if (event.getType() == DataEvent.TYPE_CHANGED) {
+ DataMap dataMap = DataMapItem.fromDataItem(event.getDataItem())
+ .getDataMap();
+ boolean questionWasAnswered = dataMap.getBoolean(QUESTION_WAS_ANSWERED);
+ boolean questionWasDeleted = dataMap.getBoolean(QUESTION_WAS_DELETED);
+ if (questionWasAnswered) {
+ // Update the answered question's status.
+ int questionIndex = dataMap.getInt(QUESTION_INDEX);
+ boolean questionCorrect = dataMap.getBoolean(CHOSEN_ANSWER_CORRECT);
+ updateQuestionStatus(questionIndex, questionCorrect);
+ askNextQuestionIfExists();
+ } else if (questionWasDeleted) {
+ // Update the deleted question's status by marking it as left blank.
+ int questionIndex = dataMap.getInt(QUESTION_INDEX);
+ markQuestionLeftBlank(questionIndex);
+ askNextQuestionIfExists();
+ }
+ }
+ }
+ }
+ });
+ }
+
+ /**
+ * Updates the given question based on whether it was answered correctly or not.
+ * This involves changing the question's text color and changing the status text for it.
+ */
+ public void updateQuestionStatus(int questionIndex, boolean questionCorrect) {
+ LinearLayout questionStatusElement = (LinearLayout)
+ questionsContainer.getChildAt(questionIndex);
+ TextView questionText = (TextView) questionStatusElement.findViewById(R.id.question);
+ TextView questionStatus = (TextView) questionStatusElement.findViewById(R.id.status);
+ if (questionCorrect) {
+ questionText.setTextColor(Color.GREEN);
+ questionStatus.setText(R.string.question_correct);
+ mNumCorrect++;
+ } else {
+ questionText.setTextColor(Color.RED);
+ questionStatus.setText(R.string.question_incorrect);
+ mNumIncorrect++;
+ }
+ }
+
+ /**
+ * Marks a question as "left blank" when its corresponding question notification is deleted.
+ */
+ private void markQuestionLeftBlank(int index) {
+ LinearLayout questionStatusElement = (LinearLayout) questionsContainer.getChildAt(index);
+ if (questionStatusElement != null) {
+ TextView questionText = (TextView) questionStatusElement.findViewById(R.id.question);
+ TextView questionStatus = (TextView) questionStatusElement.findViewById(R.id.status);
+ if (questionStatus.getText().equals(getString(R.string.question_unanswered))) {
+ questionText.setTextColor(Color.YELLOW);
+ questionStatus.setText(R.string.question_left_blank);
+ mNumSkipped++;
+ }
+ }
+ }
+
+ /**
+ * Asks the next enqueued question if it exists, otherwise ends the quiz.
+ */
+ private void askNextQuestionIfExists() {
+ if (mFutureQuestions.isEmpty()) {
+ // Quiz has been completed - send message to wearable to display end report.
+ DataMap dataMap = new DataMap();
+ dataMap.putInt(NUM_CORRECT, mNumCorrect);
+ dataMap.putInt(NUM_INCORRECT, mNumIncorrect);
+ dataMap.putInt(NUM_SKIPPED, mNumSkipped);
+ sendMessageToWearable(QUIZ_ENDED_PATH, dataMap.toByteArray());
+ setHasQuestionBeenAsked(false);
+ } else {
+ // Ask next question by putting a DataItem that will be received on the wearable.
+ Wearable.DataApi.putDataItem(mGoogleApiClient,
+ mFutureQuestions.remove().toPutDataRequest());
+ setHasQuestionBeenAsked(true);
+ }
+ }
+
+ private void sendMessageToWearable(final String path, final byte[] data) {
+ Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(
+ new ResultCallback<NodeApi.GetConnectedNodesResult>() {
+ @Override
+ public void onResult(NodeApi.GetConnectedNodesResult nodes) {
+ for (Node node : nodes.getNodes()) {
+ Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), path, data);
+ }
+
+ if (path.equals(QUIZ_EXITED_PATH) && mGoogleApiClient.isConnected()) {
+ mGoogleApiClient.disconnect();
+ }
+ }
+ });
+ }
+
+ /**
+ * Resets the current quiz when Reset Quiz is pressed.
+ */
+ public void resetQuiz(View view) {
+ // Reset quiz status in phone layout.
+ for(int i = 0; i < questionsContainer.getChildCount(); i++) {
+ LinearLayout questionStatusElement = (LinearLayout) questionsContainer.getChildAt(i);
+ TextView questionText = (TextView) questionStatusElement.findViewById(R.id.question);
+ TextView questionStatus = (TextView) questionStatusElement.findViewById(R.id.status);
+ questionText.setTextColor(Color.WHITE);
+ questionStatus.setText(R.string.question_unanswered);
+ }
+ // Reset data items and notifications on wearable.
+ if (mGoogleApiClient.isConnected()) {
+ Wearable.DataApi.getDataItems(mGoogleApiClient)
+ .setResultCallback(new ResultCallback<DataItemBuffer>() {
+ @Override
+ public void onResult(DataItemBuffer result) {
+ if (result.getStatus().isSuccess()) {
+ List<DataItem> dataItemList = FreezableUtils.freezeIterable(result);
+ result.close();
+ resetDataItems(dataItemList);
+ } else {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Reset quiz: failed to get Data Items to reset");
+ }
+ }
+ result.close();
+ }
+ });
+ } else {
+ Log.e(TAG, "Failed to reset data items because client is disconnected from "
+ + "Google Play Services");
+ }
+ setHasQuestionBeenAsked(false);
+ mNumCorrect = 0;
+ mNumIncorrect = 0;
+ mNumSkipped = 0;
+ }
+
+ private void resetDataItems(List<DataItem> dataItemList) {
+ if (mGoogleApiClient.isConnected()) {
+ for (final DataItem dataItem : dataItemList) {
+ final Uri dataItemUri = dataItem.getUri();
+ Wearable.DataApi.getDataItem(mGoogleApiClient, dataItemUri)
+ .setResultCallback(new ResetDataItemCallback());
+ }
+ } else {
+ Log.e(TAG, "Failed to reset data items because client is disconnected from "
+ + "Google Play Services");
+ }
+ }
+
+ /**
+ * Callback that marks a DataItem, which represents a question, as unanswered and not deleted.
+ */
+ private class ResetDataItemCallback implements ResultCallback<DataApi.DataItemResult> {
+ @Override
+ public void onResult(DataApi.DataItemResult dataItemResult) {
+ if (dataItemResult.getStatus().isSuccess()) {
+ PutDataMapRequest request = PutDataMapRequest.createFromDataMapItem(
+ DataMapItem.fromDataItem(dataItemResult.getDataItem()));
+ DataMap dataMap = request.getDataMap();
+ dataMap.putBoolean(QUESTION_WAS_ANSWERED, false);
+ dataMap.putBoolean(QUESTION_WAS_DELETED, false);
+ if (!mHasQuestionBeenAsked && dataMap.getInt(QUESTION_INDEX) == 0) {
+ // Ask the first question now.
+ Wearable.DataApi.putDataItem(mGoogleApiClient, request.asPutDataRequest());
+ setHasQuestionBeenAsked(true);
+ } else {
+ // Enqueue future questions.
+ mFutureQuestions.add(new Question(dataMap.getString(QUESTION),
+ dataMap.getInt(QUESTION_INDEX), dataMap.getStringArray(ANSWERS),
+ dataMap.getInt(CORRECT_ANSWER_INDEX)));
+ }
+ } else {
+ Log.e(TAG, "Failed to reset data item " + dataItemResult.getDataItem().getUri());
+ }
+ }
+ }
+
+ /**
+ * Clears the current quiz when user clicks on "New Quiz."
+ * On this end, this involves clearing the quiz status layout and deleting all DataItems. The
+ * wearable will then remove any outstanding question notifications upon receiving this change.
+ */
+ public void newQuiz(View view) {
+ clearQuizStatus();
+ if (mGoogleApiClient.isConnected()) {
+ Wearable.DataApi.getDataItems(mGoogleApiClient)
+ .setResultCallback(new ResultCallback<DataItemBuffer>() {
+ @Override
+ public void onResult(DataItemBuffer result) {
+ if (result.getStatus().isSuccess()) {
+ List<Uri> dataItemUriList = new ArrayList<Uri>();
+ for (final DataItem dataItem : result) {
+ dataItemUriList.add(dataItem.getUri());
+ }
+ result.close();
+ deleteDataItems(dataItemUriList);
+ } else {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Clear quiz: failed to get Data Items for deletion");
+ }
+ }
+ result.close();
+ }
+ });
+ } else {
+ Log.e(TAG, "Failed to delete data items because client is disconnected from "
+ + "Google Play Services");
+ }
+ }
+
+ /**
+ * Removes quiz status views (i.e. the views describing the status of each question).
+ */
+ private void clearQuizStatus() {
+ questionsContainer.removeAllViews();
+ quizStatus.setVisibility(View.INVISIBLE);
+ quizButtons.setVisibility(View.INVISIBLE);
+ setHasQuestionBeenAsked(false);
+ mFutureQuestions.clear();
+ mQuestionIndex = 0;
+ mNumCorrect = 0;
+ mNumIncorrect = 0;
+ mNumSkipped = 0;
+ }
+
+ private void deleteDataItems(List<Uri> dataItemUriList) {
+ if (mGoogleApiClient.isConnected()) {
+ for (final Uri dataItemUri : dataItemUriList) {
+ Wearable.DataApi.deleteDataItems(mGoogleApiClient, dataItemUri)
+ .setResultCallback(new ResultCallback<DataApi.DeleteDataItemsResult>() {
+ @Override
+ public void onResult(DataApi.DeleteDataItemsResult deleteResult) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ if (deleteResult.getStatus().isSuccess()) {
+ Log.d(TAG, "Successfully deleted data item " + dataItemUri);
+ } else {
+ Log.d(TAG, "Failed to delete data item " + dataItemUri);
+ }
+ }
+ }
+ });
+ }
+ } else {
+ Log.e(TAG, "Failed to delete data items because client is disconnected from "
+ + "Google Play Services");
+ }
+ }
+
+ private void setHasQuestionBeenAsked(boolean b) {
+ mHasQuestionBeenAsked = b;
+ // Only let user click on Reset or Read from file if they have answered all the questions.
+ readQuizFromFileButton.setEnabled(!mHasQuestionBeenAsked);
+ resetQuizButton.setEnabled(!mHasQuestionBeenAsked);
+ }
+}
diff --git a/prebuilts/gradle/Quiz/Wearable/build.gradle b/prebuilts/gradle/Quiz/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/Quiz/Wearable/build.gradle
+++ b/prebuilts/gradle/Quiz/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/Quiz/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/Quiz/Wearable/src/main/AndroidManifest.xml
index 7954e32..fd20def 100644
--- a/prebuilts/gradle/Quiz/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Quiz/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.quiz" >
+ package="com.example.android.wearable.quiz" >
<uses-sdk android:minSdkVersion="20"
diff --git a/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/Constants.java b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/Constants.java
new file mode 100644
index 0000000..8b81f59
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/Constants.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+/** Constants used in the wearable app. */
+public final class Constants {
+ private Constants() {
+ }
+
+ public static final String ANSWERS = "answers";
+ public static final String CHOSEN_ANSWER_CORRECT = "chosen_answer_correct";
+ public static final String CORRECT_ANSWER_INDEX = "correct_answer_index";
+ public static final String QUESTION = "question";
+ public static final String QUESTION_INDEX = "question_index";
+ public static final String QUESTION_WAS_ANSWERED = "question_was_answered";
+ public static final String QUESTION_WAS_DELETED = "question_was_deleted";
+
+ public static final String NUM_CORRECT = "num_correct";
+ public static final String NUM_INCORRECT = "num_incorrect";
+ public static final String NUM_SKIPPED = "num_skipped";
+
+ public static final String QUIZ_ENDED_PATH = "/quiz_ended";
+ public static final String QUIZ_EXITED_PATH = "/quiz_exited";
+ public static final String RESET_QUIZ_PATH = "/reset_quiz";
+
+ public static final int CONNECT_TIMEOUT_MS = 100;
+}
diff --git a/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/DeleteQuestionService.java b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/DeleteQuestionService.java
new file mode 100644
index 0000000..78e81ca
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/DeleteQuestionService.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+import android.app.IntentService;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.DataMapItem;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.PutDataRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import java.util.concurrent.TimeUnit;
+
+import static com.example.android.wearable.quiz.Constants.CONNECT_TIMEOUT_MS;
+import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_DELETED;
+
+/**
+ * Used to update quiz status on the phone when user dismisses a question on the watch.
+ */
+public class DeleteQuestionService extends IntentService
+ implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String TAG = "DeleteQuestionReceiver";
+
+ private GoogleApiClient mGoogleApiClient;
+
+ public DeleteQuestionService() {
+ super(DeleteQuestionService.class.getSimpleName());
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ public void onHandleIntent(Intent intent) {
+ mGoogleApiClient.blockingConnect(CONNECT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ Uri dataItemUri = intent.getData();
+ if (!mGoogleApiClient.isConnected()) {
+ Log.e(TAG, "Failed to update data item " + dataItemUri
+ + " because client is disconnected from Google Play Services");
+ return;
+ }
+ DataApi.DataItemResult dataItemResult = Wearable.DataApi.getDataItem(
+ mGoogleApiClient, dataItemUri).await();
+ PutDataMapRequest putDataMapRequest = PutDataMapRequest
+ .createFromDataMapItem(DataMapItem.fromDataItem(dataItemResult.getDataItem()));
+ DataMap dataMap = putDataMapRequest.getDataMap();
+ dataMap.putBoolean(QUESTION_WAS_DELETED, true);
+ PutDataRequest request = putDataMapRequest.asPutDataRequest();
+ Wearable.DataApi.putDataItem(mGoogleApiClient, request).await();
+ mGoogleApiClient.disconnect();
+ }
+
+ @Override
+ public void onConnected(Bundle bundle) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int i) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult connectionResult) {
+ }
+}
diff --git a/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/QuizListenerService.java b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/QuizListenerService.java
new file mode 100644
index 0000000..020a37b
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/QuizListenerService.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+import static com.example.android.wearable.quiz.Constants.ANSWERS;
+import static com.example.android.wearable.quiz.Constants.CONNECT_TIMEOUT_MS;
+import static com.example.android.wearable.quiz.Constants.CORRECT_ANSWER_INDEX;
+import static com.example.android.wearable.quiz.Constants.NUM_CORRECT;
+import static com.example.android.wearable.quiz.Constants.NUM_INCORRECT;
+import static com.example.android.wearable.quiz.Constants.NUM_SKIPPED;
+import static com.example.android.wearable.quiz.Constants.QUESTION;
+import static com.example.android.wearable.quiz.Constants.QUESTION_INDEX;
+import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_ANSWERED;
+import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_DELETED;
+import static com.example.android.wearable.quiz.Constants.QUIZ_ENDED_PATH;
+import static com.example.android.wearable.quiz.Constants.QUIZ_EXITED_PATH;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.net.Uri;
+import android.text.SpannableStringBuilder;
+import android.text.style.ForegroundColorSpan;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.data.FreezableUtils;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.DataItem;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.DataMapItem;
+import com.google.android.gms.wearable.MessageEvent;
+import com.google.android.gms.wearable.Wearable;
+import com.google.android.gms.wearable.WearableListenerService;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Listens to changes in DataItems, which represent quiz questions.
+ * If a new question is created, this builds a new notification for it.
+ * Otherwise, if a question is deleted, this cancels the corresponding notification.
+ *
+ * When the quiz ends, this listener receives a message telling it to create an end-of-quiz report.
+ */
+public class QuizListenerService extends WearableListenerService {
+ private static final String TAG = "QuizSample";
+ private static final int QUIZ_REPORT_NOTIF_ID = -1; // Never used by question notifications.
+ private static final Map<Integer, Integer> questionNumToDrawableId;
+
+ static {
+ Map<Integer, Integer> temp = new HashMap<Integer, Integer>(4);
+ temp.put(0, R.drawable.ic_choice_a);
+ temp.put(1, R.drawable.ic_choice_b);
+ temp.put(2, R.drawable.ic_choice_c);
+ temp.put(3, R.drawable.ic_choice_d);
+ questionNumToDrawableId = Collections.unmodifiableMap(temp);
+ }
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
+ dataEvents.close();
+
+ GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .build();
+
+ ConnectionResult connectionResult = googleApiClient.blockingConnect(CONNECT_TIMEOUT_MS,
+ TimeUnit.MILLISECONDS);
+ if (!connectionResult.isSuccess()) {
+ Log.e(TAG, "QuizListenerService failed to connect to GoogleApiClient.");
+ return;
+ }
+
+ for (DataEvent event : events) {
+ if (event.getType() == DataEvent.TYPE_CHANGED) {
+ DataItem dataItem = event.getDataItem();
+ DataMap dataMap = DataMapItem.fromDataItem(dataItem).getDataMap();
+ if (dataMap.getBoolean(QUESTION_WAS_ANSWERED)
+ || dataMap.getBoolean(QUESTION_WAS_DELETED)) {
+ // Ignore the change in data; it is used in MainActivity to update
+ // the question's status (i.e. was the answer right or wrong or left blank).
+ continue;
+ }
+ String question = dataMap.getString(QUESTION);
+ int questionIndex = dataMap.getInt(QUESTION_INDEX);
+ int questionNum = questionIndex + 1;
+ String[] answers = dataMap.getStringArray(ANSWERS);
+ int correctAnswerIndex = dataMap.getInt(CORRECT_ANSWER_INDEX);
+ Intent deleteOperation = new Intent(this, DeleteQuestionService.class);
+ deleteOperation.setData(dataItem.getUri());
+ PendingIntent deleteIntent = PendingIntent.getService(this, 0,
+ deleteOperation, PendingIntent.FLAG_UPDATE_CURRENT);
+ // First page of notification contains question as Big Text.
+ Notification.BigTextStyle bigTextStyle = new Notification.BigTextStyle()
+ .setBigContentTitle(getString(R.string.question, questionNum))
+ .bigText(question);
+ Notification.Builder builder = new Notification.Builder(this)
+ .setStyle(bigTextStyle)
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setLocalOnly(true)
+ .setDeleteIntent(deleteIntent);
+
+ // Add answers as actions.
+ Notification.WearableExtender wearableOptions = new Notification.WearableExtender();
+ for (int i = 0; i < answers.length; i++) {
+ Notification answerPage = new Notification.Builder(this)
+ .setContentTitle(question)
+ .setContentText(answers[i])
+ .extend(new Notification.WearableExtender()
+ .setContentAction(i))
+ .build();
+
+ boolean correct = (i == correctAnswerIndex);
+ Intent updateOperation = new Intent(this, UpdateQuestionService.class);
+ // Give each intent a unique action.
+ updateOperation.setAction("question_" + questionIndex + "_answer_" + i);
+ updateOperation.setData(dataItem.getUri());
+ updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_INDEX,
+ questionIndex);
+ updateOperation.putExtra(UpdateQuestionService.EXTRA_QUESTION_CORRECT, correct);
+ PendingIntent updateIntent = PendingIntent.getService(this, 0, updateOperation,
+ PendingIntent.FLAG_UPDATE_CURRENT);
+ Notification.Action action = new Notification.Action.Builder(
+ questionNumToDrawableId.get(i), null, updateIntent)
+ .build();
+ wearableOptions.addAction(action).addPage(answerPage);
+ }
+ builder.extend(wearableOptions);
+ Notification notification = builder.build();
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(questionIndex, notification);
+ } else if (event.getType() == DataEvent.TYPE_DELETED) {
+ Uri uri = event.getDataItem().getUri();
+ // URI's are of the form "/question/0", "/question/1" etc.
+ // We use the question index as the notification id.
+ int notificationId = Integer.parseInt(uri.getLastPathSegment());
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .cancel(notificationId);
+ }
+ // Delete the quiz report, if it exists.
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .cancel(QUIZ_REPORT_NOTIF_ID);
+ }
+ googleApiClient.disconnect();
+ }
+
+ @Override
+ public void onMessageReceived(MessageEvent messageEvent) {
+ String path = messageEvent.getPath();
+ if (path.equals(QUIZ_EXITED_PATH)) {
+ // Remove any lingering question notifications.
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll();
+ }
+ if (path.equals(QUIZ_ENDED_PATH) || path.equals(QUIZ_EXITED_PATH)) {
+ // Quiz ended - display overall results.
+ DataMap dataMap = DataMap.fromByteArray(messageEvent.getData());
+ int numCorrect = dataMap.getInt(NUM_CORRECT);
+ int numIncorrect = dataMap.getInt(NUM_INCORRECT);
+ int numSkipped = dataMap.getInt(NUM_SKIPPED);
+
+ Notification.Builder builder = new Notification.Builder(this)
+ .setContentTitle(getString(R.string.quiz_report))
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setLocalOnly(true);
+ SpannableStringBuilder quizReportText = new SpannableStringBuilder();
+ appendColored(quizReportText, String.valueOf(numCorrect), R.color.dark_green);
+ quizReportText.append(" " + getString(R.string.correct) + "\n");
+ appendColored(quizReportText, String.valueOf(numIncorrect), R.color.dark_red);
+ quizReportText.append(" " + getString(R.string.incorrect) + "\n");
+ appendColored(quizReportText, String.valueOf(numSkipped), R.color.dark_yellow);
+ quizReportText.append(" " + getString(R.string.skipped) + "\n");
+
+ builder.setContentText(quizReportText);
+ if (!path.equals(QUIZ_EXITED_PATH)) {
+ // Don't add reset option if user exited quiz (there might not be a quiz to reset!).
+ builder.addAction(R.drawable.ic_launcher,
+ getString(R.string.reset_quiz), getResetQuizPendingIntent());
+ }
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(QUIZ_REPORT_NOTIF_ID, builder.build());
+ }
+ }
+
+ private void appendColored(SpannableStringBuilder builder, String text, int colorResId) {
+ builder.append(text).setSpan(new ForegroundColorSpan(getResources().getColor(colorResId)),
+ builder.length() - text.length(), builder.length(), 0);
+ }
+
+ /**
+ * Returns a PendingIntent that will send a message to the phone to reset the quiz when fired.
+ */
+ private PendingIntent getResetQuizPendingIntent() {
+ Intent intent = new Intent(QuizReportActionService.ACTION_RESET_QUIZ)
+ .setClass(this, QuizReportActionService.class);
+ return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
+ }
+}
diff --git a/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/QuizReportActionService.java b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/QuizReportActionService.java
new file mode 100644
index 0000000..956bdaf
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/QuizReportActionService.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+import android.app.IntentService;
+import android.content.Intent;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.Node;
+import com.google.android.gms.wearable.NodeApi;
+import com.google.android.gms.wearable.Wearable;
+
+import java.util.concurrent.TimeUnit;
+
+import static com.example.android.wearable.quiz.Constants.CONNECT_TIMEOUT_MS;
+import static com.example.android.wearable.quiz.Constants.RESET_QUIZ_PATH;
+
+/**
+ * Service to reset the quiz (by sending a message to the phone) when the Reset Quiz
+ * action on the Quiz Report is selected.
+ */
+public class QuizReportActionService extends IntentService {
+ public static final String ACTION_RESET_QUIZ = "com.example.android.wearable.quiz.RESET_QUIZ";
+
+ private static final String TAG = "QuizReportActionReceiver";
+
+ public QuizReportActionService() {
+ super(QuizReportActionService.class.getSimpleName());
+ }
+
+ @Override
+ public void onHandleIntent(Intent intent) {
+ if (intent.getAction().equals(ACTION_RESET_QUIZ)) {
+ GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .build();
+ ConnectionResult result = googleApiClient.blockingConnect(CONNECT_TIMEOUT_MS,
+ TimeUnit.MILLISECONDS);
+ if (!result.isSuccess()) {
+ Log.e(TAG, "QuizListenerService failed to connect to GoogleApiClient.");
+ return;
+ }
+ NodeApi.GetConnectedNodesResult nodes =
+ Wearable.NodeApi.getConnectedNodes(googleApiClient).await();
+ for (Node node : nodes.getNodes()) {
+ Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), RESET_QUIZ_PATH,
+ new byte[0]);
+ }
+ }
+ }
+}
diff --git a/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/UpdateQuestionService.java b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/UpdateQuestionService.java
new file mode 100644
index 0000000..e06c303
--- /dev/null
+++ b/prebuilts/gradle/Quiz/Wearable/src/main/java/com/example/android/wearable/quiz/UpdateQuestionService.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.quiz;
+
+import android.app.IntentService;
+import android.app.NotificationManager;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.DataMapItem;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.PutDataRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import java.util.concurrent.TimeUnit;
+
+import static com.example.android.wearable.quiz.Constants.CHOSEN_ANSWER_CORRECT;
+import static com.example.android.wearable.quiz.Constants.QUESTION_INDEX;
+import static com.example.android.wearable.quiz.Constants.QUESTION_WAS_ANSWERED;
+
+/**
+ * Updates quiz status on the phone when user selects an answer to a question on the watch.
+ */
+public class UpdateQuestionService extends IntentService
+ implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
+ public static final String EXTRA_QUESTION_CORRECT = "extra_question_correct";
+ public static final String EXTRA_QUESTION_INDEX = "extra_question_index";
+
+ private static final long TIME_OUT_MS = 100;
+ private static final String TAG = "UpdateQuestionService";
+
+ private GoogleApiClient mGoogleApiClient;
+
+ public UpdateQuestionService() {
+ super(UpdateQuestionService.class.getSimpleName());
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ mGoogleApiClient.blockingConnect(TIME_OUT_MS, TimeUnit.MILLISECONDS);
+ Uri dataItemUri = intent.getData();
+ if (!mGoogleApiClient.isConnected()) {
+ Log.e(TAG, "Failed to update data item " + dataItemUri
+ + " because client is disconnected from Google Play Services");
+ return;
+ }
+ DataApi.DataItemResult dataItemResult = Wearable.DataApi.getDataItem(
+ mGoogleApiClient, dataItemUri).await();
+ PutDataMapRequest putDataMapRequest = PutDataMapRequest
+ .createFromDataMapItem(DataMapItem.fromDataItem(dataItemResult.getDataItem()));
+ DataMap dataMap = putDataMapRequest.getDataMap();
+
+ // Update quiz status variables, which will be reflected on the phone.
+ int questionIndex = intent.getIntExtra(EXTRA_QUESTION_INDEX, -1);
+ boolean chosenAnswerCorrect = intent.getBooleanExtra(EXTRA_QUESTION_CORRECT, false);
+ dataMap.putInt(QUESTION_INDEX, questionIndex);
+ dataMap.putBoolean(CHOSEN_ANSWER_CORRECT, chosenAnswerCorrect);
+ dataMap.putBoolean(QUESTION_WAS_ANSWERED, true);
+ PutDataRequest request = putDataMapRequest.asPutDataRequest();
+ Wearable.DataApi.putDataItem(mGoogleApiClient, request).await();
+
+ // Remove this question notification.
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(questionIndex);
+ mGoogleApiClient.disconnect();
+ }
+
+ @Override
+ public void onConnected(Bundle connectionHint) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int cause) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult result) {
+ }
+}
diff --git a/prebuilts/gradle/Quiz/screenshots/companion_quiz.png b/prebuilts/gradle/Quiz/screenshots/companion_quiz.png
new file mode 100644
index 0000000..15f7e80
--- /dev/null
+++ b/prebuilts/gradle/Quiz/screenshots/companion_quiz.png
Binary files differ
diff --git a/prebuilts/gradle/Quiz/screenshots/companion_quiz_correct_status.png b/prebuilts/gradle/Quiz/screenshots/companion_quiz_correct_status.png
new file mode 100644
index 0000000..c0e25ca
--- /dev/null
+++ b/prebuilts/gradle/Quiz/screenshots/companion_quiz_correct_status.png
Binary files differ
diff --git a/prebuilts/gradle/Quiz/screenshots/wearable_quiz.png b/prebuilts/gradle/Quiz/screenshots/wearable_quiz.png
new file mode 100644
index 0000000..0c63139
--- /dev/null
+++ b/prebuilts/gradle/Quiz/screenshots/wearable_quiz.png
Binary files differ
diff --git a/prebuilts/gradle/Quiz/screenshots/wearable_quiz_answer.png b/prebuilts/gradle/Quiz/screenshots/wearable_quiz_answer.png
new file mode 100644
index 0000000..eb47516
--- /dev/null
+++ b/prebuilts/gradle/Quiz/screenshots/wearable_quiz_answer.png
Binary files differ
diff --git a/prebuilts/gradle/Quiz/screenshots/wearable_quiz_report.png b/prebuilts/gradle/Quiz/screenshots/wearable_quiz_report.png
new file mode 100644
index 0000000..196d045
--- /dev/null
+++ b/prebuilts/gradle/Quiz/screenshots/wearable_quiz_report.png
Binary files differ
diff --git a/prebuilts/gradle/Quiz/settings.gradle b/prebuilts/gradle/Quiz/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/Quiz/settings.gradle
+++ b/prebuilts/gradle/Quiz/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/RecipeAssistant/Application/build.gradle b/prebuilts/gradle/RecipeAssistant/Application/build.gradle
index c50e592..75a4852 100644
--- a/prebuilts/gradle/RecipeAssistant/Application/build.gradle
+++ b/prebuilts/gradle/RecipeAssistant/Application/build.gradle
@@ -13,7 +13,7 @@
dependencies {
- // Add the support lib that is appropriate for SDK 20
+ // Add the support lib that is appropriate for SDK 18
compile "com.android.support:support-v13:20.+"
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/RecipeAssistant/Application/src/main/AndroidManifest.xml
index db13ed9..a9199ed 100644
--- a/prebuilts/gradle/RecipeAssistant/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/AndroidManifest.xml
@@ -15,10 +15,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.recipeassistant" >
+ package="com.example.android.wearable.recipeassistant" >
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application
android:allowBackup="true"
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/AssetUtils.java b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/AssetUtils.java
new file mode 100644
index 0000000..8753582
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/AssetUtils.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.recipeassistant;
+
+import android.content.Context;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.util.Log;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+final class AssetUtils {
+ private static final String TAG = "RecipeAssistant";
+
+ public static byte[] loadAsset(Context context, String asset) {
+ byte[] buffer = null;
+ try {
+ InputStream is = context.getAssets().open(asset);
+ int size = is.available();
+ buffer = new byte[size];
+ is.read(buffer);
+ is.close();
+ } catch (IOException e) {
+ Log.e(TAG, "Failed to load asset " + asset + ": " + e);
+ }
+ return buffer;
+ }
+
+ public static JSONObject loadJSONAsset(Context context, String asset) {
+ String jsonString = new String(loadAsset(context, asset));
+ JSONObject jsonObject = null;
+ try {
+ jsonObject = new JSONObject(jsonString);
+ } catch (JSONException e) {
+ Log.e(TAG, "Failed to parse JSON asset " + asset + ": " + e);
+ }
+ return jsonObject;
+ }
+
+ public static Bitmap loadBitmapAsset(Context context, String asset) {
+ InputStream is = null;
+ Bitmap bitmap = null;
+ try {
+ is = context.getAssets().open(asset);
+ if (is != null) {
+ bitmap = BitmapFactory.decodeStream(is);
+ }
+ } catch (IOException e) {
+ Log.e(TAG, e.toString());
+ } finally {
+ if (is != null) {
+ try {
+ is.close();
+ } catch (IOException e) {
+ Log.e(TAG, "Cannot close InputStream: ", e);
+ }
+ }
+ }
+ return bitmap;
+ }
+}
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/Constants.java b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/Constants.java
new file mode 100644
index 0000000..fae49ee
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/Constants.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.recipeassistant;
+
+public final class Constants {
+ private Constants() {
+ }
+ public static final String RECIPE_LIST_FILE = "recipelist.json";
+ public static final String RECIPE_NAME_TO_LOAD = "recipe_name";
+
+ public static final String RECIPE_FIELD_LIST = "recipe_list";
+ public static final String RECIPE_FIELD_IMAGE = "img";
+ public static final String RECIPE_FIELD_INGREDIENTS = "ingredients";
+ public static final String RECIPE_FIELD_NAME = "name";
+ public static final String RECIPE_FIELD_SUMMARY = "summary";
+ public static final String RECIPE_FIELD_STEPS = "steps";
+ public static final String RECIPE_FIELD_TEXT = "text";
+ public static final String RECIPE_FIELD_TITLE = "title";
+ public static final String RECIPE_FIELD_STEP_TEXT = "step_text";
+ public static final String RECIPE_FIELD_STEP_IMAGE = "step_image";
+
+ static final String ACTION_START_COOKING =
+ "com.example.android.wearable.recipeassistant.START_COOKING";
+ public static final String EXTRA_RECIPE = "recipe";
+
+ public static final int NOTIFICATION_ID = 0;
+ public static final int NOTIFICATION_IMAGE_WIDTH = 280;
+ public static final int NOTIFICATION_IMAGE_HEIGHT = 280;
+}
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/MainActivity.java b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/MainActivity.java
new file mode 100644
index 0000000..4cc860f
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/MainActivity.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.recipeassistant;
+
+import android.app.ListActivity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.View;
+import android.widget.ListView;
+
+public class MainActivity extends ListActivity {
+
+ private static final String TAG = "RecipeAssistant";
+ private RecipeListAdapter mAdapter;
+
+ @Override
+ protected void onListItemClick(ListView l, View v, int position, long id) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG , "onListItemClick " + position);
+ }
+ String itemName = mAdapter.getItemName(position);
+ Intent intent = new Intent(getApplicationContext(), RecipeActivity.class);
+ intent.putExtra(Constants.RECIPE_NAME_TO_LOAD, itemName);
+ startActivity(intent);
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(android.R.layout.list_content);
+
+ mAdapter = new RecipeListAdapter(this);
+ setListAdapter(mAdapter);
+ }
+}
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/Recipe.java b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/Recipe.java
new file mode 100644
index 0000000..e470c0f
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/Recipe.java
@@ -0,0 +1,126 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.recipeassistant;
+
+import android.content.Context;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.util.Log;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+
+public class Recipe {
+ private static final String TAG = "RecipeAssistant";
+
+ public String titleText;
+ public String summaryText;
+ public String recipeImage;
+ public String ingredientsText;
+
+ public static class RecipeStep {
+ RecipeStep() { }
+ public String stepImage;
+ public String stepText;
+
+ public Bundle toBundle() {
+ Bundle bundle = new Bundle();
+ bundle.putString(Constants.RECIPE_FIELD_STEP_TEXT, stepText);
+ bundle.putString(Constants.RECIPE_FIELD_STEP_IMAGE, stepImage);
+ return bundle;
+ }
+
+ public static RecipeStep fromBundle(Bundle bundle) {
+ RecipeStep recipeStep = new RecipeStep();
+ recipeStep.stepText = bundle.getString(Constants.RECIPE_FIELD_STEP_TEXT);
+ recipeStep.stepImage = bundle.getString(Constants.RECIPE_FIELD_STEP_IMAGE);
+ return recipeStep;
+ }
+ }
+ ArrayList<RecipeStep> recipeSteps;
+
+ public Recipe() {
+ recipeSteps = new ArrayList<RecipeStep>();
+ }
+
+ public static Recipe fromJson(Context context, JSONObject json) {
+ Recipe recipe = new Recipe();
+ try {
+ recipe.titleText = json.getString(Constants.RECIPE_FIELD_TITLE);
+ recipe.summaryText = json.getString(Constants.RECIPE_FIELD_SUMMARY);
+ if (json.has(Constants.RECIPE_FIELD_IMAGE)) {
+ recipe.recipeImage = json.getString(Constants.RECIPE_FIELD_IMAGE);
+ }
+ JSONArray ingredients = json.getJSONArray(Constants.RECIPE_FIELD_INGREDIENTS);
+ recipe.ingredientsText = "";
+ for (int i = 0; i < ingredients.length(); i++) {
+ recipe.ingredientsText += " - "
+ + ingredients.getJSONObject(i).getString(Constants.RECIPE_FIELD_TEXT) + "\n";
+ }
+
+ JSONArray steps = json.getJSONArray(Constants.RECIPE_FIELD_STEPS);
+ for (int i = 0; i < steps.length(); i++) {
+ JSONObject step = steps.getJSONObject(i);
+ RecipeStep recipeStep = new RecipeStep();
+ recipeStep.stepText = step.getString(Constants.RECIPE_FIELD_TEXT);
+ if (step.has(Constants.RECIPE_FIELD_IMAGE)) {
+ recipeStep.stepImage = step.getString(Constants.RECIPE_FIELD_IMAGE);
+ }
+ recipe.recipeSteps.add(recipeStep);
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, "Error loading recipe: " + e);
+ return null;
+ }
+ return recipe;
+ }
+
+ public Bundle toBundle() {
+ Bundle bundle = new Bundle();
+ bundle.putString(Constants.RECIPE_FIELD_TITLE, titleText);
+ bundle.putString(Constants.RECIPE_FIELD_SUMMARY, summaryText);
+ bundle.putString(Constants.RECIPE_FIELD_IMAGE, recipeImage);
+ bundle.putString(Constants.RECIPE_FIELD_INGREDIENTS, ingredientsText);
+ if (recipeSteps != null) {
+ ArrayList<Parcelable> stepBundles = new ArrayList<Parcelable>(recipeSteps.size());
+ for (RecipeStep recipeStep : recipeSteps) {
+ stepBundles.add(recipeStep.toBundle());
+ }
+ bundle.putParcelableArrayList(Constants.RECIPE_FIELD_STEPS, stepBundles);
+ }
+ return bundle;
+ }
+
+ public static Recipe fromBundle(Bundle bundle) {
+ Recipe recipe = new Recipe();
+ recipe.titleText = bundle.getString(Constants.RECIPE_FIELD_TITLE);
+ recipe.summaryText = bundle.getString(Constants.RECIPE_FIELD_SUMMARY);
+ recipe.recipeImage = bundle.getString(Constants.RECIPE_FIELD_IMAGE);
+ recipe.ingredientsText = bundle.getString(Constants.RECIPE_FIELD_INGREDIENTS);
+ ArrayList<Parcelable> stepBundles =
+ bundle.getParcelableArrayList(Constants.RECIPE_FIELD_STEPS);
+ if (stepBundles != null) {
+ for (Parcelable stepBundle : stepBundles) {
+ recipe.recipeSteps.add(RecipeStep.fromBundle((Bundle) stepBundle));
+ }
+ }
+ return recipe;
+ }
+}
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeActivity.java b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeActivity.java
new file mode 100644
index 0000000..cc7f034
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeActivity.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.recipeassistant;
+
+import android.app.Activity;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.animation.Animation;
+import android.view.animation.AnimationUtils;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+import org.json.JSONObject;
+
+public class RecipeActivity extends Activity {
+ private static final String TAG = "RecipeAssistant";
+ private String mRecipeName;
+ private Recipe mRecipe;
+ private ImageView mImageView;
+ private TextView mTitleTextView;
+ private TextView mSummaryTextView;
+ private TextView mIngredientsTextView;
+ private LinearLayout mStepsLayout;
+
+ @Override
+ protected void onStart() {
+ super.onStart();
+ Intent intent = getIntent();
+ mRecipeName = intent.getStringExtra(Constants.RECIPE_NAME_TO_LOAD);
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Intent: " + intent.toString() + " " + mRecipeName);
+ }
+ loadRecipe();
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.recipe);
+ mTitleTextView = (TextView) findViewById(R.id.recipeTextTitle);
+ mSummaryTextView = (TextView) findViewById(R.id.recipeTextSummary);
+ mImageView = (ImageView) findViewById(R.id.recipeImageView);
+ mIngredientsTextView = (TextView) findViewById(R.id.textIngredients);
+ mStepsLayout = (LinearLayout) findViewById(R.id.layoutSteps);
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ // Inflate the menu; this adds items to the action bar if it is present.
+ getMenuInflater().inflate(R.menu.main, menu);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch(item.getItemId()) {
+ case R.id.action_cook:
+ startCooking();
+ return true;
+ }
+ return super.onOptionsItemSelected(item);
+ }
+
+ private void loadRecipe() {
+ JSONObject jsonObject = AssetUtils.loadJSONAsset(this, mRecipeName);
+ if (jsonObject != null) {
+ mRecipe = Recipe.fromJson(this, jsonObject);
+ if (mRecipe != null) {
+ displayRecipe(mRecipe);
+ }
+ }
+ }
+
+ private void displayRecipe(Recipe recipe) {
+ Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
+ mTitleTextView.setAnimation(fadeIn);
+ mTitleTextView.setText(recipe.titleText);
+ mSummaryTextView.setText(recipe.summaryText);
+ if (recipe.recipeImage != null) {
+ mImageView.setAnimation(fadeIn);
+ Bitmap recipeImage = AssetUtils.loadBitmapAsset(this, recipe.recipeImage);
+ mImageView.setImageBitmap(recipeImage);
+ }
+ mIngredientsTextView.setText(recipe.ingredientsText);
+
+ findViewById(R.id.ingredientsHeader).setAnimation(fadeIn);
+ findViewById(R.id.ingredientsHeader).setVisibility(View.VISIBLE);
+ findViewById(R.id.stepsHeader).setAnimation(fadeIn);
+
+ findViewById(R.id.stepsHeader).setVisibility(View.VISIBLE);
+
+ LayoutInflater inf = LayoutInflater.from(this);
+ mStepsLayout.removeAllViews();
+ int stepNumber = 1;
+ for (Recipe.RecipeStep step : recipe.recipeSteps) {
+ View view = inf.inflate(R.layout.step_item, null);
+ ImageView iv = (ImageView) view.findViewById(R.id.stepImageView);
+ if (step.stepImage == null) {
+ iv.setVisibility(View.GONE);
+ } else {
+ Bitmap stepImage = AssetUtils.loadBitmapAsset(this, step.stepImage);
+ iv.setImageBitmap(stepImage);
+ }
+ ((TextView) view.findViewById(R.id.textStep)).setText(
+ (stepNumber++) + ". " + step.stepText);
+ mStepsLayout.addView(view);
+ }
+ }
+
+ private void startCooking() {
+ Intent intent = new Intent(this, RecipeService.class);
+ intent.setAction(Constants.ACTION_START_COOKING);
+ intent.putExtra(Constants.EXTRA_RECIPE, mRecipe.toBundle());
+ startService(intent);
+ }
+}
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeListAdapter.java b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeListAdapter.java
new file mode 100644
index 0000000..746603a
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeListAdapter.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.recipeassistant;
+
+import android.content.Context;
+import android.database.DataSetObserver;
+import android.graphics.Bitmap;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ImageView;
+import android.widget.ListAdapter;
+import android.widget.TextView;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class RecipeListAdapter implements ListAdapter {
+ private String TAG = "RecipeListAdapter";
+
+ private class Item {
+ String title;
+ String name;
+ String summary;
+ Bitmap image;
+ }
+
+ private List<Item> mItems = new ArrayList<Item>();
+ private Context mContext;
+ private DataSetObserver mObserver;
+
+ public RecipeListAdapter(Context context) {
+ mContext = context;
+ loadRecipeList();
+ }
+
+ private void loadRecipeList() {
+ JSONObject jsonObject = AssetUtils.loadJSONAsset(mContext, Constants.RECIPE_LIST_FILE);
+ if (jsonObject != null) {
+ List<Item> items = parseJson(jsonObject);
+ appendItemsToList(items);
+ }
+ }
+
+ private List<Item> parseJson(JSONObject json) {
+ List<Item> result = new ArrayList<Item>();
+ try {
+ JSONArray items = json.getJSONArray(Constants.RECIPE_FIELD_LIST);
+ for (int i = 0; i < items.length(); i++) {
+ JSONObject item = items.getJSONObject(i);
+ Item parsed = new Item();
+ parsed.name = item.getString(Constants.RECIPE_FIELD_NAME);
+ parsed.title = item.getString(Constants.RECIPE_FIELD_TITLE);
+ if (item.has(Constants.RECIPE_FIELD_IMAGE)) {
+ String imageFile = item.getString(Constants.RECIPE_FIELD_IMAGE);
+ parsed.image = AssetUtils.loadBitmapAsset(mContext, imageFile);
+ }
+ parsed.summary = item.getString(Constants.RECIPE_FIELD_SUMMARY);
+ result.add(parsed);
+ }
+ } catch (JSONException e) {
+ Log.e(TAG, "Failed to parse recipe list: " + e);
+ }
+ return result;
+ }
+
+ private void appendItemsToList(List<Item> items) {
+ mItems.addAll(items);
+ if (mObserver != null) {
+ mObserver.onChanged();
+ }
+ }
+
+ @Override
+ public int getCount() {
+ return mItems.size();
+ }
+
+ @Override
+ public Object getItem(int position) {
+ return mItems.get(position);
+ }
+
+ @Override
+ public long getItemId(int position) {
+ return 0;
+ }
+
+ @Override
+ public int getItemViewType(int position) {
+ return 0;
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ View view = convertView;
+ if (view == null) {
+ LayoutInflater inf = LayoutInflater.from(mContext);
+ view = inf.inflate(R.layout.list_item, null);
+ }
+ Item item = (Item) getItem(position);
+ TextView titleView = (TextView) view.findViewById(R.id.textTitle);
+ TextView summaryView = (TextView) view.findViewById(R.id.textSummary);
+ ImageView iv = (ImageView) view.findViewById(R.id.imageView);
+
+ titleView.setText(item.title);
+ summaryView.setText(item.summary);
+ if (item.image != null) {
+ iv.setImageBitmap(item.image);
+ } else {
+ iv.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_noimage));
+ }
+ return view;
+ }
+
+ @Override
+ public int getViewTypeCount() {
+ return 1;
+ }
+
+ @Override
+ public boolean hasStableIds() {
+ return false;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return mItems.isEmpty();
+ }
+
+ @Override
+ public void registerDataSetObserver(DataSetObserver observer) {
+ mObserver = observer;
+ }
+
+ @Override
+ public void unregisterDataSetObserver(DataSetObserver observer) {
+ mObserver = null;
+ }
+
+ @Override
+ public boolean areAllItemsEnabled() {
+ return true;
+ }
+
+ @Override
+ public boolean isEnabled(int position) {
+ return true;
+ }
+
+ public String getItemName(int position) {
+ return mItems.get(position).name;
+ }
+}
diff --git a/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeService.java b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeService.java
new file mode 100644
index 0000000..4abdf97
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/Application/src/main/java/com/example/android/wearable/recipeassistant/RecipeService.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.recipeassistant;
+
+import android.app.Notification;
+import android.app.Service;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.os.Binder;
+import android.os.IBinder;
+import android.support.v4.app.NotificationManagerCompat;
+import android.support.v4.app.NotificationCompat;
+
+import java.util.ArrayList;
+
+public class RecipeService extends Service {
+ private NotificationManagerCompat mNotificationManager;
+ private Binder mBinder = new LocalBinder();
+ private Recipe mRecipe;
+
+ public class LocalBinder extends Binder {
+ RecipeService getService() {
+ return RecipeService.this;
+ }
+ }
+
+ @Override
+ public void onCreate() {
+ mNotificationManager = NotificationManagerCompat.from(this);
+ }
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return mBinder;
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ if (intent.getAction().equals(Constants.ACTION_START_COOKING)) {
+ createNotification(intent);
+ return START_STICKY;
+ }
+ return START_NOT_STICKY;
+ }
+
+ private void createNotification(Intent intent) {
+ mRecipe = Recipe.fromBundle(intent.getBundleExtra(Constants.EXTRA_RECIPE));
+ ArrayList<Notification> notificationPages = new ArrayList<Notification>();
+
+ int stepCount = mRecipe.recipeSteps.size();
+
+ for (int i = 0; i < stepCount; ++i) {
+ Recipe.RecipeStep recipeStep = mRecipe.recipeSteps.get(i);
+ NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
+ style.bigText(recipeStep.stepText);
+ style.setBigContentTitle(String.format(
+ getResources().getString(R.string.step_count), i + 1, stepCount));
+ style.setSummaryText("");
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
+ builder.setStyle(style);
+ notificationPages.add(builder.build());
+ }
+
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
+
+ if (mRecipe.recipeImage != null) {
+ Bitmap recipeImage = Bitmap.createScaledBitmap(
+ AssetUtils.loadBitmapAsset(this, mRecipe.recipeImage),
+ Constants.NOTIFICATION_IMAGE_WIDTH, Constants.NOTIFICATION_IMAGE_HEIGHT, false);
+ builder.setLargeIcon(recipeImage);
+ }
+ builder.setContentTitle(mRecipe.titleText);
+ builder.setContentText(mRecipe.summaryText);
+ builder.setSmallIcon(R.mipmap.ic_notification_recipe);
+
+ Notification notification = builder
+ .extend(new NotificationCompat.WearableExtender()
+ .addPages(notificationPages))
+ .build();
+ mNotificationManager.notify(Constants.NOTIFICATION_ID, notification);
+ }
+}
diff --git a/prebuilts/gradle/RecipeAssistant/screenshots/guac_notification.png b/prebuilts/gradle/RecipeAssistant/screenshots/guac_notification.png
new file mode 100644
index 0000000..e041b11
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/screenshots/guac_notification.png
Binary files differ
diff --git a/prebuilts/gradle/RecipeAssistant/screenshots/guac_notification_step1.png b/prebuilts/gradle/RecipeAssistant/screenshots/guac_notification_step1.png
new file mode 100644
index 0000000..e0157ea
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/screenshots/guac_notification_step1.png
Binary files differ
diff --git a/prebuilts/gradle/RecipeAssistant/screenshots/recipe_assistant_guac.png b/prebuilts/gradle/RecipeAssistant/screenshots/recipe_assistant_guac.png
new file mode 100644
index 0000000..a34da6e
--- /dev/null
+++ b/prebuilts/gradle/RecipeAssistant/screenshots/recipe_assistant_guac.png
Binary files differ
diff --git a/prebuilts/gradle/SkeletonWearableApp/Application/build.gradle b/prebuilts/gradle/SkeletonWearableApp/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/SkeletonWearableApp/Application/build.gradle
+++ b/prebuilts/gradle/SkeletonWearableApp/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/SkeletonWearableApp/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/SkeletonWearableApp/Application/src/main/AndroidManifest.xml
index 7e19680..757c92e 100644
--- a/prebuilts/gradle/SkeletonWearableApp/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/SkeletonWearableApp/Application/src/main/AndroidManifest.xml
@@ -16,10 +16,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.skeletonwearableapp">
+ package="com.example.android.google.wearable.app">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application android:allowBackup="true"
android:label="@string/app_name">
diff --git a/prebuilts/gradle/SkeletonWearableApp/Wearable/build.gradle b/prebuilts/gradle/SkeletonWearableApp/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/SkeletonWearableApp/Wearable/build.gradle
+++ b/prebuilts/gradle/SkeletonWearableApp/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/AndroidManifest.xml
index 3e9310e..bf1c1a4 100644
--- a/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.skeletonwearableapp" >
+ package="com.example.android.google.wearable.app" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -42,7 +42,7 @@
<activity
android:name=".GridExampleActivity">
<intent-filter>
- <action android:name="com.example.android.skeletonwearableapp.GRID_ACTIVITY"/>
+ <action android:name="com.example.android.google.wearable.app.GRID_ACTIVITY"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
diff --git a/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/java/com/example/android/google/wearable/app/GridExampleActivity.java b/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/java/com/example/android/google/wearable/app/GridExampleActivity.java
new file mode 100644
index 0000000..0a88c04
--- /dev/null
+++ b/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/java/com/example/android/google/wearable/app/GridExampleActivity.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2014 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.example.android.google.wearable.app;
+
+import android.app.Activity;
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.graphics.Bitmap;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Paint;
+import android.graphics.Point;
+import android.graphics.Typeface;
+import android.os.Bundle;
+import android.support.wearable.view.CardFragment;
+import android.support.wearable.view.FragmentGridPagerAdapter;
+import android.support.wearable.view.GridViewPager;
+import android.support.wearable.view.ImageReference;
+import java.util.HashMap;
+import java.util.Map;
+
+public class GridExampleActivity extends Activity {
+ private static final int NUM_ROWS = 10;
+ private static final int NUM_COLS = 3;
+
+ MainAdapter mAdapter;
+ GridViewPager mPager;
+
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.grid_activity);
+ mPager = (GridViewPager) findViewById(R.id.fragment_container);
+ mAdapter = new MainAdapter(getFragmentManager());
+ mPager.setAdapter(mAdapter);
+
+ }
+
+ private static class MainAdapter extends FragmentGridPagerAdapter{
+ Map<Point, ImageReference> mBackgrounds = new HashMap<Point, ImageReference>();
+
+ public MainAdapter(FragmentManager fm) {
+ super(fm);
+ }
+
+ @Override
+ public int getRowCount() {
+ return NUM_ROWS;
+ }
+
+ @Override
+ public int getColumnCount(int rowNum) {
+ return NUM_COLS;
+ }
+
+ @Override
+ public Fragment getFragment(int rowNum, int colNum) {
+ return MainFragment.newInstance(rowNum, colNum);
+ }
+
+ @Override
+ public ImageReference getBackground(int row, int column) {
+ Point pt = new Point(column, row);
+ ImageReference ref = mBackgrounds.get(pt);
+ if (ref == null) {
+ Bitmap bm = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
+ Canvas c = new Canvas(bm);
+ Paint p = new Paint();
+ // Clear previous image.
+ c.drawRect(0, 0, 200, 200, p);
+ p.setAntiAlias(true);
+ p.setTypeface(Typeface.DEFAULT);
+ p.setTextSize(64);
+ p.setColor(Color.LTGRAY);
+ c.drawText(column+ "-" + row, 20, 100, p);
+ ref = ImageReference.forBitmap(bm);
+ mBackgrounds.put(pt, ref);
+ }
+ return ref;
+ }
+ }
+
+ public static class MainFragment extends CardFragment {
+ private static MainFragment newInstance(int rowNum, int colNum) {
+ Bundle args = new Bundle();
+ args.putString(CardFragment.KEY_TITLE, "Row:" + rowNum);
+ args.putString(CardFragment.KEY_TEXT, "Col:" + colNum);
+ MainFragment f = new MainFragment();
+ f.setArguments(args);
+ return f;
+ }
+ }
+}
diff --git a/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/java/com/example/android/google/wearable/app/MainActivity.java b/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/java/com/example/android/google/wearable/app/MainActivity.java
new file mode 100644
index 0000000..817e195
--- /dev/null
+++ b/prebuilts/gradle/SkeletonWearableApp/Wearable/src/main/java/com/example/android/google/wearable/app/MainActivity.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2014 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.example.android.google.wearable.app;
+
+import android.app.Activity;
+import android.app.Notification;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.v4.app.NotificationCompat;
+import android.support.v4.app.NotificationManagerCompat;
+import android.support.v4.view.GestureDetectorCompat;
+import android.support.wearable.view.DelayedConfirmationView;
+import android.support.wearable.view.DismissOverlayView;
+import android.util.Log;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
+import android.view.View;
+import android.widget.ScrollView;
+
+public class MainActivity extends Activity
+ implements DelayedConfirmationView.DelayedConfirmationListener {
+ private static final String TAG = "MainActivity";
+
+ private static final int NOTIFICATION_ID = 1;
+ private static final int NOTIFICATION_REQUEST_CODE = 1;
+ private static final int NUM_SECONDS = 5;
+
+ private GestureDetectorCompat mGestureDetector;
+ private DismissOverlayView mDismissOverlayView;
+
+ @Override
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ setContentView(R.layout.main_activity);
+
+ mDismissOverlayView = (DismissOverlayView) findViewById(R.id.dismiss_overlay);
+ mDismissOverlayView.setIntroText(R.string.intro_text);
+ mDismissOverlayView.showIntroIfNecessary();
+ mGestureDetector = new GestureDetectorCompat(this, new LongPressListener());
+ }
+
+ @Override
+ public boolean dispatchTouchEvent(MotionEvent event) {
+ return mGestureDetector.onTouchEvent(event) || super.dispatchTouchEvent(event);
+ }
+
+ private class LongPressListener extends GestureDetector.SimpleOnGestureListener {
+ @Override
+ public void onLongPress(MotionEvent event) {
+ mDismissOverlayView.show();
+ }
+ }
+
+ /**
+ * Handles the button to launch a notification.
+ */
+ public void showNotification(View view) {
+ Notification notification = new NotificationCompat.Builder(this)
+ .setContentTitle(getString(R.string.notification_title))
+ .setContentText(getString(R.string.notification_title))
+ .setSmallIcon(R.drawable.ic_launcher)
+ .addAction(R.drawable.ic_launcher,
+ getText(R.string.action_launch_activity),
+ PendingIntent.getActivity(this, NOTIFICATION_REQUEST_CODE,
+ new Intent(this, GridExampleActivity.class),
+ PendingIntent.FLAG_UPDATE_CURRENT))
+ .build();
+ NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification);
+ finish();
+ }
+
+
+ /**
+ * Handles the button press to finish this activity and take the user back to the Home.
+ */
+ public void onFinishActivity(View view) {
+ setResult(RESULT_OK);
+ finish();
+ }
+
+ /**
+ * Handles the button to start a DelayedConfirmationView timer.
+ */
+ public void onStartTimer(View view) {
+ DelayedConfirmationView delayedConfirmationView = (DelayedConfirmationView)
+ findViewById(R.id.timer);
+ delayedConfirmationView.setTotalTimeMs(NUM_SECONDS * 1000);
+ delayedConfirmationView.setListener(this);
+ delayedConfirmationView.start();
+ scroll(View.FOCUS_DOWN);
+ }
+
+ @Override
+ public void onTimerFinished(View v) {
+ Log.d(TAG, "onTimerFinished is called.");
+ scroll(View.FOCUS_UP);
+ }
+
+ @Override
+ public void onTimerSelected(View v) {
+ Log.d(TAG, "onTimerSelected is called.");
+ scroll(View.FOCUS_UP);
+ }
+
+ private void scroll(final int scrollDirection) {
+ final ScrollView scrollView = (ScrollView) findViewById(R.id.scroll);
+ scrollView.post(new Runnable() {
+ @Override
+ public void run() {
+ scrollView.fullScroll(scrollDirection);
+ }
+ });
+ }
+}
diff --git a/prebuilts/gradle/SkeletonWearableApp/screenshots/delayed_confirmation.png b/prebuilts/gradle/SkeletonWearableApp/screenshots/delayed_confirmation.png
new file mode 100644
index 0000000..2994361
--- /dev/null
+++ b/prebuilts/gradle/SkeletonWearableApp/screenshots/delayed_confirmation.png
Binary files differ
diff --git a/prebuilts/gradle/SkeletonWearableApp/screenshots/dismiss_overlay.png b/prebuilts/gradle/SkeletonWearableApp/screenshots/dismiss_overlay.png
new file mode 100644
index 0000000..142d7e4
--- /dev/null
+++ b/prebuilts/gradle/SkeletonWearableApp/screenshots/dismiss_overlay.png
Binary files differ
diff --git a/prebuilts/gradle/SkeletonWearableApp/screenshots/grid_view_pager.png b/prebuilts/gradle/SkeletonWearableApp/screenshots/grid_view_pager.png
new file mode 100644
index 0000000..f59c13d
--- /dev/null
+++ b/prebuilts/gradle/SkeletonWearableApp/screenshots/grid_view_pager.png
Binary files differ
diff --git a/prebuilts/gradle/SkeletonWearableApp/screenshots/skeleton_wearable_app.png b/prebuilts/gradle/SkeletonWearableApp/screenshots/skeleton_wearable_app.png
new file mode 100644
index 0000000..4f17274
--- /dev/null
+++ b/prebuilts/gradle/SkeletonWearableApp/screenshots/skeleton_wearable_app.png
Binary files differ
diff --git a/prebuilts/gradle/SkeletonWearableApp/settings.gradle b/prebuilts/gradle/SkeletonWearableApp/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/SkeletonWearableApp/settings.gradle
+++ b/prebuilts/gradle/SkeletonWearableApp/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/SpeedTracker/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/SpeedTracker/Application/src/main/AndroidManifest.xml
index 3361a44..97db732 100644
--- a/prebuilts/gradle/SpeedTracker/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/SpeedTracker/Application/src/main/AndroidManifest.xml
@@ -12,7 +12,7 @@
android:glEsVersion="0x00020000" android:required="true"/>
<uses-sdk
android:minSdkVersion="18"
- android:targetSdkVersion="19" />
+ android:targetSdkVersion="20" />
<application
android:name=".PhoneApplication"
diff --git a/prebuilts/gradle/StorageClient/Application/build.gradle b/prebuilts/gradle/StorageClient/Application/build.gradle
index 78ae552..bd1120c 100644
--- a/prebuilts/gradle/StorageClient/Application/build.gradle
+++ b/prebuilts/gradle/StorageClient/Application/build.gradle
@@ -26,12 +26,12 @@
'template'] // boilerplate code that is generated by the sample template process
android {
- compileSdkVersion 19
+ compileSdkVersion 21
buildToolsVersion "21.0.0"
defaultConfig {
minSdkVersion 4
- targetSdkVersion 19
+ targetSdkVersion 21
}
sourceSets {
diff --git a/prebuilts/gradle/SynchronizedNotifications/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/AndroidManifest.xml
index c46f772..9d7df72 100644
--- a/prebuilts/gradle/SynchronizedNotifications/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/AndroidManifest.xml
@@ -18,12 +18,12 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.synchronizednotifications"
+ package="com.example.android.wearable.synchronizednotifications"
android:versionCode="1"
android:versionName="1.0">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application android:allowBackup="true"
android:label="@string/app_name"
@@ -47,7 +47,7 @@
</intent-filter>
<intent-filter>
<action
- android:name="com.example.android.wearable.synchronizednotifications.DISMISS" />
+ android:name="com.example.android.wearable.wearable.synchronizednotifications.DISMISS" />
</intent-filter>
</service>
</application>
diff --git a/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/DismissListener.java b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/DismissListener.java
new file mode 100644
index 0000000..8d5cca4
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/DismissListener.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.synchronizednotifications;
+
+import static com.google.android.gms.wearable.PutDataRequest.WEAR_URI_SCHEME;
+
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.v4.app.NotificationManagerCompat;
+import android.util.Log;
+
+import com.example.android.wearable.synchronizednotifications.common.Constants;
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.Wearable;
+import com.google.android.gms.wearable.WearableListenerService;
+
+/**
+ * A {@link com.google.android.gms.wearable.WearableListenerService} that is invoked when certain
+ * notifications are dismissed from either the phone or watch.
+ */
+public class DismissListener extends WearableListenerService
+ implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
+ ResultCallback<DataApi.DeleteDataItemsResult> {
+
+ private static final String TAG = "DismissListener";
+ private GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ for (DataEvent dataEvent : dataEvents) {
+ if (dataEvent.getType() == DataEvent.TYPE_DELETED) {
+ if (Constants.BOTH_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
+ // notification on the phone should be dismissed
+ NotificationManagerCompat.from(this).cancel(Constants.BOTH_ID);
+ }
+ }
+ }
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ if (null != intent) {
+ String action = intent.getAction();
+ if (Constants.ACTION_DISMISS.equals(action)) {
+ // We need to dismiss the wearable notification. We delete the DataItem that
+ // created the notification to inform the wearable.
+ int notificationId = intent.getIntExtra(Constants.KEY_NOTIFICATION_ID, -1);
+ if (notificationId == Constants.BOTH_ID) {
+ dismissWearableNotification(notificationId);
+ }
+ }
+ }
+ return super.onStartCommand(intent, flags, startId);
+ }
+
+ /**
+ * Removes the DataItem that was used to create a notification on the watch. By deleting the
+ * data item, a {@link com.google.android.gms.wearable.WearableListenerService} on the watch
+ * will be notified and the notification on the watch will be removed. To
+ * access the Wearable DataApi, we first need to ensure the GoogleApiClient is ready,
+ * which will then run the onConnected callback were the data removal is
+ * defined.
+ *
+ * @param id The ID of the notification that should be removed
+ */
+ private void dismissWearableNotification(final int id) {
+ mGoogleApiClient.connect();
+ }
+
+ @Override // ConnectionCallbacks
+ public void onConnected(Bundle bundle) {
+ final Uri dataItemUri =
+ new Uri.Builder().scheme(WEAR_URI_SCHEME).path(Constants.BOTH_PATH).build();
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Deleting Uri: " + dataItemUri.toString());
+ }
+ Wearable.DataApi.deleteDataItems(
+ mGoogleApiClient, dataItemUri).setResultCallback(this);
+ }
+
+ @Override // ConnectionCallbacks
+ public void onConnectionSuspended(int i) {
+ }
+
+ @Override // OnConnectionFailedListener
+ public void onConnectionFailed(ConnectionResult connectionResult) {
+ Log.e(TAG, "Failed to connect to the Google API client");
+ }
+
+ @Override // ResultCallback<DataApi.DeleteDataItemsResult>
+ public void onResult(DataApi.DeleteDataItemsResult deleteDataItemsResult) {
+ if (!deleteDataItemsResult.getStatus().isSuccess()) {
+ Log.e(TAG, "dismissWearableNotification(): failed to delete DataItem");
+ }
+ mGoogleApiClient.disconnect();
+ }
+}
diff --git a/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/MainActivity.java b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/MainActivity.java
new file mode 100644
index 0000000..9946430
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/MainActivity.java
@@ -0,0 +1,78 @@
+/*
+* Copyright 2013 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.example.android.wearable.synchronizednotifications;
+
+import android.graphics.Color;
+import android.os.Bundle;
+import android.support.v4.app.FragmentTransaction;
+import android.view.Menu;
+
+import com.example.android.common.activities.SampleActivityBase;
+import com.example.android.common.logger.Log;
+import com.example.android.common.logger.LogFragment;
+import com.example.android.common.logger.LogWrapper;
+import com.example.android.common.logger.MessageOnlyLogFilter;
+
+/**
+ * A simple launcher activity containing a summary sample description
+ * and a few action bar buttons.
+ */
+public class MainActivity extends SampleActivityBase {
+
+ public static final String TAG = "MainActivity";
+
+ public static final String FRAGTAG = "SynchronizedNotificationsFragment";
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_main);
+
+ FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
+ SynchronizedNotificationsFragment fragment = new SynchronizedNotificationsFragment();
+ transaction.add(fragment, FRAGTAG);
+ transaction.commit();
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.main, menu);
+ return true;
+ }
+
+ /** Create a chain of targets that will receive log data */
+ @Override
+ public void initializeLogging() {
+ // Wraps Android's native log framework.
+ LogWrapper logWrapper = new LogWrapper();
+ // Using Log, front-end to the logging chain, emulates android.util.log method signatures.
+ Log.setLogNode(logWrapper);
+
+ // Filter strips out everything except the message text.
+ MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
+ logWrapper.setNext(msgFilter);
+
+ // On screen logging via a fragment with a TextView.
+ LogFragment logFragment = (LogFragment) getSupportFragmentManager()
+ .findFragmentById(R.id.log_fragment);
+ msgFilter.setNext(logFragment.getLogView());
+ logFragment.getLogView().setTextAppearance(this, R.style.Log);
+ logFragment.getLogView().setBackgroundColor(Color.WHITE);
+
+ Log.i(TAG, "Ready");
+ }
+}
\ No newline at end of file
diff --git a/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/SynchronizedNotificationsFragment.java b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/SynchronizedNotificationsFragment.java
new file mode 100644
index 0000000..240af9b
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/Application/src/main/java/com/example/android/wearable/synchronizednotifications/SynchronizedNotificationsFragment.java
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.synchronizednotifications;
+
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.support.v4.app.Fragment;
+import android.app.Activity;
+import android.net.Uri;
+import android.os.Bundle;
+import android.support.v4.app.NotificationCompat;
+import android.support.v4.app.NotificationManagerCompat;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Toast;
+
+import com.example.android.wearable.synchronizednotifications.common.Constants;
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.PutDataRequest;
+import com.google.android.gms.wearable.Wearable;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+
+
+/**
+ * A simple fragment that presents three buttons that would trigger three different combinations of
+ * notifications on the handset and the watch:
+ * <ul>
+ * <li>The first button builds a simple local-only notification on the handset.</li>
+ * <li>The second one creates a wearable-only notification by putting a data item in the shared data
+ * store and having a {@link com.google.android.gms.wearable.WearableListenerService} listen for
+ * that on the wearable</li>
+ * <li>The third one creates a local notification and a wearable notification by combining the above
+ * two. It, however, demonstrates how one can set things up so that the dismissal of one
+ * notification results in the dismissal of the other one.</li>
+ * </ul>
+ */
+public class SynchronizedNotificationsFragment extends Fragment
+ implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
+
+ private static final String TAG = "SynchronizedNotificationsFragment";
+ private GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ setHasOptionsMenu(true);
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ switch (item.getItemId()) {
+ case R.id.btn_phone_only:
+ buildLocalOnlyNotification(getString(R.string.phone_only), now(),
+ Constants.PHONE_ONLY_ID, false);
+ return true;
+ case R.id.btn_wear_only:
+ buildWearableOnlyNotification(getString(R.string.wear_only), now(),
+ Constants.WATCH_ONLY_PATH);
+ return true;
+ case R.id.btn_different:
+ buildMirroredNotifications(getString(R.string.phone_both), getString(R.string.watch_both), now());
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Builds a local-only notification for the handset. This is achieved by using
+ * <code>setLocalOnly(true)</code>. If <code>withDismissal</code> is set to <code>true</code>, a
+ * {@link android.app.PendingIntent} will be added to handle the dismissal of notification to
+ * be able to remove the mirrored notification on the wearable.
+ */
+ private void buildLocalOnlyNotification(String title, String content, int notificationId,
+ boolean withDismissal) {
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getActivity());
+ builder.setContentTitle(title)
+ .setContentText(content)
+ .setLocalOnly(true)
+ .setSmallIcon(R.drawable.ic_launcher);
+
+ if (withDismissal) {
+ Intent dismissIntent = new Intent(Constants.ACTION_DISMISS);
+ dismissIntent.putExtra(Constants.KEY_NOTIFICATION_ID, Constants.BOTH_ID);
+ PendingIntent pendingIntent = PendingIntent
+ .getService(this.getActivity(), 0, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+ builder.setDeleteIntent(pendingIntent);
+ }
+ NotificationManagerCompat.from(this.getActivity()).notify(notificationId, builder.build());
+ }
+
+ /**
+ * Builds a DataItem that on the wearable will be interpreted as a request to show a
+ * notification. The result will be a notification that only shows up on the wearable.
+ */
+ private void buildWearableOnlyNotification(String title, String content, String path) {
+ if (mGoogleApiClient.isConnected()) {
+ PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path);
+ putDataMapRequest.getDataMap().putString(Constants.KEY_CONTENT, content);
+ putDataMapRequest.getDataMap().putString(Constants.KEY_TITLE, title);
+ PutDataRequest request = putDataMapRequest.asPutDataRequest();
+ Wearable.DataApi.putDataItem(mGoogleApiClient, request)
+ .setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
+ @Override
+ public void onResult(DataApi.DataItemResult dataItemResult) {
+ if (!dataItemResult.getStatus().isSuccess()) {
+ Log.e(TAG, "buildWatchOnlyNotification(): Failed to set the data, "
+ + "status: " + dataItemResult.getStatus().getStatusCode());
+ }
+ }
+ });
+ } else {
+ Log.e(TAG, "buildWearableOnlyNotification(): no Google API Client connection");
+ }
+ }
+
+ /**
+ * Builds a local notification and sets a DataItem that will be interpreted by the wearable as
+ * a request to build a notification on the wearable as as well. The two notifications show
+ * different messages.
+ * Dismissing either of the notifications will result in dismissal of the other; this is
+ * achieved by creating a {@link android.app.PendingIntent} that results in removal of
+ * the DataItem that created the watch notification. The deletion of the DataItem is observed on
+ * both sides, using WearableListenerService callbacks, and is interpreted on each side as a
+ * request to dismiss the corresponding notification.
+ */
+ private void buildMirroredNotifications(String phoneTitle, String watchTitle, String content) {
+ if (mGoogleApiClient.isConnected()) {
+ // Wearable notification
+ buildWearableOnlyNotification(watchTitle, content, Constants.BOTH_PATH);
+
+ // Local notification, with a pending intent for dismissal
+ buildLocalOnlyNotification(phoneTitle, content, Constants.BOTH_ID, true);
+ }
+ }
+
+ @Override
+ public void onStart() {
+ super.onStart();
+ mGoogleApiClient.connect();
+ }
+
+ @Override
+ public void onStop() {
+ mGoogleApiClient.disconnect();
+ super.onStop();
+ }
+
+ @Override
+ public void onConnected(Bundle bundle) {
+ }
+
+ @Override
+ public void onConnectionSuspended(int i) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult connectionResult) {
+ Log.e(TAG, "Failed to connect to Google API Client");
+ }
+
+ /**
+ * Returns a string built from the current time
+ */
+ private String now() {
+ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
+ return sdf.format(new Date());
+ }
+
+}
diff --git a/prebuilts/gradle/SynchronizedNotifications/Shared/src/main/AndroidManifest.xml b/prebuilts/gradle/SynchronizedNotifications/Shared/src/main/AndroidManifest.xml
index 7235ace..5362fc7 100644
--- a/prebuilts/gradle/SynchronizedNotifications/Shared/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/SynchronizedNotifications/Shared/src/main/AndroidManifest.xml
@@ -16,7 +16,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.synchronizednotifications.common">
+ package="com.example.android.wearable.synchronizednotifications.common">
<application android:allowBackup="true"
android:label="@string/app_name">
diff --git a/prebuilts/gradle/SynchronizedNotifications/Shared/src/main/java/com/example/android/wearable/synchronizednotifications/common/Constants.java b/prebuilts/gradle/SynchronizedNotifications/Shared/src/main/java/com/example/android/wearable/synchronizednotifications/common/Constants.java
new file mode 100644
index 0000000..2e1d46c
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/Shared/src/main/java/com/example/android/wearable/synchronizednotifications/common/Constants.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2013 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.example.android.wearable.synchronizednotifications.common;
+
+/**
+ * Constants that are used in both the Application and the Wearable modules.
+ */
+public final class Constants {
+
+ private Constants() {};
+
+ public static final int WATCH_ONLY_ID = 2;
+ public static final int PHONE_ONLY_ID = 3;
+ public static final int BOTH_ID = 4;
+
+ public static final String BOTH_PATH = "/both";
+ public static final String WATCH_ONLY_PATH = "/watch-only";
+ public static final String KEY_NOTIFICATION_ID = "notification-id";
+ public static final String KEY_TITLE = "title";
+ public static final String KEY_CONTENT = "content";
+
+ public static final String ACTION_DISMISS
+ = "com.example.android.wearable.synchronizednotifications.DISMISS";
+}
diff --git a/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/AndroidManifest.xml
index 97702ce..b8d5e85 100644
--- a/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/AndroidManifest.xml
@@ -17,7 +17,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.synchronizednotifications">
+ package="com.example.android.wearable.synchronizednotifications">
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -46,7 +46,7 @@
</intent-filter>
<intent-filter>
<action
- android:name="com.example.android.synchronizednotifications.DISMISS" />
+ android:name="com.example.android.wearable.synchronizednotifications.DISMISS" />
</intent-filter>
</service>
diff --git a/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/java/com/example/android/wearable/synchronizednotifications/NotificationUpdateService.java b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/java/com/example/android/wearable/synchronizednotifications/NotificationUpdateService.java
new file mode 100644
index 0000000..8b46bf3
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/java/com/example/android/wearable/synchronizednotifications/NotificationUpdateService.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.synchronizednotifications;
+
+import static com.google.android.gms.wearable.PutDataRequest.WEAR_URI_SCHEME;
+
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.example.android.wearable.synchronizednotifications.common.Constants;
+import com.google.android.gms.common.ConnectionResult;
+import com.google.android.gms.common.api.GoogleApiClient;
+import com.google.android.gms.common.api.ResultCallback;
+import com.google.android.gms.wearable.DataApi;
+import com.google.android.gms.wearable.DataEvent;
+import com.google.android.gms.wearable.DataEventBuffer;
+import com.google.android.gms.wearable.DataMap;
+import com.google.android.gms.wearable.DataMapItem;
+import com.google.android.gms.wearable.PutDataMapRequest;
+import com.google.android.gms.wearable.Wearable;
+import com.google.android.gms.wearable.WearableListenerService;
+
+/**
+ * A {@link com.google.android.gms.wearable.WearableListenerService} that will be invoked when a
+ * DataItem is added or deleted. The creation of a new DataItem will be interpreted as a request to
+ * create a new notification and the removal of that DataItem is interpreted as a request to
+ * dismiss that notification.
+ */
+public class NotificationUpdateService extends WearableListenerService
+ implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
+ ResultCallback<DataApi.DeleteDataItemsResult> {
+
+ private static final String TAG = "NotificationUpdate";
+ private GoogleApiClient mGoogleApiClient;
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ mGoogleApiClient = new GoogleApiClient.Builder(this)
+ .addApi(Wearable.API)
+ .addConnectionCallbacks(this)
+ .addOnConnectionFailedListener(this)
+ .build();
+ }
+
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ if (null != intent) {
+ String action = intent.getAction();
+ if (Constants.ACTION_DISMISS.equals(action)) {
+ // We need to dismiss the wearable notification. We delete the data item that
+ // created the notification and that is how we inform the phone
+ int notificationId = intent.getIntExtra(Constants.KEY_NOTIFICATION_ID, -1);
+ if (notificationId == Constants.BOTH_ID) {
+ dismissPhoneNotification(notificationId);
+ }
+ }
+ }
+ return super.onStartCommand(intent, flags, startId);
+ }
+
+ /**
+ * Dismisses the phone notification, via a {@link android.app.PendingIntent} that is triggered
+ * when the user dismisses the local notification. Deleting the corresponding data item notifies
+ * the {@link com.google.android.gms.wearable.WearableListenerService} on the phone that the
+ * matching notification on the phone side should be removed.
+ */
+ private void dismissPhoneNotification(int id) {
+ mGoogleApiClient.connect();
+ }
+
+ @Override
+ public void onDataChanged(DataEventBuffer dataEvents) {
+ for (DataEvent dataEvent : dataEvents) {
+ if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
+ DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();
+ String content = dataMap.getString(Constants.KEY_CONTENT);
+ String title = dataMap.getString(Constants.KEY_TITLE);
+ if (Constants.WATCH_ONLY_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
+ buildWearableOnlyNotification(title, content, false);
+ } else if (Constants.BOTH_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
+ buildWearableOnlyNotification(title, content, true);
+ }
+ } else if (dataEvent.getType() == DataEvent.TYPE_DELETED) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "DataItem deleted: " + dataEvent.getDataItem().getUri().getPath());
+ }
+ if (Constants.BOTH_PATH.equals(dataEvent.getDataItem().getUri().getPath())) {
+ // Dismiss the corresponding notification
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .cancel(Constants.WATCH_ONLY_ID);
+ }
+ }
+ }
+ }
+
+ /**
+ * Builds a simple notification on the wearable.
+ */
+ private void buildWearableOnlyNotification(String title, String content,
+ boolean withDismissal) {
+ Notification.Builder builder = new Notification.Builder(this)
+ .setSmallIcon(R.drawable.ic_launcher)
+ .setContentTitle(title)
+ .setContentText(content);
+
+ if (withDismissal) {
+ Intent dismissIntent = new Intent(Constants.ACTION_DISMISS);
+ dismissIntent.putExtra(Constants.KEY_NOTIFICATION_ID, Constants.BOTH_ID);
+ PendingIntent pendingIntent = PendingIntent
+ .getService(this, 0, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+ builder.setDeleteIntent(pendingIntent);
+ }
+
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
+ .notify(Constants.WATCH_ONLY_ID, builder.build());
+ }
+
+ @Override
+ public void onConnected(Bundle bundle) {
+ final Uri dataItemUri =
+ new Uri.Builder().scheme(WEAR_URI_SCHEME).path(Constants.BOTH_PATH).build();
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Deleting Uri: " + dataItemUri.toString());
+ }
+ Wearable.DataApi.deleteDataItems(
+ mGoogleApiClient, dataItemUri).setResultCallback(this);
+ }
+
+ @Override
+ public void onConnectionSuspended(int i) {
+ }
+
+ @Override
+ public void onConnectionFailed(ConnectionResult connectionResult) {
+ }
+
+ @Override
+ public void onResult(DataApi.DeleteDataItemsResult deleteDataItemsResult) {
+ if (!deleteDataItemsResult.getStatus().isSuccess()) {
+ Log.e(TAG, "dismissWearableNotification(): failed to delete DataItem");
+ }
+ mGoogleApiClient.disconnect();
+ }
+}
diff --git a/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/java/com/example/android/wearable/synchronizednotifications/WearableActivity.java b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/java/com/example/android/wearable/synchronizednotifications/WearableActivity.java
new file mode 100644
index 0000000..6ef2f1b
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/java/com/example/android/wearable/synchronizednotifications/WearableActivity.java
@@ -0,0 +1,28 @@
+/*
+ * Copyright (C) 2013 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.example.android.wearable.synchronizednotifications;
+
+import android.app.Activity;
+import android.os.Bundle;
+
+public class WearableActivity extends Activity {
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_wearable);
+ }
+}
diff --git a/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/res/values/strings.xml b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/res/values/strings.xml
index 4240ff5..aa51a71 100644
--- a/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/res/values/strings.xml
+++ b/prebuilts/gradle/SynchronizedNotifications/Wearable/src/main/res/values/strings.xml
@@ -15,6 +15,6 @@
-->
<resources>
- <string name="app_name">Sample Wearable app</string>
+ <string name="app_name">Synchronized Notifications</string>
</resources>
diff --git a/prebuilts/gradle/SynchronizedNotifications/screenshots/different_notifications_phone.png b/prebuilts/gradle/SynchronizedNotifications/screenshots/different_notifications_phone.png
new file mode 100644
index 0000000..cab31e0
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/screenshots/different_notifications_phone.png
Binary files differ
diff --git a/prebuilts/gradle/SynchronizedNotifications/screenshots/different_notifications_wearable.png b/prebuilts/gradle/SynchronizedNotifications/screenshots/different_notifications_wearable.png
new file mode 100644
index 0000000..97da715
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/screenshots/different_notifications_wearable.png
Binary files differ
diff --git a/prebuilts/gradle/SynchronizedNotifications/screenshots/notification_options.png b/prebuilts/gradle/SynchronizedNotifications/screenshots/notification_options.png
new file mode 100644
index 0000000..8cd0095
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/screenshots/notification_options.png
Binary files differ
diff --git a/prebuilts/gradle/SynchronizedNotifications/screenshots/watch_only_notification.png b/prebuilts/gradle/SynchronizedNotifications/screenshots/watch_only_notification.png
new file mode 100644
index 0000000..34e950f
--- /dev/null
+++ b/prebuilts/gradle/SynchronizedNotifications/screenshots/watch_only_notification.png
Binary files differ
diff --git a/prebuilts/gradle/Timer/Application/build.gradle b/prebuilts/gradle/Timer/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/Timer/Application/build.gradle
+++ b/prebuilts/gradle/Timer/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/Timer/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/Timer/Application/src/main/AndroidManifest.xml
index b8ebd74..6b34b12 100644
--- a/prebuilts/gradle/Timer/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Timer/Application/src/main/AndroidManifest.xml
@@ -16,10 +16,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.timer">
+ package="com.example.android.wearable.timer">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application android:allowBackup="true"
android:label="@string/app_name">
diff --git a/prebuilts/gradle/Timer/Wearable/build.gradle b/prebuilts/gradle/Timer/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/Timer/Wearable/build.gradle
+++ b/prebuilts/gradle/Timer/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/Timer/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/Timer/Wearable/src/main/AndroidManifest.xml
index 3dabadc..9e27947 100644
--- a/prebuilts/gradle/Timer/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/Timer/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.timer" >
+ package="com.example.android.wearable.timer" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
diff --git a/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/SetTimerActivity.java b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/SetTimerActivity.java
new file mode 100644
index 0000000..f660f9f
--- /dev/null
+++ b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/SetTimerActivity.java
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.timer;
+
+import android.app.Activity;
+import android.app.AlarmManager;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Resources;
+import android.os.Bundle;
+import android.provider.AlarmClock;
+import android.support.wearable.view.WearableListView;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import com.example.android.wearable.timer.util.Constants;
+import com.example.android.wearable.timer.util.TimerFormat;
+
+/** This class sets a timer. */
+public class SetTimerActivity extends Activity implements WearableListView.ClickListener {
+
+ public static final int NUMBER_OF_TIMES = 10;
+ public static final String TAG = "SetTimerActivity";
+
+ private ListViewItem[] mTimeOptions = new ListViewItem[NUMBER_OF_TIMES];
+ private WearableListView mWearableListView;
+
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ int paramLength = getIntent().getIntExtra(AlarmClock.EXTRA_LENGTH, 0);
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "SetTimerActivity:onCreate=" + paramLength);
+ }
+ if (paramLength > 0 && paramLength <= 86400) {
+ long durationMillis = paramLength * 1000;
+ setupTimer(durationMillis);
+ finish();
+ return;
+ }
+
+ Resources res = getResources();
+ for (int i = 0; i < NUMBER_OF_TIMES; i++) {
+ mTimeOptions[i] = new ListViewItem(
+ res.getQuantityString(R.plurals.timer_minutes, i + 1, i + 1),
+ (i + 1) * 60 * 1000);
+ }
+
+ setContentView(R.layout.timer_set_timer);
+
+ // Initialize a simple list of countdown time options.
+ mWearableListView = (WearableListView) findViewById(R.id.times_list_view);
+ mWearableListView.setAdapter(new TimerWearableListViewAdapter(this));
+ mWearableListView.setClickListener(this);
+ }
+
+ /**
+ * Sets up an alarm (and an associated notification) to go off after <code>duration</code>
+ * milliseconds.
+ */
+ private void setupTimer(long duration) {
+ NotificationManager notifyMgr =
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE));
+
+ // Delete dataItem and cancel a potential old countdown.
+ cancelCountdown(notifyMgr);
+
+ // Build notification and set it.
+ notifyMgr.notify(Constants.NOTIFICATION_TIMER_COUNTDOWN, buildNotification(duration));
+
+ // Register with the alarm manager to display a notification when the timer is done.
+ registerWithAlarmManager(duration);
+
+ finish();
+ }
+
+ @Override
+ public void onClick(WearableListView.ViewHolder holder) {
+ long duration = mTimeOptions[holder.getPosition()].duration;
+ setupTimer(duration);
+ }
+
+ @Override
+ public void onTopEmptyRegionClick() {
+ }
+
+ private void registerWithAlarmManager(long duration) {
+ // Get the alarm manager.
+ AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
+
+ // Create intent that gets fired when timer expires.
+ Intent intent = new Intent(Constants.ACTION_SHOW_ALARM, null, this,
+ TimerNotificationService.class);
+ PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
+ PendingIntent.FLAG_UPDATE_CURRENT);
+
+ // Calculate the time when it expires.
+ long wakeupTime = System.currentTimeMillis() + duration;
+
+ // Schedule an alarm.
+ alarm.setExact(AlarmManager.RTC_WAKEUP, wakeupTime, pendingIntent);
+ }
+
+ /**
+ * Build a notification including different actions and other various setup and return it.
+ *
+ * @param duration the duration of the timer.
+ * @return the notification to display.
+ */
+
+ private Notification buildNotification(long duration) {
+ // Intent to restart a timer.
+ Intent restartIntent = new Intent(Constants.ACTION_RESTART_ALARM, null, this,
+ TimerNotificationService.class);
+ PendingIntent pendingIntentRestart = PendingIntent
+ .getService(this, 0, restartIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ // Intent to delete a timer.
+ Intent deleteIntent = new Intent(Constants.ACTION_DELETE_ALARM, null, this,
+ TimerNotificationService.class);
+ PendingIntent pendingIntentDelete = PendingIntent
+ .getService(this, 0, deleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ // Create countdown notification using a chronometer style.
+ return new Notification.Builder(this)
+ .setSmallIcon(R.drawable.ic_cc_alarm)
+ .setContentTitle(getString(R.string.timer_time_left))
+ .setContentText(TimerFormat.getTimeString(duration))
+ .setUsesChronometer(true)
+ .setWhen(System.currentTimeMillis() + duration)
+ .addAction(R.drawable.ic_cc_alarm, getString(R.string.timer_restart),
+ pendingIntentRestart)
+ .addAction(R.drawable.ic_cc_alarm, getString(R.string.timer_delete),
+ pendingIntentDelete)
+ .setDeleteIntent(pendingIntentDelete)
+ .setLocalOnly(true)
+ .build();
+ }
+
+ /**
+ * Cancels an old countdown and deletes the dataItem.
+ *
+ * @param notifyMgr the notification manager.
+ */
+ private void cancelCountdown(NotificationManager notifyMgr) {
+ notifyMgr.cancel(Constants.NOTIFICATION_TIMER_EXPIRED);
+ }
+
+ /** Model class for the listview. */
+ private static class ListViewItem {
+
+ // Duration in milliseconds.
+ long duration;
+ // Label to display.
+ private String label;
+
+ public ListViewItem(String label, long duration) {
+ this.label = label;
+ this.duration = duration;
+ }
+
+ @Override
+ public String toString() {
+ return label;
+ }
+ }
+
+ private final class TimerWearableListViewAdapter extends WearableListView.Adapter {
+ private final Context mContext;
+ private final LayoutInflater mInflater;
+
+ private TimerWearableListViewAdapter(Context context) {
+ mContext = context;
+ mInflater = LayoutInflater.from(context);
+ }
+
+ @Override
+ public WearableListView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
+ return new WearableListView.ViewHolder(
+ mInflater.inflate(R.layout.timer_list_item, null));
+ }
+
+ @Override
+ public void onBindViewHolder(WearableListView.ViewHolder holder, int position) {
+ TextView view = (TextView) holder.itemView.findViewById(R.id.time_text);
+ view.setText(mTimeOptions[position].label);
+ holder.itemView.setTag(position);
+ }
+
+ @Override
+ public int getItemCount() {
+ return NUMBER_OF_TIMES;
+ }
+ }
+
+}
diff --git a/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/TimerNotificationService.java b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/TimerNotificationService.java
new file mode 100644
index 0000000..5822fe4
--- /dev/null
+++ b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/TimerNotificationService.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.timer;
+
+import android.app.AlarmManager;
+import android.app.IntentService;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import com.example.android.wearable.timer.util.Constants;
+
+/**
+ * Service class that manages notifications of the timer.
+ */
+public class TimerNotificationService extends IntentService {
+
+ public static final String TAG = "TimerNotificationSvc";
+
+ public TimerNotificationService() {
+ super(TAG);
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ }
+
+ @Override
+ protected void onHandleIntent(Intent intent) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onHandleIntent called with intent: " + intent);
+ }
+ String action = intent.getAction();
+ if (Constants.ACTION_SHOW_ALARM.equals(action)) {
+ showTimerDoneNotification();
+ } else if (Constants.ACTION_DELETE_ALARM.equals(action)) {
+ deleteTimer();
+ } else if (Constants.ACTION_RESTART_ALARM.equals(action)) {
+ restartAlarm();
+ } else {
+ throw new IllegalStateException("Undefined constant used: " + action);
+ }
+ }
+
+ private void restartAlarm() {
+ Intent dialogIntent = new Intent(this, SetTimerActivity.class);
+ dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ startActivity(dialogIntent);
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Timer restarted.");
+ }
+ }
+
+ private void deleteTimer() {
+ cancelCountdownNotification();
+
+ AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
+ Intent intent = new Intent(Constants.ACTION_SHOW_ALARM, null, this,
+ TimerNotificationService.class);
+ PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
+ PendingIntent.FLAG_UPDATE_CURRENT);
+ alarm.cancel(pendingIntent);
+
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Timer deleted.");
+ }
+ }
+
+ private void cancelCountdownNotification() {
+ NotificationManager notifyMgr =
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE));
+ notifyMgr.cancel(Constants.NOTIFICATION_TIMER_COUNTDOWN);
+ }
+
+ private void showTimerDoneNotification() {
+ // Cancel the countdown notification to show the "timer done" notification.
+ cancelCountdownNotification();
+
+ // Create an intent to restart a timer.
+ Intent restartIntent = new Intent(Constants.ACTION_RESTART_ALARM, null, this,
+ TimerNotificationService.class);
+ PendingIntent pendingIntentRestart = PendingIntent
+ .getService(this, 0, restartIntent, PendingIntent.FLAG_UPDATE_CURRENT);
+
+ // Create notification that timer has expired.
+ NotificationManager notifyMgr =
+ ((NotificationManager) getSystemService(NOTIFICATION_SERVICE));
+ Notification notif = new Notification.Builder(this)
+ .setSmallIcon(R.drawable.ic_cc_alarm)
+ .setContentTitle(getString(R.string.timer_done))
+ .setContentText(getString(R.string.timer_done))
+ .setUsesChronometer(true)
+ .setWhen(System.currentTimeMillis())
+ .addAction(R.drawable.ic_cc_alarm, getString(R.string.timer_restart),
+ pendingIntentRestart)
+ .setLocalOnly(true)
+ .build();
+ notifyMgr.notify(Constants.NOTIFICATION_TIMER_EXPIRED, notif);
+ }
+
+}
diff --git a/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/WearableListItemLayout.java b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/WearableListItemLayout.java
new file mode 100644
index 0000000..0bbc587
--- /dev/null
+++ b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/WearableListItemLayout.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.timer;
+
+import android.content.Context;
+import android.graphics.drawable.GradientDrawable;
+import android.support.wearable.view.WearableListView;
+import android.util.AttributeSet;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+
+public class WearableListItemLayout extends LinearLayout implements WearableListView.Item {
+ private final float mFadedTextAlpha;
+ private final int mFadedCircleColor;
+ private final int mChosenCircleColor;
+ private ImageView mCircle;
+ private float mScale;
+ private TextView mName;
+
+ public WearableListItemLayout(Context context) {
+ this(context, null);
+ }
+
+ public WearableListItemLayout(Context context, AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public WearableListItemLayout(Context context, AttributeSet attrs, int defStyle) {
+ super(context, attrs, defStyle);
+ mFadedTextAlpha = getResources().getInteger(R.integer.action_text_faded_alpha) / 100f;
+ mFadedCircleColor = getResources().getColor(R.color.wl_gray);
+ mChosenCircleColor = getResources().getColor(R.color.wl_blue);
+ }
+
+ @Override
+ protected void onFinishInflate() {
+ super.onFinishInflate();
+ mCircle = (ImageView) findViewById(R.id.circle);
+ mName = (TextView) findViewById(R.id.time_text);
+ }
+
+ @Override
+ public float getProximityMinValue() {
+ return 1f;
+ }
+
+ @Override
+ public float getProximityMaxValue() {
+ return 1.6f;
+ }
+
+ @Override
+ public float getCurrentProximityValue() {
+ return mScale;
+ }
+
+ @Override
+ public void setScalingAnimatorValue(float scale) {
+ mScale = scale;
+ mCircle.setScaleX(scale);
+ mCircle.setScaleY(scale);
+ }
+
+ @Override
+ public void onScaleUpStart() {
+ mName.setAlpha(1f);
+ ((GradientDrawable) mCircle.getDrawable()).setColor(mChosenCircleColor);
+ }
+
+ @Override
+ public void onScaleDownStart() {
+ ((GradientDrawable) mCircle.getDrawable()).setColor(mFadedCircleColor);
+ mName.setAlpha(mFadedTextAlpha);
+ }
+}
diff --git a/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/Constants.java b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/Constants.java
new file mode 100644
index 0000000..85885e4
--- /dev/null
+++ b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/Constants.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.timer.util;
+
+import android.net.Uri;
+
+/** Used to hold constants. */
+public final class Constants {
+
+ public static final String START_TIME = "timer_start_time";
+ public static final String ORIGINAL_TIME = "timer_original_time";
+ public static final String DATA_ITEM_PATH = "/timer";
+ public static final Uri URI_PATTERN_DATA_ITEMS =
+ Uri.fromParts("wear", DATA_ITEM_PATH, null);
+
+ public static final int NOTIFICATION_TIMER_COUNTDOWN = 1;
+ public static final int NOTIFICATION_TIMER_EXPIRED = 2;
+
+ public static final String ACTION_SHOW_ALARM
+ = "com.android.example.clockwork.timer.ACTION_SHOW";
+ public static final String ACTION_DELETE_ALARM
+ = "com.android.example.clockwork.timer.ACTION_DELETE";
+ public static final String ACTION_RESTART_ALARM
+ = "com.android.example.clockwork.timer.ACTION_RESTART";
+
+ private Constants() {
+ }
+
+}
diff --git a/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/TimerFormat.java b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/TimerFormat.java
new file mode 100644
index 0000000..b40351b
--- /dev/null
+++ b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/TimerFormat.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.timer.util;
+
+/** Helper class to format the timer. Based on com.android.deskclock.timer.CountingTimerView. */
+public final class TimerFormat {
+
+ private static final String TWO_DIGITS = "%02d";
+
+ private static final String ONE_DIGIT = "%01d";
+
+ private static final String NEG_TWO_DIGITS = "-%02d";
+
+ private static final String NEG_ONE_DIGIT = "-%01d";
+
+ private static String mHours;
+
+ private static String mMinutes;
+
+ private static String mSeconds;
+
+ private TimerFormat() {
+
+ }
+
+ /**
+ * Update the time to display. Separates that time into the hours, minutes, seconds.
+ * Copied and shortened from com.android.deskclock.timer.CountingTimerView.
+ *
+ * @param time new time to display - in milliseconds
+ */
+ private static void setTime(long time) {
+ boolean neg = false;
+ boolean showNeg = false;
+ String format;
+ if (time < 0) {
+ time = -time;
+ neg = showNeg = true;
+ }
+ long seconds = time / 1000;
+ long hundreds = (time - seconds * 1000) / 10;
+ long minutes = seconds / 60;
+ seconds = seconds - minutes * 60;
+ long hours = minutes / 60;
+ minutes = minutes - hours * 60;
+ if (hours > 999) {
+ hours = 0;
+ }
+ // The time can be between 0 and -1 seconds, but the "truncated" equivalent time of hours
+ // and minutes and seconds could be zero, so since we do not show fractions of seconds
+ // when counting down, do not show the minus sign.
+ if (hours == 0 && minutes == 0 && seconds == 0) {
+ showNeg = false;
+ }
+
+ // Normalize and check if it is 'time' to invalidate
+ if (!neg && hundreds != 0) {
+ seconds++;
+ if (seconds == 60) {
+ seconds = 0;
+ minutes++;
+ if (minutes == 60) {
+ minutes = 0;
+ hours++;
+ }
+ }
+ }
+
+ // Hours may be empty
+ if (hours >= 10) {
+ format = showNeg ? NEG_TWO_DIGITS : TWO_DIGITS;
+ mHours = String.format(format, hours);
+ } else if (hours > 0) {
+ format = showNeg ? NEG_ONE_DIGIT : ONE_DIGIT;
+ mHours = String.format(format, hours);
+ } else {
+ mHours = null;
+ }
+
+ // Minutes are never empty and when hours are non-empty, must be two digits
+ if (minutes >= 10 || hours > 0) {
+ format = (showNeg && hours == 0) ? NEG_TWO_DIGITS : TWO_DIGITS;
+ mMinutes = String.format(format, minutes);
+ } else {
+ format = (showNeg && hours == 0) ? NEG_ONE_DIGIT : ONE_DIGIT;
+ mMinutes = String.format(format, minutes);
+ }
+
+ // Seconds are always two digits
+ mSeconds = String.format(TWO_DIGITS, seconds);
+ }
+
+ /**
+ * Based on com.android.deskclock.timer.CountingTimerView.
+ *
+ * @param time the time to format.
+ * @return nicely formatted time.
+ */
+ public static String getTimeString(long time) {
+ setTime(time);
+ if (mHours == null) {
+ return String.format("%s:%s", mMinutes, mSeconds);
+ }
+ return String.format("%s:%s:%s", mHours, mMinutes, mSeconds);
+
+ }
+}
diff --git a/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/TimerObj.java b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/TimerObj.java
new file mode 100644
index 0000000..52f7244
--- /dev/null
+++ b/prebuilts/gradle/Timer/Wearable/src/main/java/com/example/android/wearable/timer/util/TimerObj.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2014 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.example.android.wearable.timer.util;
+
+import android.os.SystemClock;
+
+/** This class represents a timer. */
+public class TimerObj {
+
+ // Start time in milliseconds.
+ public long startTime;
+
+ // Length of the timer in milliseconds.
+ public long originalLength;
+
+ /**
+ * Construct a timer with a specific start time and length.
+ *
+ * @param startTime the start time of the timer.
+ * @param timerLength the length of the timer.
+ */
+ public TimerObj(long startTime, long timerLength) {
+ this.startTime = startTime;
+ this.originalLength = timerLength;
+ }
+
+ /**
+ * Calculate the time left of this timer.
+ * @return the time left for this timer.
+ */
+ public long timeLeft() {
+ long millis = SystemClock.elapsedRealtime();
+ return originalLength - (millis - startTime);
+ }
+}
diff --git a/prebuilts/gradle/Timer/screenshots/timer.png b/prebuilts/gradle/Timer/screenshots/timer.png
new file mode 100644
index 0000000..6ef8f86
--- /dev/null
+++ b/prebuilts/gradle/Timer/screenshots/timer.png
Binary files differ
diff --git a/prebuilts/gradle/Timer/screenshots/timer_countdown.png b/prebuilts/gradle/Timer/screenshots/timer_countdown.png
new file mode 100644
index 0000000..505733d
--- /dev/null
+++ b/prebuilts/gradle/Timer/screenshots/timer_countdown.png
Binary files differ
diff --git a/prebuilts/gradle/Timer/settings.gradle b/prebuilts/gradle/Timer/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/Timer/settings.gradle
+++ b/prebuilts/gradle/Timer/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'
diff --git a/prebuilts/gradle/WatchViewStub/Application/build.gradle b/prebuilts/gradle/WatchViewStub/Application/build.gradle
index 41fc623..0c6e001 100644
--- a/prebuilts/gradle/WatchViewStub/Application/build.gradle
+++ b/prebuilts/gradle/WatchViewStub/Application/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
- compile project(':Shared')
wearApp project(':Wearable')
}
diff --git a/prebuilts/gradle/WatchViewStub/Application/src/main/AndroidManifest.xml b/prebuilts/gradle/WatchViewStub/Application/src/main/AndroidManifest.xml
index aa0d790..d33b81f 100644
--- a/prebuilts/gradle/WatchViewStub/Application/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/WatchViewStub/Application/src/main/AndroidManifest.xml
@@ -16,10 +16,10 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.watchviewstub">
+ package="com.example.android.google.wearable.watchviewstub">
- <uses-sdk android:minSdkVersion="19"
- android:targetSdkVersion="19" />
+ <uses-sdk android:minSdkVersion="18"
+ android:targetSdkVersion="20" />
<application android:allowBackup="true"
android:label="@string/app_name">
diff --git a/prebuilts/gradle/WatchViewStub/Wearable/build.gradle b/prebuilts/gradle/WatchViewStub/Wearable/build.gradle
index b8151b1..864b2fd 100644
--- a/prebuilts/gradle/WatchViewStub/Wearable/build.gradle
+++ b/prebuilts/gradle/WatchViewStub/Wearable/build.gradle
@@ -16,7 +16,6 @@
compile 'com.google.android.gms:play-services-wearable:5.0.+'
compile 'com.android.support:support-v13:20.0.+'
compile 'com.google.android.support:wearable:1.0.+'
- compile project(':Shared')
}
// The sample build uses multiple directories to
diff --git a/prebuilts/gradle/WatchViewStub/Wearable/src/main/AndroidManifest.xml b/prebuilts/gradle/WatchViewStub/Wearable/src/main/AndroidManifest.xml
index 5b33044..baa3f78 100644
--- a/prebuilts/gradle/WatchViewStub/Wearable/src/main/AndroidManifest.xml
+++ b/prebuilts/gradle/WatchViewStub/Wearable/src/main/AndroidManifest.xml
@@ -15,7 +15,7 @@
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.android.watchviewstub" >
+ package="com.example.android.google.wearable.watchviewstub" >
<uses-sdk android:minSdkVersion="20"
android:targetSdkVersion="20" />
@@ -28,7 +28,7 @@
android:label="@string/app_name"
android:theme="@android:style/Theme.DeviceDefault">
<activity
- android:name="com.example.android.watchviewstub.MainActivity"
+ android:name="com.example.android.google.wearable.watchviewstub.MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
diff --git a/prebuilts/gradle/WatchViewStub/Wearable/src/main/java/com/example/android/google/wearable/watchviewstub/MainActivity.java b/prebuilts/gradle/WatchViewStub/Wearable/src/main/java/com/example/android/google/wearable/watchviewstub/MainActivity.java
new file mode 100644
index 0000000..e4271d2
--- /dev/null
+++ b/prebuilts/gradle/WatchViewStub/Wearable/src/main/java/com/example/android/google/wearable/watchviewstub/MainActivity.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2014 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.example.android.google.wearable.watchviewstub;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.support.v4.view.GestureDetectorCompat;
+import android.support.wearable.view.DismissOverlayView;
+import android.support.wearable.view.WatchViewStub;
+import android.view.GestureDetector;
+import android.view.MotionEvent;
+import android.view.View;
+import android.view.animation.Animation;
+import android.view.animation.ScaleAnimation;
+import android.widget.RelativeLayout;
+
+public class MainActivity extends Activity {
+ private RelativeLayout mRectBackground;
+ private RelativeLayout mRoundBackground;
+
+ private GestureDetectorCompat mGestureDetector;
+ private DismissOverlayView mDismissOverlayView;
+
+ @Override
+ public void onCreate(Bundle b) {
+ super.onCreate(b);
+ setContentView(R.layout.main_activity);
+
+ WatchViewStub stub = (WatchViewStub) findViewById(R.id.stub);
+ stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
+ @Override
+ public void onLayoutInflated(WatchViewStub stub) {
+ mRectBackground = (RelativeLayout) findViewById(R.id.rect_layout);
+ mRoundBackground = (RelativeLayout) findViewById(R.id.round_layout);
+ }
+ });
+
+ mDismissOverlayView = (DismissOverlayView) findViewById(R.id.dismiss_overlay);
+ mGestureDetector = new GestureDetectorCompat(this, new LongPressListener());
+ }
+
+ /**
+ * Animates the layout when clicked. The animation used depends on whether the
+ * device is round or rectangular.
+ */
+ public void onLayoutClicked(View view) {
+ if (mRectBackground != null) {
+ ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, 0.7f, 1.0f, 0.7f,
+ Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
+ scaleAnimation.setDuration(300);
+ scaleAnimation.setRepeatCount(1);
+ scaleAnimation.setRepeatMode(Animation.REVERSE);
+ mRectBackground.startAnimation(scaleAnimation);
+ }
+ if (mRoundBackground != null) {
+ mRoundBackground.animate().rotationBy(360).setDuration(300).start();
+ }
+ }
+
+ @Override
+ public boolean dispatchTouchEvent(MotionEvent event) {
+ return mGestureDetector.onTouchEvent(event) || super.dispatchTouchEvent(event);
+ }
+
+ private class LongPressListener extends GestureDetector.SimpleOnGestureListener {
+ @Override
+ public void onLongPress(MotionEvent event) {
+ mDismissOverlayView.show();
+ }
+ }
+}
diff --git a/prebuilts/gradle/WatchViewStub/screenshots/watch_view_stub_rectangular.png b/prebuilts/gradle/WatchViewStub/screenshots/watch_view_stub_rectangular.png
new file mode 100644
index 0000000..939cb18
--- /dev/null
+++ b/prebuilts/gradle/WatchViewStub/screenshots/watch_view_stub_rectangular.png
Binary files differ
diff --git a/prebuilts/gradle/WatchViewStub/screenshots/watch_view_stub_round.png b/prebuilts/gradle/WatchViewStub/screenshots/watch_view_stub_round.png
new file mode 100644
index 0000000..3055f6d
--- /dev/null
+++ b/prebuilts/gradle/WatchViewStub/screenshots/watch_view_stub_round.png
Binary files differ
diff --git a/prebuilts/gradle/WatchViewStub/settings.gradle b/prebuilts/gradle/WatchViewStub/settings.gradle
index 8522c57..19d00ac 100644
--- a/prebuilts/gradle/WatchViewStub/settings.gradle
+++ b/prebuilts/gradle/WatchViewStub/settings.gradle
@@ -1 +1 @@
-include ':Application', ':Wearable', ':Shared'
+include ':Application', ':Wearable'