与android磨损同步数据

时间:2015-07-23 12:52:49

标签: android wear-os android-wear-data-api

移动 - 活动

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

}

}

从移动中获取输出 - 活动 - System.out﹕ syncing successful....Status{statusCode=SUCCESS, resolution=null}

但它显示没有对Wear - 活动的反应(想要在设备已同步的机器人佩戴上显示某些内容)。

以下是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 - 穿

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

以下是适用于移动设备的Android清单

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

2 个答案:

答案 0 :(得分:0)

你有一行&#34; mGoogleApiClient.connect();&#34;注释掉并因此无法保证可以访问Play服务WearableAPI

此外,有两个主要原因导致onDataChanged无法在Android服装设备上触发1)您正在使用的DataItem&#34; put&#34;自上次将其放入DataLayer以来,还没有更改过。尝试添加时间戳以避免此问题以进行调试。 2)套装名称和签名在wear apk和mobile apk上不一样。尽你所能确保两个模块上的相同。

答案 1 :(得分:0)

确保可穿戴应用程序和手持式应用程序模块具有相同的程序包名称和版本号。如果您使用Gradle构建,请同时检查项目的可穿戴和手持应用程序模块上applicationId versionNameversionCode个文件中的build.gradle12-31 05:11:36.314 26809-26809/com.androidatc.customviewindrawer E/AndroidRuntime: java.lang.IllegalStateException: Could not find a method loginUser(View) in the activity class com.androidatc.customviewindrawer.MainActivity for onClick handler on view class android.widget.Button with id 'btnLogin' 12-31 05:11:36.314 26809-26809/com.androidatc.customviewindrawer E/AndroidRuntime: at android.view.View$1.onClick(View.java:4052) 12-31 05:11:36.314 26809-26809/com.androidatc.customviewindrawer E/AndroidRuntime: at android.view.View.performClick(View.java:4820) 12-31 05:11:36.314 26809-26809/com.androidatc.customviewindrawer E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:20158) package com.androidatc.customviewindrawer; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.support.v7.app.ActionBarActivity; import android.support.v7.app.ActionBar; import android.app.Fragment; //import android.support.v4.app.Fragment; //import android.support.v4.app.FragmentManager; import android.app.FragmentManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.support.v4.widget.DrawerLayout; import android.widget.Toast; public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, SearchCatFragment.OnFragmentInteractionListener, AndroidBarcodeQrExample.OnFragmentInteractionListener, BarCodeFrag.OnFragmentInteractionListener, LoginFrag.OnFragmentInteractionListener, MainViewFragment.OnFragmentInteractionListener { /** * Fragment managing the behaviors, interactions and presentation of the navigation drawer. */ private NavigationDrawerFragment mNavigationDrawerFragment; /** * Used to store the last screen title. For use in {@link #restoreActionBar()}. */ private CharSequence mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer); mTitle = getTitle(); // Set up the drawer. mNavigationDrawerFragment.setUp( R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout)); } @Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.container, PlaceholderFragment.newInstance(position + 1)) .commit(); } public void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { if (resultCode == RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String format = intent.getStringExtra("SCAN_RESULT_FORMAT"); Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format, Toast.LENGTH_LONG); toast.show(); } } } public void onSectionAttached(int number) { switch (number) { case 1: mTitle = getString(R.string.title_section1); break; case 2: mTitle = getString(R.string.title_section2); break; case 3: mTitle = getString(R.string.title_section3); break; case 4: mTitle = getString(R.string.title_section4); break; case 5: mTitle = getString(R.string.title_section5); break; } } public void restoreActionBar() { ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!mNavigationDrawerFragment.isDrawerOpen()) { // Only show items in the action bar relevant to this screen // if the drawer is not showing. Otherwise, let the drawer // decide what to show in the action bar. getMenuInflater().inflate(R.menu.menu_main, menu); restoreActionBar(); return true; } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onFragmentInteraction(Uri uri) { } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { /** * The fragment argument representing the section number for this * fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; /** * Returns a new instance of this fragment for the given section * number. */ public static PlaceholderFragment newInstance(int sectionNumber) { PlaceholderFragment fragment = new PlaceholderFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((MainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } } }