我做了一個稱爲SendToWear
與被叫sendMessage(Context context, String path, @Nullable String data)
靜態方法,該方法找到所有連接的節點,併發送數據到任何找到的節點類。手持設備無法連接到GoogleApiClient
這個類是相同的我叫SendToPhone
的Android Wear設備,其成功的作品使用,並會發送一個其他類的發射後不管消息,我連接的手機上,但SendToWear
(與相同代碼的類,如上所述)不會。
問題是,在本節:
GoogleApiClient sClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.build();
ConnectionResult connectionResult =
sClient.blockingConnect(5, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to sClient.");
return 0;
} else Log.d(TAG, "sClient connected!");
的手持設備,總是返回「無法連接到sClient」。有人可以解釋這一點嗎?
謝謝。
全部下面的代碼:
import android.content.Context;
import android.support.annotation.Nullable;
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.MessageApi;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class SendToPhone {
public static int sendMessage(Context context, String path, @Nullable String data){
Log.d(TAG, "Path: " + path + "\tData: " + data);
ArrayList<String> nodes;
int sent; // amount of nodes which received the message
if(context == null || path == null){
Log.d(TAG, "Context or Path is null.");
return 0;
}
GoogleApiClient sClient = new GoogleApiClient.Builder(context)
.addApi(Wearable.API)
.build();
ConnectionResult connectionResult =
sClient.blockingConnect(5, TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Log.e(TAG, "Failed to connect to sClient.");
return 0;
} else Log.d(TAG, "sClient connected!");
nodes = getNodes(sClient);
if(nodes.size() == 0) return 0;
for(int i = sent = 0; i < nodes.size(); i++) {
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
sClient, nodes.get(i), path, data.getBytes()).await();
// was not able to send message
if(result.getStatus().isSuccess())
++sent;
}
sClient.disconnect();
Log.d(TAG, "SENT: " + sent);
return sent;
}
private static ArrayList<String> getNodes(GoogleApiClient client) {
ArrayList<String> results = new ArrayList<String>();
NodeApi.GetConnectedNodesResult nodes =
Wearable.NodeApi.getConnectedNodes(client).await(3, TimeUnit.SECONDS);
if(nodes == null || !nodes.getStatus().isSuccess())
return results;
for (Node node : nodes.getNodes()) {
results.add(node.getId());
}
return results;
}
}
你並不需要以前連接到做一個同步連接(如你在做的方法'DoSomething的()')。儘管如此,你的代碼仍然有效。 – 2015-08-31 11:45:13