最近在我的一个Wear OS(Android Wear)启用的应用程序中出现了一个错误,当可穿戴设备发送数据时,移动设备上的服务永远不会做出反应。
在排查根本原因时,我注意到永远不会调用 WearableListenerService 的 onCreate()方法。同样,从不调用Service超类中的 onStartCommand()方法,我认为这意味着Service确实没有运行。
服务在 AndroidManifest.xml 中定义,因此我无法理解为什么它不再运行。
以下是来自新项目的一些代码片段,我所做的就是定义 WearableListenerService 并尝试启动它。请注意,这是为了定义在移动设备上运行的服务:
WearMessageListenerService.java
package com.example.test.wearlistenertest;
import android.content.Intent;
import android.util.Log;
import com.google.android.gms.wearable.WearableListenerService;
public class WearMessageListenerService extends WearableListenerService {
@Override
public void onCreate() {
super.onCreate();
Log.v("test", "onCreate()");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("test", "onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
}
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test.wearlistenertest">
<application
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="com.example.test.wearlistenertest.WearMessageListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_LISTENER" />
<data android:scheme="wear" android:host="*" />
</intent-filter>
</service>
</application>
</manifest>
的build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.test.wearlistenertest"
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
compile 'com.google.android.gms:play-services-wearable:11.8.0'
}
上面的 Log.v()方法都没有在运行时输出任何内容。我已经在API 23和27上进行了测试。
我真的很感激这方面的一些帮助,因为我无法理解为什么我无法启动基本服务。我很乐意提供任何其他细节。非常感谢您提供的任何帮助。 - 亚伦
答案 0 :(得分:1)
在我看来,你的消息接收器的清单声明是错误的。这是我的一个应用程序中的一个:
<service android:name=".MyMessageListener"
android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data android:host="*" android:scheme="wear"
android:pathPrefix="@string/wear_path_prefix"/>
</intent-filter>
</service>
具体而言,请注意action
应以MESSAGE_RECEIVED
结尾(您的清单代之以MESSAGE_LISTENER
)。我认为这是关键问题,但导出服务并添加pathPrefix
也可能是好主意。