我应该使用什么样的服务在后台访问传感器的数据?

问题描述 投票:0回答:1

我成功地使用的服务做在前台某项任务。现在,这样做的背景下,我会删除handler.removeCallbacksonDestroy()方法。

但是,这也使我不能停止使用stopService(intent)服务。

我在电视上看到我也许应该使用的jobscheduler(因为我的目标API 28)的官方文档。

这里是我的代码更精确的指示:

public class MainActivity {
    private Intent intent;    
    onCreate() {
        if (intent == null) {
            intent = new Intent(this, MyService.class);
        }
    }
    startService(intent);
    ... // Then is some code to  stop the service if needed with  stopService(intent)
}
--------------------------------------------------------------
public class myService {
    private Handler handler = null;
    private static Runnable runnable = null;
    @Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("Running service times " + i);
            i++;
            handler.postDelayed(runnable, 1000);
        }
    };
    handler.post(runnable);
}

@Override
public void onDestroy() {
    handler.removeCallbacks(runnable);
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
}

我想它在后台运行(即使设备处于锁定状态),但仍然能够禁用该服务(或的jobscheduler?)。

你有什么建议?

android wear-os
1个回答
1
投票

您可以使用work manager

job dispatcher

并且有很多像SyncAdapter选项,绑定服务,服务意向

您可以根据自己的需要使用这些选项之一

© www.soinside.com 2019 - 2024. All rights reserved.