安卓服务启动时间

标签 android service bind

我在实现一个简单的服务示例时遇到问题。 按照 Android 开发人员方案,我成功绑定(bind)到服务。该服务运行完美。

我想要实现的是服务的开始日期。我在

public class MyService extends Service {

    private Date _firstActivation= new Date();
    ....
    ....
    public Date GetFirstActivation() {
    return _firstActivation;
}
}

在绑定(bind)到服务的主要 Activity 中,我在 OnStart 方法期间有一个基本实现

 // Check if the Service is running and if it's running let's bind to the service through ServiceConnectionClass
    if (((MyApplication)getApplication())._serviceIsRunning)
    {
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, mConnection, 0);
        _startingTime_TV.setText(_df.format(_myService.GetFirstActivation()));
    }
    else {
        _startingTime_TV.setText("Service Not Started");
    }

其中 _myService 是 MyService,mConnection 是 ServiceConnection...

现在我期望的是,一旦服务第一次启动,每次我在 TextView 上停止 Activity (并同时取消绑定(bind))并重新启动 Activity (并同时绑定(bind))时,我都可以看到始终相同的开始时间。

每次我重新启动 Activity 时时间都会发生变化...

有人知道吗?

最佳答案

Service 的生命周期确定为: - 如果通过bindService启动,则在解除绑定(bind)时停止Service - 如果通过 startService 启动,则通过 stopService 停止,或者如果 Android 操作系统需要这样

所以首先:始终通过 startService 启动您的服务,然后绑定(bind)到它。 在您的绑定(bind)中,您可以执行以下操作: _startingTime_TV.setText(_df.format(_myService.GetFirstActivation())); 因为在 bindService(intent, mConnection, 0); 之后,您还没有绑定(bind)。您必须等待回调:onServiceConnected(ServiceConnection 的函数)

关于安卓服务启动时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012693/

相关文章:

Android:如何从原始短信中获取发件人和收件人的电话号码

android - 如何从以编程方式创建的微调器中获取位置

android - 如何获得可靠的 Broadcastreceiver

javascript - Angular.js - 使用服务需要回调

javascript - 使用新的构造函数绑定(bind)这样的参数?

java - 根据两个条件对列表进行排序

android - 如何在 AsyncTask 中举杯,提示我使用 Looper

c++ - boost::bind 返回一个函数对象,它是需要指针的函数的参数

symfony - 服务中的 Simfony2 服务尝试调用方法 "get"

c++ - 在 boost for_each 中运行成员函数 vector