我想将一条消息从移动应用程序发送到一个磨损应用程序,当磨损应用程序收到它时,它会显示一些UI活动。
我已经准备好了所有工作(移动应用程序正在使用Wearable.MessageApi.sendMessage,而磨损应用程序正在扩展WearableListenerService)。但是我的问题是,当我运行穿戴应用程序时,UI会在启动时出现,我应该更改什么,以便在磨损应用程序收到来自移动设备的消息之前不会显示任何内容?如何阻止在应用程序启动时创建活动?
清单:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.DeviceDefault" >
<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=".WearMessageListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
</application>
的活动:
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("WEAR", "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
}
}
服务:
public class WearMessageListenerService extends WearableListenerService {
private static final String START_ACTIVITY = "/start_activity";
@Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.i("WEAR", "WearableListenerService:onMessageReceived");
if( messageEvent.getPath().equalsIgnoreCase( START_ACTIVITY ) ) {
Intent intent = new Intent( this, MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( intent );
} else {
super.onMessageReceived(messageEvent);
}
}
}
答案 0 :(得分:3)
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
您已在主LAUNCHER
中的intent-filter
中设置了Activity
类别,这意味着此活动可以从启动器启动 - 在Android上它是按下后的位置在表盘上启动“现在说话”屏幕并向下滚动到开始... 。您将看到一个“可启动”应用程序列表,根据您的描述,这也是您想要避免的。
删除此intent-filter
后,请确保用户无法手动启动此Activity
,因此启动它的唯一方法是“当磨损应用程序收到来自移动设备的消息时” ,直接来自您的代码。
您的最终清单应如下所示:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.DeviceDefault" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
</activity>
<service android:name=".WearMessageListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>
</application>
如果您之前已定义,则Android Studio将不允许您在没有“默认活动”的情况下启动应用程序。您需要单击“编辑配置”,然后单击“磨损”模块,并在“常规”选项卡中选择“不启动活动”。
答案 1 :(得分:0)
不确定这是否是一种很好的方法,但您可以从服务中发送额外的意向。在活动的onCreate方法中,您可以检查是否已收到任何额外内容,如果没有,您的应用程序作为启动器活动启动,那么您可以使用finish()来销毁活动,否则如果您收到额外的,这意味着来自服务的电话会显示您要显示的内容。