简体   繁体   中英

Sync data with android wear

Mobile - Activity

public class TestActivity extends Activity implements DataApi.DataListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient mGoogleApiClient;

Button syncBtn;

static int click = 0;

@Override
protected void onStart()
{
    super.onStart();

    mGoogleApiClient.connect();
}

@Override
protected void onPause()
{
    super.onPause();

    mGoogleApiClient.disconnect();
}

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_test);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    //mGoogleApiClient.connect();

    syncBtn = (Button) findViewById(R.id.syncBtn);

    syncBtn.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            if(mGoogleApiClient.isConnected())
            {
                PutDataMapRequest mapRequest = PutDataMapRequest.create(Constants.RUN_UPDATE_NOTIFICATION);
                mapRequest.getDataMap().putDouble(Constants.NOTIFICATION_TIMESTAMP, System.currentTimeMillis());
                mapRequest.getDataMap().putString(Constants.NOTIFICATION_TITLE, "This is a Title");
                mapRequest.getDataMap().putString(Constants.NOTIFICATION_CONTENT, "This is a text with some, notification, see click:  "+click++);
                PutDataRequest request = mapRequest.asPutDataRequest();
                Wearable.DataApi.putDataItem(mGoogleApiClient, request).setResultCallback(new ResultCallback<DataApi.DataItemResult>()
                {
                    @Override
                    public void onResult(DataApi.DataItemResult dataItemResult)
                    {
                        if (dataItemResult.getStatus().isSuccess())
                        {
                            System.out.println(" syncing successful...."+dataItemResult.getStatus());
                        }
                        else
                        {
                            System.out.println(" syncing failed.."+dataItemResult.getStatus());
                        }
                    }
                });
            }
            else
            {
                System.out.println("not connected....");
            }
        }
    });
}

@Override
public void onConnected(Bundle bundle)
{

}

@Override
public void onConnectionSuspended(int i)
{

}

@Override
public void onDataChanged(DataEventBuffer dataEventBuffer)
{

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult)
{

}

}

Getting output from Mobile - activity - System.out﹕ syncing successful....Status{statusCode=SUCCESS, resolution=null}

But it show no response on Wear - activity(Want to show something on android wear that device has synced).

Below is the code for Wear - activity

public class NotificationUpdateService extends WearableListenerService{
private int notificationId = 001;

@Override
public void onDataChanged(DataEventBuffer dataEvents)
{
    super.onDataChanged(dataEvents);

    System.out.println("****** ");

    for(DataEvent dataEvent: dataEvents)
    {
        if(dataEvent.getType() == DataEvent.TYPE_CHANGED)
        {
            DataMap dataMap = DataMapItem.fromDataItem(dataEvent.getDataItem()).getDataMap();

            String title = dataMap.getString("title");
            String content = dataMap.getString("content");

            System.out.println("title:  "+title+" content: "+content);

            sendNotification(title, content);
        }
    }
}

private void sendNotification(String title, String content)
{
    Intent viewIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingViewIntent = PendingIntent.getActivity(this, 0, viewIntent, 0);

    // this intent will be sent when the user swipes the notification to dismiss it
   /* Intent dismissIntent = new Intent(Constants.ACTION_DISMISS);
    PendingIntent pendingDeleteIntent = PendingIntent.getService(this, 0, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT);*/

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(content)
            .setContentIntent(pendingViewIntent);
    //.setDeleteIntent(pendingDeleteIntent)

    Notification notification = builder.build();

    NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
    notificationManagerCompat.notify(notificationId++, notification);
}}

Android manifest.xml - Wear

 <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.speedometer" >

<uses-feature android:name="android.hardware.type.watch" />

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

   <service
       android:name=".NotificationUpdateService">

       <intent-filter>
           <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
       </intent-filter>
   </service>
</application></manifest>

Below is the Android manifest for Mobile

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.speedometer" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <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>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".LocationActivity"
        android:label="@string/title_activity_location" >
    </activity>
    <activity
        android:name=".TestActivity"
        android:label="@string/title_activity_test" >
    </activity>
</application></manifest>

You have the line "mGoogleApiClient.connect();" commented out and therefor are not guaranteed to have usable access to the play services WearableAPI

Additionally there are two main reasons why onDataChanged won't be triggered on an android wear device 1) The DataItem you are "putting" hasn't been changed since the last time you put it into the DataLayer. Try adding a timestamp to avoid this issue for debugging purposes. 2) The package name and signature are not identical on the wear apk and mobile apk. Do all you can to ensure these are identical on both modules.

Make sure both the wearable and handheld app modules have the same package name and version number. Also check the applicationId , versionName and versionCode in build.gradle files on both the wearable and handheld app modules of your project if you are building with Gradle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM