如何 运行 服务 android 永远穿

How to run a Service in an android wear forever

我正在尝试创建一项服务(在智能手表中),即使用户没有使用该应用程序,它也应该 运行 永远。主要目的是将该服务用于语音识别。因此,每当用户说出特定单词时,应用程序应该能够像 google 语音一样做出响应。

然而,出于测试目的,我在日志中打印了一个整数,但它只执行了一次。这意味着该服务不会永远 运行ning。

我的服务代码:

public class VoiceService extends Service {

private IBinder mBinder = new VoiceBinder();
int i = 1;
public VoiceService() {
}

@Override
public void onCreate() {
    super.onCreate();
    updateLog();
}

public void updateLog() {
    ++i;
    Log.v("DATA", Integer.toString(i));
}
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    return mBinder;
}


//inner helper class
public class VoiceBinder extends Binder {

    //constructor
    VoiceService getService() {
        return VoiceService.this;
    }
}
}

我的 MainActivity 代码:

serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            VoiceService.VoiceBinder binder = (VoiceService.VoiceBinder) iBinder;
            iBinder = (IBinder) binder.getService();
            MainActivity.this.voiceService = ((VoiceService.VoiceBinder)iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            voiceService = null;
        }
    };

    //bind service
    bindService(new Intent(this, VoiceService.class), serviceConnection, getApplicationContext().BIND_AUTO_CREATE);
    startService(new Intent(this, VoiceService.class));

AndroidManifest:

<service
        android:name=".VoiceService"
        android:enabled="true"
        android:exported="false">

    </service>

我的输出:

12-20 22:27:20.307 23624-23624/? V/DATA: 2

您可能想要浏览 Running in a Background Service 其中提到

Long-running foreground operations can cause problems and interfere with the responsiveness of your user interface, which annoys your users and can even cause system errors. To avoid this, the Android framework offers several classes that help you off-load operations onto a separate thread that runs in the background. The most useful of these is IntentService.

并且,还要注意:

If your app targets Android 5.0 (API level 21), you should use JobScheduler to execute background services.

为了获得最佳应用程序性能并最大程度地减少电池消耗,您可能还需要检查以下链接: