带有计时器的服务调用另一个服务

Service with Timer calling another Service

我正在使用 Service 管理从 服务器到客户端 客户端到服务器 的数据。因为我在登录后调用一个 Service:

context.startService(new Intent(LoginActivity.this, CheckAutoSyncReceivingOrder.class));
context.startService(new Intent(LoginActivity.this, CheckAutoSyncSendingOrder.class));

我在上面都调用了一个计时器Service

CheckAutoSyncReceivingOrder 服务:

Its calling another service named ReceivingOrderService on Every 1 minute to get updated data from server.

public class CheckAutoSyncReceivingOrder extends Service {

    Timer timer;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        Log.i(TAG, "CheckAutoSyncReceivingOrder Binding Service...");
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub

        if (timer != null) {
            timer.cancel();
            Log.i(TAG, "RECEIVING OLD TIMER CANCELLED>>>");
        }

        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG, "<<<<<<<<< RECEIVING AUTO SYNC SERVICE <<<<<<<<");
                if (InternetConnection.checkConnection(getApplicationContext())) {
                    if (getDatabasePath(DatabaseHelper.DATABASE_NAME).exists())
                        startService(new Intent(
                                CheckAutoSyncReceivingOrder.this,
                                ReceivingOrderService.class));
                } else {
                    Log.d(TAG, "Connection not available");
                }
            }
        }, 0, 60000); // 1000*60 = 60000 = 1 minutes
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub

        if (timer != null)
            timer.cancel();

        Log.d(TAG, "Stopping Receiving...");

        super.onDestroy();
    }
}

CheckAutoSyncSendingOrder 服务:

Its calling another service named SendingOrderService on Every 2.5 minute to send updated data to server.

public class CheckAutoSyncSendingOrder extends Service {

    Timer timer;

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub

        if (timer != null) {
            timer.cancel();
            Log.i(TAG, "OLD TIMER CANCELLED>>>");
        }

        timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG, ">>>>>>>> SENDING AUTO SYNC SERVICE >>>>>>>>");
                if (InternetConnection.checkConnection(getApplicationContext())) {
                    if (getDatabasePath(DatabaseHelper.DATABASE_NAME).exists())
                        startService(new Intent(CheckAutoSyncSendingOrder.this,
                                SendingOrderService.class));
                } else {
                    Log.d(TAG, "connection not available");
                }
            }
        }, 0, 150000); // 1000*60 = 60000 = 1 minutes * 2.5 = 2.5 =>Minutes
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub

        if (timer != null)
            timer.cancel();

        Log.d(TAG, "Stopping Sending...");

        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

两者 Activity 都会 运行 直到网络关闭。它会在 Internet 连接可用时自动再次调用。

主要是我遇到了问题在自动销毁activity 服务调用时

是否有任何解决方案或方法可以改变同一事物的流程?

提前谢谢。

来自documentation

When a service is started, it has a lifecycle that's independent of the component that started it and the service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is done by calling stopSelf(), or another component can stop it by calling stopService().

由于您 "dont have overrides any other methods excepting onCreate()" 在问题 Activity 中,您可能会遇到以下情况:

  1. ServiceonDestroy() 不会被调用,除非另一个应用程序组件调用 stopService();
  2. 这导致 Timer 继续执行它的工作。

根据文档停止服务。

编辑(针对您的评论):

"its starting new job when i destroy activity" 表示系统终止了该服务,并且由于您没有覆盖 onStartCommand(),其默认 return 值为 START_STICKY,已重新创建服务并已调用其 onStart() 方法。

不能改变这样的系统行为。但是您可以 运行 foreground 中的服务。

您必须使用 IntentService 而不是 Service

  • Service 在后台运行,但它在应用程序的主线程上运行。
  • IntentService 在单独的工作线程上运行。

如果运行您的服务的进程被终止,Android 系统将自动重启它,这是默认行为。

因此,如果 Activity 的主线程被破坏,服务将重新启动,但如果您使用 IntentService 并使用 START_NOT_STICKY,则它不会重新启动您的服务。

此行为由您的服务实现中 onStartCommand() 的 return 值定义。常量 START_NOT_STICKY 告诉 Android 如果它是 运行 而进程是 "killed".

不要重新启动服务

您需要覆盖服务 class 中的方法 onStartCommand() 并将所有代码从 onStart() 方法移动到 onStartCommand() 方法。

根据 Android 文档:

For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them

onStart() 方法每次在服务重新启动时调用,但 onStartCommand() 方法不会被调用,如果你 return START_NON_STICKY.

有关 IntentServiceService 之间差异的更多详细信息。你可以查看 this.

希望对您有所帮助。