【发布时间】:2017-02-05 22:22:26
【问题描述】:
我正在处理可穿戴设备,我的目的是下一个:
在我的手表上,我想按一个简单的按钮,向手机发送一条简单的消息。但我想处理所有这些行为:
- 当移动应用尚未启动时,启动应用并传递来自 Wear 的消息,可在启动器活动中处理
- 当移动应用程序在后台启动时,只需将其带到前台并处理来自磨损的消息,这可以在启动器活动中处理
- 当移动应用程序在前台启动时,只需在启动器活动中处理消息
到目前为止,我处理尚未启动的应用程序,但我无法在 intent 中包含的启动器活动中获得 额外消息时间>。代码在这里。
移动服务
public class MobileWearService extends WearableListenerService {
private static final String START_ACTIVITY = "/start_activity";
@Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
String event = messageEvent.getPath();
String msg = new String(messageEvent.getData());
if (event.equals(START_ACTIVITY)) {
Intent intent = new Intent( this, MainActivity.class );
intent.putExtra("Data", msg);
intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity( intent );
}
}
}
但是,如果我使用广播将消息从服务发送到主要活动,则它仅在应用程序启动和前台时才有效
public class MobileWearService extends WearableListenerService {
private static final String START_ACTIVITY = "/start_activity";
@Override
public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
String event = messageEvent.getPath();
String msg = new String(messageEvent.getData());
if (event.equals(START_ACTIVITY)) {
broadcastIntent.setAction("com.me.project.wear.to.app");
broadcastIntent.putExtra("Data", msg);
broadcastIntent.putExtras(intent);
sendBroadcast(broadcastIntent);
}
}
}
启动器活动
private IntentFilter mIntentFilter = new IntentFilter("com.me.project.wear.to.app");
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction().equals("com.me.project.wear.to.app")) {
String msg = intent.getStringExtra("Data");
}
}
};
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
因此,我会结合这一事实从磨损中获取消息(我知道如何),但无论应用程序的状态如何,都会传递此消息以在启动器活动中获取它。
【问题讨论】:
标签: android android-intent broadcastreceiver wear-os