将字符串从手表发送到手机 [英] Sending String from watch to phone

查看:50
本文介绍了将字符串从手表发送到手机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码将字符串从可穿戴设备发送到移动设备.此实现基于 https://github.com/twotoasters/Wear-MessageApiDemo/

如果连接到我增加的设备的时间延迟有问题CONNECTION_TIME_OUT_MS 从 100 到 2000(毫秒).

我在移动清单中添加:

<服务android:name=".ListenerService" ><意图过滤器><action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED"/></意图过滤器></服务>

代替

<服务android:name=".ListenerService" ><意图过滤器><action android:name="com.google.android.gms.wearable.BIND_LISTENER"/></意图过滤器></服务>

因为 com.google.android.gms.wearable.BIND_LISTENER 已弃用

代码编译通过,但电话未收到消息.

方法

private void showToast(String message) {Log.d(TAG, "收到消息:" + message);}

应该在接收到消息时在 listenerService 内触发.

问题是从未收到消息.我是否正确实现了消息 API?

API 版本:23

来源:

<块引用>

移动组件

启动 listenerService :

----------------------------------- MainActivity.onCreate ---------------

 @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);新的 ListenerService();}

定义监听器服务来监听消息

----------------------------------- ListenerService ------------------

import android.util.Log;导入 android.widget.TextView;导入 com.google.android.gms.wearable.MessageEvent;导入 com.google.android.gms.wearable.WearableListenerService;公共类 ListenerService 扩展了 WearableListenerService {private static final String TAG = "ListenerService";TextView mTextView;@覆盖public void onMessageReceived(MessageEvent messageEvent) {MainActivity.mTextView.setText("收到消息");showToast(messageEvent.getPath());}私人无效showToast(字符串消息){Log.d(TAG, "收到消息:" + message);}}

在清单中定义服务

----------------------------------- AndroidManifest.xml ----------------

<uses-permission android:name="android.permission.WAKE_LOCK"/><uses-permission android:name="android.permission.BODY_SENSORS"/><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/><uses-permission android:name="android.permission.GPS_PROVIDER"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.INTERNET"/><申请机器人:allowBackup =真"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><意图过滤器><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></意图过滤器></活动><服务android:name=".ListenerService" ><意图过滤器><action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED"/></意图过滤器></服务></应用程序></清单>

<块引用>

磨损组件

主活动:

包通用;导入 android.content.Context;导入 android.location.Location;导入 android.location.LocationManager;导入 android.os.Bundle;导入 android.support.wearable.activity.WearableActivity;导入 android.support.wearable.view.BoxInsetLayout;导入 android.util.Log;导入 android.view.View;导入 android.widget.TextView;导入 com.google.android.gms.common.api.GoogleApiClient;导入 com.google.android.gms.wearable.Node;导入 com.google.android.gms.wearable.NodeApi;导入 com.google.android.gms.wearable.Wearable;导入 java.text.SimpleDateFormat;导入 java.util.Date;导入 java.util.List;导入 java.util.Locale;导入 java.util.concurrent.TimeUnit;公共类 MainActivity 扩展了 WearableActivity {私有静态最终长 CONNECTION_TIME_OUT_MS = 2000;private static final String MESSAGE = "Hello Wear!";私人 GoogleApiClient 客户端;私有字符串 nodeId;private static final String TAG = "MainActivity";私有 BoxInsetLayout mContainerView;/*** 初始化 GoogleApiClient 并获取连接设备的 Node ID.*/私有无效initApi(){客户端 = getGoogleApiClient(this);检索设备节点();}/*** 返回一个可以访问 Wear API 的 GoogleApiClient.* @param 上下文* @return 一个可以调用 Wea​​r API 的 GoogleApiClient*/私有 GoogleApiClient getGoogleApiClient(上下文上下文){返回新的 GoogleApiClient.Builder(context).addApi(Wearable.API).建造();}/*** 连接到 GoogleApiClient 并检索连接设备的节点 ID.如果有* 多个连接的设备,返回第一个节点 ID.*/私有无效检索设备节点(){新线程(新运行(){@覆盖公共无效运行(){client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);NodeApi.GetConnectedNodesResult 结果 =Wearable.NodeApi.getConnectedNodes(client).await();列表<节点>节点 = result.getNodes();如果(节点.大小()> 0){Log.d(TAG, "nodeId "+nodeId);nodeId = nodes.get(0).getId();}客户端断开连接();}}).开始();}@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initApi();发送Toast();}/*** 向连接的移动设备发送消息,告诉它显示 Toast.*/私有无效 sendToast() {如果(节点 ID != null){新线程(新运行(){@覆盖公共无效运行(){client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);Wearable.MessageApi.sendMessage(client, nodeId, MESSAGE, null);客户端断开连接();}}).开始();}}}

更新:

这是添加到移动模块的类,用于监听接收到的消息:

package com.receivers;导入 android.content.BroadcastReceiver;导入 android.content.Context;导入 android.content.Intent;导入 android.util.Log;公共类 MessageListener 扩展了 BroadcastReceiver {private static final String TAG = "MessageListener";@覆盖public void onReceive(上下文上下文,意图意图){String str = intent.getAction();Log.i(TAG, "onReceive 触发:"+str);}}

AndroidManifest.xml 中 MessageListener 的配置:

 <意图过滤器><action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED"/></意图过滤器></接收器>

我尝试在 String str = intent.getAction(); 行设置断点,但 onReceive 方法似乎没有被调用.

在 Wear 模块中,方法 onNodeFound() 似乎可以正确发送消息,因为这一行 Wearable.MessageApi.sendMessage(googleApiClient, nodeId, MESSAGE_PATH, "Hello Wear!".getBytes(Charset.forName("UTF-8"))); 正在被调用.我是否正确设置了 MessageListener ?

更新 2:

接收者活动:

import android.app.Activity;导入 android.content.BroadcastReceiver;导入 android.content.Context;导入 android.content.Intent;导入 android.content.IntentFilter;导入 android.os.Bundle;导入 android.support.v4.content.LocalBroadcastManager;导入 android.util.Log;公共类 ReceiverActivity 扩展 Activity {@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,new IntentFilter("custom-event-name"));}私有广播接收器 mMessageReceiver = 新广播接收器(){@覆盖public void onReceive(上下文上下文,意图意图){//获取包含在 Intent 中的额外数据String message = intent.getStringExtra("EXTRA_MESSAGE");Log.d("receiver", "收到消息:" + message);}};@覆盖受保护的无效 onDestroy() {LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);super.onDestroy();}}

ListenerService 中,方法 onMessageReceived 被触发,并在此处尝试广播消息:

@Overridepublic void onMessageReceived(MessageEvent messageEvent) {super.onMessageReceived(messageEvent);Log.d("tester", "收到来自wear的消息:" + new String(messageEvent.getData()));final String message = new String(messageEvent.getData());最终意图 messageIntent = new Intent();messageIntent.putExtra("EXTRA_MESSAGE", message);//定义你的额外LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);}

在 AndroidManifest.xml 中启动活动:

</活动>

但是 ReceiverActivity 似乎没有收到消息,ReceiverActivity 设置是否正确?

更新 3:

根据评论开始我添加的活动:

 Intent intent = new Intent(this, ReceiverActivity.class);开始活动(意图);

MainActivity.onCreate :

 @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);Intent intent = new Intent(this, ReceiverActivity.class);开始活动(意图);......

解决方案

new ListenerService();

这不是您启动任何服务的方式.这只是创建了一个什么都不做的服务实例,并且会在 onCreate() 退出后被收集.

当您收到消息时,系统会启动此服务.您只需要在清单中定义它.此外,您可能需要为您收到的消息定义一个路径,例如

<意图过滤器><action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED"/><data android:scheme="wear" android:host="*" android:pathPrefix="/message"/></意图过滤器></服务>

这就是设置服务所需的全部内容.另外,请记住,为了接收消息,您的 Wear 应用和手持应用应具有相同的包名称 (applicationId).仔细检查您的口味或构建类型是否有不匹配的 applicationId.因此,如果您在 build.gradle 中有 applicationId,请确保它们与 Wear 和 Handhelp 应用程序项目相匹配

defaultConfig {applicationIdcom.runner"

关于更新用户界面:

@Overridepublic void onMessageReceived(MessageEvent messageEvent) {MainActivity.mTextView.setText("收到消息");}

这不是一种服务与活动交互的方式.当服务运行时,活动可能正在运行,也可能没有运行.仅从 Activity 更新 Activity UI.如果您需要向用户显示消息,请使用 BroadcastReceiverObserver.

注意onMessageReceived()不会在Main UI线程上运行,所以在显示Toast<之前使用Handler/code> 那里.

所以如果你想把消息从这个Service传递给Activity,方法之一就是

@Overridepublic void onMessageReceived(MessageEvent messageEvent) {最终字节[] 数据 = messageEvent.getData();如果(数据!= null){final String message = new String(data, Charset.forName("UTF-8"));final Intent messageIntent = new Intent("custom-event-name");intent.putExtra(EXTRA_MESSAGE,消息);//定义你的额外LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);//在您的 Activity 中从 LocalBroadcastManager 注册 BroadcastReiver 以接收此广播}}

或者,如果您想在 Activity 未运行的情况下启动它,则需要不同的方法:

服务:

@Overridepublic void onMessageReceived(MessageEvent messageEvent) {最终字节[] 数据 = messageEvent.getData();如果(数据!= null){final String message = new String(data, Charset.forName("UTF-8"));最终意图activityIntent = new Intent(this, ReceiverActivity.class);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.putExtra("EXTRA_MESSAGE", message);开始活动(意图);}}//在这种情况下,在 Activity 中,如果它是显式启动的,则不需要 BroadcastReceiver//相反,你可以从 Activity Intent 中获得额外的@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);handleIntent(getIntent());}@覆盖受保护的无效 onNewIntent(意图意图){super.onNewIntent(意图);处理意图(意图);}私人无效handleIntent(意图意图){String message = intent.getStringExtra("EXTRA_MESSAGE");}

In Wear 组件

initApi();发送Toast();

您使用可能同时运行的不同线程,因此当 sendToast() 运行时,您实际上可能尚未解析 nodeId.

我建议做的是将 onCreate() 中的 GoogleApiClient 与一个监听器连接起来.客户端连接后,开始获取节点.你不需要产生你自己的线程,如果你使用 setResultCallback() 而不是 await()

,API 是异步的

编辑 14/02/2018:正如 Rajesh 在评论中提到的,Wearable.API 已被弃用.下面的答案指的是旧 API,它们在撰写本文时是新的.我将保留旧答案,但我没有时间研究如何使用新 API 执行此操作.

private static final String MESSAGE_PATH = "/message";私人 GoogleApiClient googleApiClient;@覆盖protected void onCerate(Bundle state) {super.onCreate(state);googleApiClient = getGoogleApiClient(this);googleApiClient.connect();}@覆盖受保护的无效 onDestroy() {super.onDestroy();googleApiClient.disconnect();}私有 GoogleApiClient getGoogleApiClient(上下文上下文){返回新的 GoogleApiClient.Builder(上下文).addApi(Wearable.API).addConnectionCallbacks(mConnectionCallbacks).建造();}私有无效 findNodes() {Wearable.NodeApi.getConnectedNodes(googleApiClient).setResultCallback(new ResultCallback() {@覆盖公共无效 onResult(@NonNull final NodeApi.GetConnectedNodesResult getConnectedNodesResult) {列表<节点>节点 = result.getNodes();if (nodes != null && !nodes.isEmpty()) {nodeId = nodes.get(0).getId();Log.d(TAG, "nodeId "+ nodeId);onNodeFound();}}});}私有无效 onNodeFound() {如果(节点 ID != null){//现在你有了你的节点,发送一条消息,确保路径像清单中的路径一样开始//你以为的消息其实是一条路径,实际的消息是字节数组.//您可以在路径中连接您的消息,但请记住,您必须解析字符串然后Wearable.MessageApi.sendMessage(client, nodeId, MESSAGE_PATH, "Hello Wear!".getBytes(Charset.forName("UTF-8")));}}私有最终 GoogleApiClient.ConnectionCallbacks mConnectionCallbacks= 新 GoogleApiClient.ConnectionCallbacks() {@覆盖public void onConnected(@Nullable final Bundle bundle) {查找节点();}@覆盖public void onConnectionSuspended(final int i) {}};

I'm attempting to send a string from wearable to mobile device using code below. This implementation is based on https://github.com/twotoasters/Wear-MessageApiDemo/

Case there is an issue with the time delay in connecting to the device I've increased CONNECTION_TIME_OUT_MS from 100 to 2000 (milliseconds).

To the mobile manifest I add :

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

instead of

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

as com.google.android.gms.wearable.BIND_LISTENER is deprecated

The code compiles but the message is not received by phone.

The method

private void showToast(String message) {

        Log.d(TAG, "received message : " + message);

    }

Should fire within the listenerService when a message is received.

The issue is a message is never received. Have I implemented the message api correctly ?

API version : 23

Source :

Mobile component

Kick off listenerService :

----------------------------------- MainActivity.onCreate ---------------

  @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new ListenerService();

}

Define the Listener service to listen for messages

----------------------------------- ListenerService ------------------

import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;

public class ListenerService extends WearableListenerService {

    private static final String TAG = "ListenerService";

    TextView mTextView;

    @Override
    public void onMessageReceived(MessageEvent messageEvent) {
        MainActivity.mTextView.setText("got message");
        showToast(messageEvent.getPath());
    }

    private void showToast(String message) {

        Log.d(TAG, "received message : " + message);

    }
}

Define the service in the manifest

----------------------------------- AndroidManifest.xml ----------------

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

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.BODY_SENSORS"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.GPS_PROVIDER" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />

    <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">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

    </application>

</manifest>

Wear component

MainActivity :

package common;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.support.wearable.view.BoxInsetLayout;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.Wearable;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class MainActivity extends WearableActivity {

    private static final long CONNECTION_TIME_OUT_MS = 2000;
    private static final String MESSAGE = "Hello Wear!";

    private GoogleApiClient client;
    private String nodeId;

    private static final String TAG = "MainActivity";

    private BoxInsetLayout mContainerView;


    /**
     * Initializes the GoogleApiClient and gets the Node ID of the connected device.
     */
    private void initApi() {
        client = getGoogleApiClient(this);
        retrieveDeviceNode();
    }

    /**
     * Returns a GoogleApiClient that can access the Wear API.
     * @param context
     * @return A GoogleApiClient that can make calls to the Wear API
     */
    private GoogleApiClient getGoogleApiClient(Context context) {
        return new GoogleApiClient.Builder(context)
                .addApi(Wearable.API)
                .build();
    }

    /**
     * Connects to the GoogleApiClient and retrieves the connected device's Node ID. If there are
     * multiple connected devices, the first Node ID is returned.
     */
    private void retrieveDeviceNode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
                NodeApi.GetConnectedNodesResult result =
                        Wearable.NodeApi.getConnectedNodes(client).await();
                List<Node> nodes = result.getNodes();
                if (nodes.size() > 0) {
                    Log.d(TAG, "nodeId "+nodeId);
                    nodeId = nodes.get(0).getId();
                }
                client.disconnect();
            }
        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initApi();
        sendToast();

    }


    /**
     * Sends a message to the connected mobile device, telling it to show a Toast.
     */
    private void sendToast() {
        if (nodeId != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    client.blockingConnect(CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS);
                    Wearable.MessageApi.sendMessage(client, nodeId, MESSAGE, null);
                    client.disconnect();
                }
            }).start();
        }
    }

}

Update :

Here is the class added to mobile module to listen for received messages :

package com.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class MessageListener extends BroadcastReceiver {

    private static final String TAG = "MessageListener";

    @Override
    public void onReceive(Context context, Intent intent) {
        String str = intent.getAction();
        Log.i(TAG, "onReceive triggered : "+str);
    }
}

Config of MessageListener in AndroidManifest.xml :

    <receiver android:name="com.receivers.MessageListener">
        <intent-filter>
            <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
        </intent-filter>
    </receiver>

I've tried setting a breakpoint at line String str = intent.getAction(); but onReceive method does not appear to be invoked.

Within the wear module the method onNodeFound() does appear to send the message correctly as this line Wearable.MessageApi.sendMessage(googleApiClient, nodeId, MESSAGE_PATH, "Hello Wear!".getBytes(Charset.forName("UTF-8"))); is being invoked. Have i setup the MessageListener correctly ?

Update 2 :

ReceiverActivity :

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class ReceiverActivity extends Activity {

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

        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
                new IntentFilter("custom-event-name"));

    }

    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String message = intent.getStringExtra("EXTRA_MESSAGE");
            Log.d("receiver", "Got message: " + message);
        }
    };

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

}

Within the ListenerService , method onMessageReceived is being fired and here trying to broadcast the message :

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    super.onMessageReceived(messageEvent);
    Log.d("tester", "received a message from wear: " + new String(messageEvent.getData()));

    final String message = new String(messageEvent.getData());
    final Intent messageIntent = new Intent();
    messageIntent.putExtra("EXTRA_MESSAGE", message); // define your extra
    LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);

}

Starting the activity in AndroidManifest.xml :

<activity android:name=".ReceiverActivity">
</activity>

But ReceiverActivity does not appear to receive message, is ReceiverActivity setup correctly ?

Update 3 :

As per comment to start the activity I add :

    Intent intent = new Intent(this, ReceiverActivity.class);
    startActivity(intent);

to MainActivity.onCreate :

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, ReceiverActivity.class);
        startActivity(intent);
        ......

解决方案

new ListenerService();

This is not how you start any Service. This just creates a Servie instance that will do nothing and will be collected after onCreate() exits.

This Service will be started by the system when you'll receive a message. You only need to define it in the manifest. Also, you might need to define a path for messages you receive, like

<service android:name=".ListenerService" >
    <intent-filter>
        <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
        <data android:scheme="wear" android:host="*" android:pathPrefix="/message"/>
    </intent-filter>
</service>

That's all you need for your Service to be set up. Also, keep in mind that in order to receive messages your Wear app and Handheld app should have the same package name (applicationId). Double check you don't have mismatching applicationId for flavors or buildTypes. So if you have applicationId in build.gradle, make sure they match for both wear and handhelp app projects

defaultConfig {
    applicationId "com.runner"

About updating UI:

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    MainActivity.mTextView.setText("got message");
}

This is not a way to interact a Service with Activity. Activity might or might not be running when Service runs. Only update Activtity UI from Activity. If you need to show user a message, use a BroadcastReceiver or an Observer.

Note that onMessageReceived() will not be ran on Main UI thread, so use a Handler before showing a Toast there.

So if you want to pass the Message from this Service to Activity, one of the ways is like

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    final byte[] data = messsageEvent.getData();
    if (data != null) {
        final String message = new String(data, Charset.forName("UTF-8"));
        final Intent messageIntent = new Intent("custom-event-name");
        intent.putExtra(EXTRA_MESSAGE, message); // define your extra
        LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent); 
        // Register BroadcastReiver from LocalBroadcastManager in your Activity to receive this broadcast
    }
}

Or if you want to start Activity if it's not running, you need a different approach:

<activity
    android:name=".ReceiverActivity"
    android:launchMode="singleTop"/>

Service:

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    final byte[] data = messsageEvent.getData();
    if (data != null) {
        final String message = new String(data, Charset.forName("UTF-8"));
        final Intent activityIntent = new Intent(this, ReceiverActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("EXTRA_MESSAGE", message);
        startActivity(intent);
    }
}

// In this case, in Activity, if it's explicitly started, you don't need a BroadcastReceiver
// Instead, you can get the extra from Activity Intent

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

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    String message = intent.getStringExtra("EXTRA_MESSAGE");
}

In Wear component

initApi();
sendToast();

you use different threads that may run simultaneously so when sendToast() runs you may actually have nodeId not resolved yet.

What I suggest doing is connecting GoogleApiClient in onCreate() with a Listener. Once the client connects, start getting the node. You don't need to spawn your own threads, the API is asynchronous if you use setResultCallback() instead of await()

Edit 14/02/2018: as Rajesh mentioned in the comments, Wearable.API is deprecated. The answer below refers to old API, which were new on the time of writing. I am leaving the old answer as is, but I don't have time to investigate how to do this with new APIs.

private static final String MESSAGE_PATH = "/message";

private GoogleApiClient googleApiClient;

@Override
protected void onCerate(Bundle state) {
    super.onCreate(state);
    googleApiClient = getGoogleApiClient(this);
    googleApiClient.connect();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    googleApiClient.disconnect();
}

private GoogleApiClient getGoogleApiClient(Context context) {
    return new GoogleApiClient.Builder(context)
            .addApi(Wearable.API)
            .addConnectionCallbacks(mConnectionCallbacks)
            .build();
}

private void findNodes() {
     Wearable.NodeApi.getConnectedNodes(googleApiClient).setResultCallback(
            new ResultCallback<NodeApi.GetConnectedNodesResult>() {
                @Override
                public void onResult(
                        @NonNull final NodeApi.GetConnectedNodesResult getConnectedNodesResult) {
                    List<Node> nodes = result.getNodes();
                    if (nodes != null && !nodes.isEmpty()) {
                        nodeId = nodes.get(0).getId();
                        Log.d(TAG, "nodeId "+ nodeId);
                        onNodeFound();
                    }
                }
            });
}

private void onNodeFound() {
    if (nodeId != null) {
        // Now you have your node, send a message, make sure the path starts like the path in manifest
        // What you thought is a message is actually a path, and the actual message is the byte array.
        // You may concat your message in path though, but keep in mind you will have to parse the string then
        Wearable.MessageApi.sendMessage(client, nodeId, MESSAGE_PATH, "Hello Wear!".getBytes(Charset.forName("UTF-8")));
    }
}

private final GoogleApiClient.ConnectionCallbacks mConnectionCallbacks
        = new GoogleApiClient.ConnectionCallbacks() {

    @Override
    public void onConnected(@Nullable final Bundle bundle) {
        findNodes();
    }

    @Override
    public void onConnectionSuspended(final int i) {
    }
};

这篇关于将字符串从手表发送到手机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆