我想从移动应用向 Wear 应用发送一条消息,当 Wear 应用接收到它以显示一些 UI Activity 时。
我已准备就绪并为此工作(移动应用程序正在使用 Wearable.MessageApi.sendMessage 并且穿戴式应用程序正在扩展 WearableListenerService)。但是我的问题是,当我运行 wear 应用程序时,UI 在启动时出现,我应该更改什么以便在 wear 应用程序收到来自移动设备的消息之前不显示任何内容?如何防止在应用启动时创建 Activity?
list :
<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>
Activity :
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);
}
}
}
最佳答案
list 中的变化
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
您已在主 Activity
中的 intent-filter
中设置了 LAUNCHER
类别,这意味着可以从启动器启动此 Activity - on Android Wear 它是按下表盘启动“现在说话”屏幕并向下滚动到开始... 后的地方。您会在那里看到“可启动”应用程序的列表,根据您的描述,这也是您要避免的。
通过删除此 intent-filter
,您可以确保用户无法手动启动此 Activity
,因此启动它的唯一方法是“当佩戴时应用程序直接从您的代码接收来自手机的消息”。
您的最终 list 应如下所示:
<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>
配置的变化
如果您之前定义了“默认 Activity ”,Android Studio 将不允许您启动没有“默认 Activity ”的应用程序。您需要点击“编辑配置”,然后点击“穿戴”模块并在“常规”选项卡中选择“不启动 Activity ”。
关于android - 如何防止服务应用程序在启动时启动其 ui Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28077966/