onDataChanged() not being called on android wear - android

I'm trying to use Data Items to send a few strings through to my wear, but my wear never seems to receive any signal, because onDataChanged() is never called. I even set a time stamp to ensure the data is always different whenever it is sent.
Is there a specific way I have to install the app onto both devices to get it to work? I'm just clicking run and selecting my phone, then switching modules and doing the same for my wear device.
Here is the code from my main activity on my phone:
public class HomeActivity extends Activity{
public static String TAG = "HomeActivity";
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home_view);
Button mButton = (Button) findViewById(R.id.send_button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendData();
}
});
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}).addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
private void sendData(){
if (mGoogleApiClient!=null){
return;
}
final PutDataMapRequest putRequest = PutDataMapRequest.create("/SAMPLE");
final DataMap map = putRequest.getDataMap();
map.putInt("color", Color.RED);
map.putLong("date", new Date().getTime());
Wearable.DataApi.putDataItem(mGoogleApiClient, putRequest.asPutDataRequest());
}
}
And here is the code on my wearable:
public class LayoutFaceService extends CanvasWatchFaceService implements DataApi.DataListener{
#Override
public void onCreate(){
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected");
Wearable.DataApi.addListener(mGoogleApiClient, LayoutFaceService.this);
}
#Override
public void onConnectionSuspended(int i) {
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
})
.build();
mGoogleApiClient.connect();
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent event : dataEvents) {
if (event.getType() == DataEvent.TYPE_DELETED) {
Log.d(TAG, "DataItem deleted: " + event.getDataItem().getUri());
} else if (event.getType() == DataEvent.TYPE_CHANGED) {
Log.d(TAG, "DataItem changed: " + event.getDataItem().getUri());
}
}
}
And my wear manifest :
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<service
android:name=".LayoutFaceService"
android:label="#string/my_digital_name"
android:permission="android.permission.BIND_WALLPAPER" >
<meta-data
android:name="android.service.wallpaper"
android:resource="#xml/watch_face" />
<meta-data
android:name="com.google.android.wearable.watchface.preview"
android:resource="#drawable/preview_digital" />
<meta-data
android:name="com.google.android.wearable.watchface.preview_circular"
android:resource="#drawable/preview_digital_circular" />
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
<category android:name="com.google.android.wearable.watchface.category.WATCH_FACE" />
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>

In sendData(), your conditional seems to be incorrect; mGoogleApiClient != null is true so you exit right there. Address that and see whether you can get any further; there might be other issues but that is the first obvious one. If that didn't completely fix your issue, then make sure you also include the manifest on your phone in your post.

Related

Activity Fence not working in Awareness API

I tried implementing the Activity Fence using the Google Awareness API. But changes in the user's activity are not getting detected. The headphone fence works as expected though.
ActivityFenceActivity
public class ActivityFenceActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks {
private static final String FENCE_RECEIVER_ACTION = "FENCE_RECEIVE";
private static final String FENCE_WALKING_KEY = "walkingKey";
private static final String FENCE_RUNNING_KEY = "runningKey";
private static final String TAG = ActivityFenceActivity.class.getSimpleName();
private GoogleApiClient googleApiClient;
private TextView activityTextView;
private BroadcastReceiver activityFenceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
Toast.makeText(context, "Recieved", Toast.LENGTH_SHORT).show();
FenceState fenceState = FenceState.extract(intent);
if (TextUtils.equals(fenceState.getFenceKey(), FENCE_WALKING_KEY)) {
switch (fenceState.getCurrentState()) {
case FenceState.TRUE:
activityTextView.setText("User is walking");
break;
case FenceState.FALSE:
activityTextView.setText("User is not walking");
break;
case FenceState.UNKNOWN:
activityTextView.setText("Activity state unknown");
break;
}
} else if (TextUtils.equals(fenceState.getFenceKey(), FENCE_RUNNING_KEY)) {
switch (fenceState.getCurrentState()) {
case FenceState.TRUE:
activityTextView.setText("User is running");
break;
case FenceState.FALSE:
activityTextView.setText("User is not running");
break;
case FenceState.UNKNOWN:
activityTextView.setText("Activity state unknown");
break;
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_fence);
activityTextView = (TextView) findViewById(R.id.activityTextView);
googleApiClient = new GoogleApiClient.Builder(ActivityFenceActivity.this)
.addApi(Awareness.API)
.addConnectionCallbacks(this)
.build();
googleApiClient.connect();
findViewById(R.id.register_fence).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerActivityFence();
}
});
findViewById(R.id.unregister_fence).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
unregisterActivityFence();
}
});
}
#Override
public void onConnected(#Nullable final Bundle bundle) {
Log.d(TAG, "Google API connected");
}
#Override
public void onConnectionSuspended(final int i) {
Log.d(TAG, "Google API connection suspended");
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(activityFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION));
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(activityFenceReceiver);
unregisterActivityFence();
}
private void registerActivityFence() {
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
AwarenessFence runningFence = DetectedActivityFence.during(DetectedActivityFence.RUNNING);
PendingIntent fencePendingIntent = PendingIntent.getBroadcast(this,
0,
new Intent(FENCE_RECEIVER_ACTION),
0);
Awareness.FenceApi.updateFences(googleApiClient, new FenceUpdateRequest.Builder()
.addFence(FENCE_WALKING_KEY, walkingFence, fencePendingIntent).build())
.setResultCallback(new ResultCallbacks<Status>() {
#Override
public void onSuccess(#NonNull final Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Fence registered successfully",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(#NonNull final Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Cannot register activity fence.",
Toast.LENGTH_SHORT).show();
}
});
Awareness.FenceApi.updateFences(googleApiClient, new FenceUpdateRequest.Builder()
.addFence(FENCE_RUNNING_KEY, runningFence, fencePendingIntent).build());
}
private void unregisterActivityFence() {
Awareness.FenceApi.updateFences(
googleApiClient,
new FenceUpdateRequest.Builder()
.removeFence(FENCE_WALKING_KEY)
.removeFence(FENCE_RUNNING_KEY)
.build()).setResultCallback(new ResultCallbacks<Status>() {
#Override
public void onSuccess(#NonNull Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Fence unregistered successfully.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(#NonNull Status status) {
Toast.makeText(ActivityFenceActivity.this,
"Cannot unregister headphone fence.",
Toast.LENGTH_SHORT).show();
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.subhrajyoti.awareness">
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.awareness.API_KEY"
android:value="AIzaSyBEmjlfC87xRUP2FnFynsDdY3QRuI1hIHs" />
</application>
</manifest>
If the headphone fence is working and the activity fence is not, maybe you simply forgot to add the permission in the manifest?
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
I tried to use Awareness API instead of geofencing, I think the problem is how you tested your code.
I'm pretty sure that Awareness uses phone's sensors, so when I use the GPS simulator to simulate a walk, it doesn't trigger anything, but if I use my real phone and walk, BroadcastReceiver is triggered.
However, I don't know how to simulate a "sensor walking" on the emulator!

how to send location data (latitude, longitude) periodically to web server

I am developing real time application so i need to send continuous or some periodic (in seconds) location data as latitude and longitude to web service using rest API. so what can i use to send continuous or periodic data to server? do i need to use back ground service or anything else? i don't know how background service work and how to use it? so can anyone help me for this? thanks in advance.
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
displayLocation();
}
you need to make a service for that if you want to send data continuous to the server even after your application is closed.
Here is how i made my service.
public class FeatureService extends Service
{
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
// make your api call here and other implementations according to your requirement.
super.onCreate();
}
#Override
public void onDestroy()
{
// what you want when service is destroyed
}
Declare your service in Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="Your Serive"
android:enabled="true">
</service>
</application>
And Finally call your service like this in onCreate of your relevant activity.
Intent i= new Intent(this,FeatureService.class);
startService(i);
Get the lat and Long Values, then Schedule a periodic task to run the method to send value to the server
you can use Job Scheduler (https://developer.android.com/reference/android/app/job/JobScheduler.html)
or
You can use android-job/evernote to do a periodic Task
(https://github.com/evernote/android-job)
private void schedulePeriodicJob() {
int jobId = new JobRequest.Builder(DemoSyncJob.TAG)
.setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
.setPersisted(true)
.build()
.schedule();
}

Twilio Device defined in sticky Service is not starting activity if app closed

I need to be able to receive incoming Twilio calls regardless of whether the app is currently running or not.
Once the user has started the app and logged into our server, I start the service shown below.
The Service is started sticky, and at no point is stopService or stopSelf etc ever called, so the service should still be running after the App is closed.
When the App is running, IncomingCallActivity starts fine in response to a Twilio call.
If the App is in the background, IncomingCallActivity still starts fine in response to a Twilio call.
If however the App is closed, IncomingCallActivity no longer starts in response to a Twilio call.
Why isn't IncomingCallActivity started if the App has been closed??
public class CallService extends Service implements Twilio.InitListener, DeviceListener, ConnectionListener {
private Device mDevice;
private Connection mConnection;
#Override
public void onCreate() {
super.onCreate();
registerBroadcastReceiver();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Initialize the Twilio SDK if required
if (!Twilio.isInitialized()) {
Twilio.initialize(getApplicationContext(), this);
} else {
getCapabilityToken("CallService", getUser());
}
...
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
// Unregister broadcast receiver
final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
#Override
public void onInitialized() {
getCapabilityToken("CallService", getUser());
}
#Override
public void onError(Exception e) {
}
private void getCapabilityToken(String string, User user) {
// Request the capability token from the server.
...
}
protected void setCapabilityToken() {
// Create device using the capability token
mDevice = Twilio.createDevice(getUser().capabilityToken, this);
// Set pending intent for Twilio device
Intent intent = new Intent(this, IncomingCallActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mDevice.setIncomingIntent(pendingIntent);
// Broadcast that CallService is ready, to any registered receivers
Intent broadcastIntent = new Intent(App.ACTION__TWILIO_SERVICE_READY);
LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
}
public void connect() {
mConnection = mDevice.connect(null /* parameters */, null /* ConnectionListener */);
if (mConnection == null) {
...
} else {
...
}
}
private void answerCall(Device device, Connection connection) {
if (mConnection != null) {
mConnection.disconnect();
}
mConnection = connection;
mConnection.accept();
}
/**
* BroadcastReceiver
*/
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case App.ACTION__CAPABILITY_TOKEN_OBTAINED:
setCapabilityToken();
break;
case App.ACTION__CONNECT:
connect();
break;
}
}
};
#Override
public void onStartListening(Device device) {
}
#Override
public void onStopListening(Device device) {
}
#Override
public void onStopListening(Device device, int i, String s) {
}
#Override
public boolean receivePresenceEvents(Device device) {
return false;
}
#Override
public void onPresenceChanged(Device device, PresenceEvent presenceEvent) {
}
#Override
public void onConnecting(Connection connection) {
}
#Override
public void onConnected(Connection connection) {
}
#Override
public void onDisconnected(Connection connection) {
}
#Override
public void onDisconnected(Connection connection, int i, String s) {
}
}
Edit:
To clarify how I've declared my services etc, here is my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="au.com.encall.encall"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".IncomingCallActivity"
android:screenOrientation="portrait"/>
<service android:name=".services.CallService"/>
<service android:name=".services.DownloadService"/>
<service
android:name="com.twilio.client.TwilioClientService"
android:exported="false"
android:stopWithTask="false" />
<meta-data
... />
...
</application>
</manifest>
if you are using twilio demo than You need to service in Androidmenifest
<service android:name="com.twilio.client.TwilioClientService" android:exported="false" android:stopWithTask="true"/>
its working for me.
twilio provide their own service. so you need to just declare it on menifest.so does't need to create new service.
jusr remove this service and put it on android menifest.it will automatically start after app close.
Its Work for me no need extra service
<service android:name="com.twilio.client.TwilioClientService" android:exported="false" android:stopWithTask="false"/>
But How can we Handle if token is Expired ? At that time IncomingCallActivity no longer starts

Android Wear: Custom Page on Notification

I'm very new to Android Wear (development). I started reading and implementing the documentation.
However I'm not sure if what I want to implement is "überhaupt" possible.
I can attach custom "actions" on the push notifications I receive, but it seems it can only open a phone-activity. Why can't I open a wear-activity?
The push notifications contains text, which is initially displayed, and data about a soccer match (second page?). I want to display the names of the teams and the score without an intervention of the phone.
So is it possible?
Plus what is the default behaviour? Do I attach this to an action or via an extra page on the notification?
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notification_icon3)
.setContentTitle(this.getString(R.string.notifications_title))
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(matchDetailPendingIntent)
.setAutoCancel(true)
.extend(new NotificationCompat.WearableExtender()
.addPage(CustomDesignedPage) //Is this possible?
.addAction(action)
.setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.soccer_background_big))
);
EDIT
Looking at the Messenger wear-app it seems possible?
The second screen shows a list of messages for example.
I was having the same problem. My solution was to implement an Activity and add to this activity the custom layout. Follow this step.
Step 1: Create a custom layout in your wear module. Example: customlayout.xml
Step 2: Create an Activity in the wear module:
public class WearNotificationActivity extends Activity{
private ImageView mSomeButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customlayout);
mSomeButton= (ImageView) this.findViewById(R.id.somebutton);
mSomeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do something here
}
});
}
}
Step 3. Send the data you want from your phone to your wear:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;
private Button mSomeButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
mSomeButton=(Button) findViewById(R.id.somebutton);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(AppIndex.APP_INDEX_API)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mSomeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendToWear("title","description");
}
});
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
if(!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(mGoogleApiClient!=null) {
mGoogleApiClient.disconnect();
}
}
public void sendToWear(String title, String description){
PutDataMapRequest putDataMapReq = PutDataMapRequest.create("/wear");
putDataMapReq.getDataMap().putString("title", title);
putDataMapReq.getDataMap().putString("description", description);
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest);
}
}
Step 4. Receive the data in your wear and make the notification. For do this you have to create a class in the wear module that extends for WearableListenerService and add this class to your wear manifest.
public class NotificationUpdateService extends WearableListenerService
implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
ResultCallback<DataApi.DeleteDataItemsResult> {
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_CHANGED) {
DataItem item = dataEvent.getDataItem();
if (item.getUri().getPath().compareTo("/wear") == 0) {
DataMap dataMap = DataMapItem.fromDataItem(item).getDataMap();
String title = dataMap.getString("title");
String description=dataMap.getString("description");
buildWearableOnlyNotification(title, description)
}
} else if (dataEvent.getType() == DataEvent.TYPE_DELETED) {
}
}
}
/**
* Builds a simple notification on the wearable.
*/
private void buildWearableOnlyNotification(String title, String content) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setVibrate(new long[]{10, 10, 10, 10, 10})
.setContentTitle(title)
.setContentText(content);
Intent notificationIntent = new Intent(this, WearNotificationActivity.class);
PendingIntent pendingNotificationIntent =
PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder secondpage =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.extend(new NotificationCompat.WearableExtender()
.setDisplayIntent(pendingNotificationIntent)
.setCustomSizePreset(NotificationCompat.WearableExtender.SIZE_FULL_SCREEN)
);
mNotificationBuilder = new NotificationCompat.WearableExtender()
.addPage(secondpage.build()).extend(builder);
Notification notification=mNotificationBuilder.build();
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.notify(Constants.WATCH_ONLY_ID, notification);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
And in your manifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".WearNotificationActivity"
android:exported="true"
android:allowEmbedded="true"
android:taskAffinity=""
android:theme="#android:style/Theme.DeviceDefault.Light"
>
</activity>
<service android:name=".NotificationUpdateService">
<intent-filter>
<action
android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
</application>
Finally you need to add all the dependencies in your phone and wear gradle.
Phone:
compile 'com.google.android.gms:play-services-wearable:7.5.0'
compile 'com.android.support:support-v4:23.1.0'
wearApp project(':wearmodule')
Wear:
compile 'com.google.android.support:wearable:1.3.0'
provided 'com.google.android.wearable:wearable:+'
compile 'com.google.android.gms:play-services-wearable:8.1.0'
I hope this was useful to you.

How to launch android wear activity from mobile

I have been working on a project where I need a button on a mobile to start up an activity on the watch. I have been going through the data layer sample in the sdk but can not get it working. I set up a wearable listener service class, but it is not picking up any messages. The service is added to the manifest but it is still not working. I do have other services too and I am thinking I might have too many services.
On the Wear watch, does an activity have to be running in order for it to start another activity? I want the watch to run nothing until it receives a message, is this possible?
Also, what should my edit configuration settings for wear module be? (eg, do not launch activity, launch default or launch from activity) I just want the wearable to boot up when a message is received.
If anybody can point me in the right direction, it would be hugely appreciated.
Thanks.
Moblie
Accessing the Wearable Data Layer
MainActivity.java
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
Log.d("GoogleApi", "onConnected: " + bundle);
}
#Override
public void onConnectionSuspended(int i) {
Log.d("GoogleApi", "onConnectionSuspended: " + i);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("GoogleApi", "onConnectionFailed: " + connectionResult);
}
GetConnectedNodes
Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult getConnectedNodesResult) {
for (Node node : getConnectedNodesResult.getNodes()) {
sendMessage(node.getId());
}
}
});
SendMessage
public static final String START_ACTIVITY_PATH = "/start/MainActivity";
private void sendMessage(String node) {
Wearable.MessageApi.sendMessage(mGoogleApiClient , node , START_ACTIVITY_PATH , new byte[0]).setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
#Override
public void onResult(MessageApi.SendMessageResult sendMessageResult) {
if (!sendMessageResult.getStatus().isSuccess()) {
Log.e("GoogleApi", "Failed to send message with status code: "
+ sendMessageResult.getStatus().getStatusCode());
}
}
});
}
Wear
Implement a Message Listener
WearDataLayerListenerService.java
public class WearDataLayerListenerService extends WearableListenerService {
public static final String START_ACTIVITY_PATH = "/start/MainActivity";
#Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
if(messageEvent.getPath().equals(START_ACTIVITY_PATH)){
Intent intent = new Intent(this , MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}}
Add Listener Service to Manifest
<service
android:name=".WearDataLayerListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>

Categories

Resources