Stop/Pause/Sleep 如果连接不可用则服务,如果可用则恢复

Stop/Pause/Sleep Service if connection unavailable and resume if available

我有一个应用程序,我在其中创建了一项服务 MyService.class 现在 MyService.class 使用 bindService() 与我的 activity 绑定,但我希望我的服务在后台为 运行 即使 activity 自行销毁。

所以我启动了服务,然后像下面这样绑定它:

private void doBindService() {
  if (!isServiceBound){
    Log.d(LOG_TAG, "Binding Service...");
    if (mBtAdapter != null && mBtAdapter.isEnabled()){
      Intent intent = new Intent(MyActivity.this, MyService.class);
      startService(intent);
      bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
  }
}

在 MyActivity 的 onDestroy 方法中,我解除绑定服务

现在我的服务 运行 正在顺利进行,直到与远程设备的连接中断。如果连接中断,我想 pause/sleep/stop 此服务,然后每隔 60 秒它会尝试启动 service/connection。

我已经试过了,但是没有用。

private void stopService() {
    doUnbindService();
    stopService(new Intent(MyActivity.this, MyService.class));
    startService(new Intent(MyActivity.this, MyService.class));
}

如有任何帮助,我们将不胜感激。提前致谢!!!

试试这个

  • 创建一个方法来执行您想要的操作
  • 创建线程或 Runnable class
  • 调用您在 Thread 或 Runnable 的 运行() 中创建的 Helper 方法
  • 如果连接可用,在服务 onStartCommand 中启动线程
  • 线程。wait/sleep如果没有连接

我不确定我是否理解您的请求。

使用此解决方案,您可以播放、暂停和停止服务。 服务每 60 秒做一些工作

public class MyService extends Service {

    public static boolean testConnexion;

    private Timer timer;

    @Override
    public void onCreate() {
        super.onCreate();
        timer = null;
        testConnexion = true;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (timer != null) {
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    if (testConnexion) {
                        //StartConnexion
                    }
                }
            }, 1000, 60000);
        }

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}

任意 activity 启动或停止服务。 (你可以多次调用startService,只有一个会运行。)

if (v.getId() == R.id.startService) {
            Intent intent = new Intent(this, MyService.class);
            startService(intent);
        } else if (v.getId() == R.id.stopService) {
            Intent intent = new Intent(this, MyService.class);
            stopService(intent);
        }

暂停操作(但不终止服务)

MyService.testConnexion = false;

并重新启动

MyService.testConnexion = true;

您的服务与您的 activity 无关。 如果您杀死 activity,您的服务将继续 运行。

希望对您有所帮助