Подтвердить что ты не робот

Результат Wearable.NodeApi.getConnectedNodes никогда не вызывался

i разработка приложения для износа android. Ниже кода с объяснением проблемы

 if(mGoogleApiClient.isConnected()){
            K.i("Always called!");
            Wearable.NodeApi.getConnectedNodes(mGoogleApiClient).setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
                @Override
                public void onResult(NodeApi.GetConnectedNodesResult nodes) {
                    K.i("Never called :( ");
                    for (Node node : nodes.getNodes()) {
                        Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), message, null);
                    }
                }
            });      
        }

UPD: я решаю проблему, выключая и снова включаю свой телефон (Nexus 5) Может быть, есть более простой способ решить проблему?

Попробовал добавить .await() и AsyncTask, но результат тот же

4b9b3361

Ответ 1

Я считаю, что вы можете только позвонить getConnectedNodes один раз за соединение GoogleApiClient. Вы хотите кэшировать идентификатор node при первом получении результата, а затем использовать обратные вызовы onPeerConnected/Disconnected(), чтобы отслеживать, действительно ли имеет значение node.

Ответ 2

Если вы посмотрите образцы одежды для google, там будет проект под названием FindMyPhone. Я думаю, что они решают вашу проблему намного чище. Они проверяют, подключено или отключено устройство с помощью фоновой службы.

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

}

Они также добавляют это в AndroidManifest.xml

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

Ответ 3

Я получил его работу:

Инициируйте клиент Google API:

private void initGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Wearable.API)
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle bundle) {
                    Log.d(TAG, "ConnectionCallback onConnected");
                    if (servicesAvailable()) {
                        // new CheckWearableConnected().execute();
                        resolveNodes();
                    }
                }

                @Override
                public void onConnectionSuspended(int i) {
                    Log.d(TAG, "ConnectionCallback onConnectionSuspended");
                }
            })
            .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult connectionResult) {
                    Log.d(TAG, "ConnectionCallback onConnectionFailed");
                    //TODO do something on connection failed
                }
            })
            .build();

}

Затем в вашем методе onStart подключите клиент API:

@Override
public void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

И чтобы очистить, в методе onStop:

@Override
protected void onStop() {
    super.onStop();
    Log.d(TAG, "onStop");
    if (mGoogleApiClient != null)
        if (mGoogleApiClient.isConnected()) mGoogleApiClient.disconnect();
}

Ответ 4

Вот полный код проверки:

добавьте это в файл gradle:

compile 'com.google.android.gms:play-services-wearable:9.4.0'

И используйте эту функцию, чтобы проверить, подключен ли носитель:

@WorkerThread
public boolean isWearableAvailable(Context context) {
    NotificationManagerCompat.from(context).cancel(NotificationType.WEARABLE_IN_CALL.getId());
    final GoogleApiClient googleApiClient = new Builder(context).addApi(Wearable.API).build();
    final ConnectionResult connectionResult = googleApiClient.blockingConnect();
    if (connectionResult.isSuccess()) {
        NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await();
        for (Node node : nodes.getNodes()) {
            if (node.isNearby()) 
                return true;
        }
    }
    return false;
}